query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
UnmarshalJSON supports json.Unmarshaler interface
func (v *BlitzedItemResponse) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjson6a975c40DecodeJsonBenchmark4(&r, v) return r.Error() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (j *jsonNative) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func unmarshalJSON(j extv1.JSON, output *any) error {\n\tif len(j.Raw) == 0 {\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(j.Raw, output)\n}", "func (j *JSON) Unmarshal(input, target interface{}) error {\n\t// take the input and convert it to target\n\treturn jsonEncoding.Unmarshal(input.([]byte), target)\n}", "func (j *Publisher) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *OneLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneLike(&r, v)\n\treturn r.Error()\n}", "func UnmarshalJSON(data []byte, v interface{}) {\n\terr := json.Unmarshal(data, v)\n\tAbortIf(err)\n}", "func jsonUnmarshal(r io.Reader, o interface{}, opts ...JSONOpt) error {\n\td := json.NewDecoder(r)\n\tfor _, opt := range opts {\n\t\td = opt(d)\n\t}\n\tif err := d.Decode(&o); err != nil {\n\t\treturn fmt.Errorf(\"while decoding JSON: %v\", err)\n\t}\n\treturn nil\n}", "func UnmarshalJSON(b []byte, discriminator string, f Factory) (interface{}, error) {\n\tm := make(map[string]interface{})\n\terr := json.Unmarshal(b, &m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn Decode(m, discriminator, f)\n}", "func UnmarshalFromJSON(data []byte, target interface{}) error {\n\tvar ctx map[string]interface{}\n\terr := json.Unmarshal(data, &ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn Unmarshal(ctx, target)\n}", "func (s *Serializer) Unmarshal(data []byte, v interface{}) error {\n\treturn jsoniter.Unmarshal(data,v)\n}", "func (j *ThirdParty) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func unmarshal() {\n\tfmt.Println(\"=== json.unmarshal ===\")\n\tvar jsonBlob = []byte(`[\n\t\t{\"name\": \"Bill\", \"age\": 109},\n\t\t{\"name\": \"Bob\", \"age\": 5}\n\t]`)\n\n\tvar persons []Person\n\terr := json.Unmarshal(jsonBlob, &persons)\n\tcheck(err)\n\n\tfmt.Printf(\"%+v\\n\", persons)\n}", "func (j *Data) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *JsonMarshaler) Unmarshal(data []byte, v interface{}) error {\n\treturn json.Unmarshal(data, v)\n}", "func (j *Type) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (this *Simple) UnmarshalJSON(b []byte) error {\n\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (j *Response) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (pl PLUtil) Unmarshal(data []byte, v interface{}) error {\n\tcmd := pl.execCommand(\n\t\t\"plutil\",\n\t\t\"-convert\", \"json\",\n\t\t// Read from stdin.\n\t\t\"-\",\n\t\t// Output to stdout.\n\t\t\"-o\", \"-\")\n\tcmd.Stdin = bytes.NewReader(data)\n\tstdout, err := cmd.Output()\n\tif exitErr, ok := err.(*exec.ExitError); ok {\n\t\treturn fmt.Errorf(\"`%s` failed (%w) with stderr: %s\", cmd, err, exitErr.Stderr)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"`%s` failed (%w)\", cmd, err)\n\t}\n\tif err := json.Unmarshal(stdout, v); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse json: %w\", err)\n\t}\n\treturn nil\n}", "func (j *LuaFunction) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func Unmarshal(data []byte, v Unmarshaler) error {\n\tl := jlexer.Lexer{Data: data}\n\tv.UnmarshalTinyJSON(&l)\n\treturn l.Error()\n}", "func (j *Producer) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *User) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *Json) UnmarshalJSON(b []byte) error {\n\tr, err := loadContentWithOptions(b, Options{\n\t\tType: ContentTypeJson,\n\t\tStrNumber: true,\n\t})\n\tif r != nil {\n\t\t// Value copy.\n\t\t*j = *r\n\t}\n\treturn err\n}", "func (j *Error) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *Element) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB83d7b77DecodeGoplaygroundMyjson2(&r, v)\n\treturn r.Error()\n}", "func (j *Message) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func jsonDecode(reader io.ReadCloser, v interface{}) error {\n\tdecoder := json.NewDecoder(reader)\n\terr := decoder.Decode(v)\n\treturn err\n}", "func (j *FactoryPluginRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (m *gohaiMarshaler) UnmarshalJSON(bytes []byte) error {\n\tfirstUnmarshall := \"\"\n\terr := json.Unmarshal(bytes, &firstUnmarshall)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal([]byte(firstUnmarshall), &(m.gohai))\n\treturn err\n}", "func (j *Packet) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (receiver *Type) UnmarshalJSON(src []byte) error {\n\tif nil == receiver {\n\t\treturn errNilReceiver\n\t}\n\n\tvar s string\n\tif err := json.Unmarshal(src, &s); nil != err {\n\t\treturn err\n\t}\n\n\tif err := receiver.Scan(s); nil != err {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (j *qProxyClient) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func Unmarshal(data []byte, v Unmarshaler) error {\n\tl := jlexer.Lexer{Data: data}\n\tv.UnmarshalEasyJSON(&l)\n\treturn l.Error()\n}", "func (j *TextMarshaler) Unmarshal(data []byte, v interface{}) error {\n\treturn json.Unmarshal(data, v)\n}", "func (w *Entry) UnmarshalJSON(bb []byte) error {\n\t<<!!YOUR_CODE!!>>\n}", "func UnmarshalJSON(body io.Reader, v interface{}) error {\n\tdecoder := json.NewDecoder(body)\n\treturn decoder.Decode(v)\n}", "func Unmarshal(data []byte) (interface{}, error) {\n\tvar value marble\n\terr := json.Unmarshal(data, &value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &value, nil\n}", "func (j *RunPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (i *Transform) UnmarshalJSON(data []byte) error {\n\tvar s string\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn fmt.Errorf(\"Transform should be a string, got %[1]s\", data)\n\t}\n\n\tvar err error\n\t*i, err = ParseTransformString(s)\n\treturn err\n}", "func (this *Service) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (v *OneUpdateLike) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\tdecodeOneUpdateLike(&r, v)\n\treturn r.Error()\n}", "func (j *RunRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *Raw) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer10(&r, v)\n\treturn r.Error()\n}", "func (j *Server) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *JSONText) Unmarshal(v interface{}) error {\n\treturn json.Unmarshal([]byte(*j), v)\n}", "func (j *JsonlMarshaler) Unmarshal(data []byte, v interface{}) error {\n\treturn json.Unmarshal(data, v)\n}", "func (j *PublishMessagesResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *Event) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *FactoryPluginPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j JSON) Unmarshal(dest interface{}) error {\n\tif dest == nil {\n\t\treturn errors.New(\"destination is nil, not a valid pointer to an object\")\n\t}\n\n\t// Call our implementation of\n\t// JSON MarshalJSON through json.Marshal\n\t// to get the value of the JSON object\n\tres, err := json.Marshal(j)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(res, dest)\n}", "func (v *User) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson9e1087fdDecodeHw3Bench(&r, v)\n\treturn r.Error()\n}", "func Unmarshal(data []byte, v interface{}) error {\n\terr := json.Unmarshal(data, v)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif ImplementsPostJSONUnmarshaler(v) {\n\t\terr := v.(PostJSONUnmarshaler).PostUnmarshalJSON()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func FromJSON(i interface{}, r io.Reader) error {\n\td := json.NewDecoder(r)\n\treturn d.Decode(i)\n}", "func (v *FormulaAndFunctionResponseFormat) UnmarshalJSON(src []byte) error {\n\tvar value string\n\terr := json.Unmarshal(src, &value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*v = FormulaAndFunctionResponseFormat(value)\n\treturn nil\n}", "func (j *GetMessagesResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *RespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (f genHelperDecoder) DecJSONUnmarshal(tm jsonUnmarshaler) {\n\tf.d.jsonUnmarshalV(tm)\n}", "func (j *LuaTable) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *Regulations) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *User) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson2bc03518DecodeLangTaskOnBench(&r, v)\n\treturn r.Error()\n}", "func Unmarshal(b []byte, v interface{}) error {\n\treturn json.Unmarshal(b, v)\n}", "func (v *UnloadCheckResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark(&r, v)\n\treturn r.Error()\n}", "func (this *DeploymentStrategy) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (j *LuaInt) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *Visit) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel1(&r, v)\n\treturn r.Error()\n}", "func (u *Unstructured) UnmarshalJSON(b []byte) error {\n\t_, _, err := UnstructuredJSONScheme.Decode(b, nil, u)\n\treturn err\n}", "func UnmarshalJSON(b []byte) (dgo.Value, error) {\n\tdec := json.NewDecoder(bytes.NewReader(b))\n\tdec.UseNumber()\n\treturn jsonDecodeValue(dec)\n}", "func unmarshal(data []byte, v interface{}) {\n\terr := json.Unmarshal(data, v)\n\tassert(err == nil, \"unmarshal error: %s\", err)\n}", "func (j *Balance) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (t *Type) UnmarshalJSON(b []byte) error {\n\tvar text string\n\tif err := json.Unmarshal(b, &text); err != nil {\n\t\treturn err\n\t}\n\n\treturn t.UnmarshalText([]byte(text))\n}", "func JSONDecode(ctx context.Context, data []byte, obj interface{}) error {\n\treturn json.Unmarshal(data, obj)\n}", "func (j *RegisterRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *ListPluginRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (this *Probe) UnmarshalJSON(b []byte) error {\n\treturn CommonUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (j *BootInitiationRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (v *VisitArray) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel(&r, v)\n\treturn r.Error()\n}", "func (v *ExportItem) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjsonB83d7b77DecodeGoplaygroundMyjson1(&r, v)\n\treturn r.Error()\n}", "func (this *ImportedReference) UnmarshalJSON(b []byte) error {\n\treturn TypesUnmarshaler.Unmarshal(bytes.NewReader(b), this)\n}", "func (j *LuaString) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (jz JSONGzipEncoding) Unmarshal(data []byte, value interface{}) error {\n\tjsonData, err := GzipDecode(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(jsonData, value)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (v *ItemCheckResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark2(&r, v)\n\treturn r.Error()\n}", "func (i *Interface) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", i, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"etag\":\n\t\t\terr = unpopulate(val, \"Etag\", &i.Etag)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"extendedLocation\":\n\t\t\terr = unpopulate(val, \"ExtendedLocation\", &i.ExtendedLocation)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"id\":\n\t\t\terr = unpopulate(val, \"ID\", &i.ID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"location\":\n\t\t\terr = unpopulate(val, \"Location\", &i.Location)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &i.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"properties\":\n\t\t\terr = unpopulate(val, \"Properties\", &i.Properties)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"tags\":\n\t\t\terr = unpopulate(val, \"Tags\", &i.Tags)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"type\":\n\t\t\terr = unpopulate(val, \"Type\", &i.Type)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", i, err)\n\t\t}\n\t}\n\treturn nil\n}", "func Unmarshal(data []byte, typ DataFormat, target interface{}) {\n\tswitch typ {\n\tcase GOB:\n\t\tbuf := bytes.NewReader(data)\n\t\tgob.NewDecoder(buf).Decode(target)\n\n\tdefault:\n\t\tif err := json.Unmarshal(data, target); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (j *Json) UnmarshalJSON(data []byte) error {\n\terr := json.Unmarshal(data, &j.data)\n\n\tj.exists = (err == nil)\n\treturn err\n}", "func (v *PbTestObject) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson5fcf962eDecodeGithubComJsonIteratorGoBenchmarkWith10IntFields(&r, v)\n\treturn r.Error()\n}", "func (j *ModifyQueueResponse) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *UnInstallRespPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func unmarshalJSON(i *big.Int, bz []byte) error {\n\tvar text string\n\terr := json.Unmarshal(bz, &text)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn i.UnmarshalText([]byte(text))\n}", "func (j *LuaBool) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (j *WorkerCreateOperation) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func jsonDec(t reflect.Type, in []byte) (T, error) {\n\tval := reflect.New(t)\n\tif err := jsonx.Unmarshal(val.Interface(), in); err != nil {\n\t\treturn nil, err\n\t}\n\treturn val.Elem().Interface(), nil\n}", "func (z *Int) UnmarshalJSON(text []byte) error {}", "func (j *PeerInfo) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func (obj *miner) UnmarshalJSON(data []byte) error {\n\tins := new(JSONMiner)\n\terr := json.Unmarshal(data, ins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpr, err := createMinerFromJSON(ins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinsMiner := pr.(*miner)\n\tobj.toTransact = insMiner.toTransact\n\tobj.queue = insMiner.queue\n\tobj.broadcasted = insMiner.broadcasted\n\tobj.toLink = insMiner.toLink\n\treturn nil\n}", "func (j *UnInstallPacket) UnmarshalJSON(input []byte) error {\n\tfs := fflib.NewFFLexer(input)\n\treturn j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)\n}", "func deJSONify(i interface{}) (interface{}, error) {\n\tvar data []byte\n\tswitch t := i.(type) {\n\tcase string:\n\t\tdata = []byte(t)\n\tcase []byte:\n\t\tdata = t\n\tcase json.RawMessage:\n\t\tdata = []byte(t)\n\tdefault:\n\t\treturn i, nil\n\t}\n\tvar x interface{}\n\tif err := json.Unmarshal(data, &x); err != nil {\n\t\treturn nil, &kivik.Error{HTTPStatus: http.StatusBadRequest, Err: err}\n\t}\n\treturn x, nil\n}", "func (v *DocumentResponse) UnmarshalJSON(data []byte) error {\n\tr := jlexer.Lexer{Data: data}\n\teasyjson6a975c40DecodeJsonBenchmark3(&r, v)\n\treturn r.Error()\n}", "func (c *JSONCodec) Unmarshal(data []byte, v interface{}) error {\n\treturn json.Unmarshal(data, v)\n}", "func NewJSONUnmarshaler(resolver Resolver) Unmarshaler {\n\treturn newJSONUnmarshaler(resolver)\n}", "func NewJSONUnmarshaler(resolver Resolver) Unmarshaler {\n\treturn newJSONUnmarshaler(resolver)\n}" ]
[ "0.70113605", "0.698139", "0.6947301", "0.6867781", "0.68005323", "0.67680764", "0.6741481", "0.67051035", "0.6688701", "0.66797084", "0.6676911", "0.6669605", "0.6661001", "0.66579056", "0.6652777", "0.66498846", "0.6632663", "0.663189", "0.6627629", "0.6612909", "0.6587119", "0.65519077", "0.6545157", "0.6537283", "0.6533197", "0.6532074", "0.6526187", "0.6518123", "0.6512875", "0.6505786", "0.64908326", "0.64847505", "0.64830405", "0.64820194", "0.6469316", "0.64528453", "0.64508975", "0.6441661", "0.6441397", "0.6438974", "0.6438737", "0.642948", "0.6408435", "0.640738", "0.6396278", "0.6394157", "0.6385808", "0.63855124", "0.63844603", "0.6375449", "0.63702816", "0.63625103", "0.63553596", "0.63552856", "0.63477194", "0.6344893", "0.6339914", "0.6331977", "0.63298523", "0.6323917", "0.63238263", "0.6318712", "0.631284", "0.63110864", "0.6310182", "0.6305762", "0.63040566", "0.62972116", "0.62931895", "0.6291462", "0.62913823", "0.62810636", "0.6280757", "0.6274565", "0.6273215", "0.62724316", "0.62711626", "0.6271133", "0.62660044", "0.6263724", "0.62590677", "0.62587553", "0.62568384", "0.6255846", "0.6252581", "0.62471205", "0.6244156", "0.6241776", "0.62323636", "0.62298375", "0.6226608", "0.6226587", "0.62243664", "0.6220156", "0.6218001", "0.6216062", "0.6215216", "0.621471", "0.62088907", "0.62088907" ]
0.66243863
19
UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *BlitzedItemResponse) UnmarshalEasyJSON(l *jlexer.Lexer) { easyjson6a975c40DecodeJsonBenchmark4(l, v) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (v *Fruit) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeBackendInternalModels11(l, v)\n}", "func (v *Boo) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeMsgpJson(l, v)\n}", "func (v *Element) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB83d7b77DecodeGoplaygroundMyjson2(l, v)\n}", "func (c *Context) UnmarshalEasyJSON(in *jlexer.Lexer) {\n\tContextSerialization.UnmarshalFromEasyJSONLexer(in, c)\n}", "func (v *Format) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson14(l, v)\n}", "func (v *DetectedFruit) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeBackendInternalModels12(l, v)\n}", "func (v *item) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeGithubComZhekabyGoGeneratorMongoRequestwrapperTests(l, v)\n}", "func (v *ItemCheckResponse) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6a975c40DecodeJsonBenchmark2(l, v)\n}", "func (v *Native) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson10(l, v)\n}", "func (v *FormDataMQ) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB83d7b77DecodeGoplaygroundMyjson(l, v)\n}", "func (v *DocumentResponse) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6a975c40DecodeJsonBenchmark3(l, v)\n}", "func (v *Node) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6601e8cdDecodeGithubComSkydiveProjectSkydiveGraffitiApiTypes1(l, v)\n}", "func (v *flattenedField) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson390b7126DecodeGithubComChancedPicker35(l, v)\n}", "func (v *ExtFilter) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson795c59c6DecodeGrapeGuardRules11(l, v)\n}", "func (v *Deal) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson8a221a72DecodeGithubComVungleVungoOpenrtb(l, v)\n}", "func (v *OrderCheckResponse) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6a975c40DecodeJsonBenchmark1(l, v)\n}", "func (v *Visit) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel1(l, v)\n}", "func (v *Error) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer26(l, v)\n}", "func (v *GetUserResponse) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson84c0690eDecodeMainHandlers1(l, v)\n}", "func (v *User) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson9e1087fdDecodeHw3Bench(l, v)\n}", "func (v *IngredientArr) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeBackendInternalModels7(l, v)\n}", "func (v *VisitArray) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonE564fc13DecodeGithubComLa0rgHighloadcupModel(l, v)\n}", "func (v *Foo) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonAbe23ddeDecodeGithubComUberZanzibarExamplesExampleGatewayBuildGenCodeClientsCorgeCorge1(l, v)\n}", "func (v *Ingredient) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeBackendInternalModels8(l, v)\n}", "func (v *Musician) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson62dc445bDecode20211NoskoolTeamInternalAppMusiciansModels2(l, v)\n}", "func (v *ThirdParty) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson2(l, v)\n}", "func (v *Data) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson17(l, v)\n}", "func (v *Deal) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson16(l, v)\n}", "func (v *Raw) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer10(l, v)\n}", "func (v *EasyResponse) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6ff3ac1dDecodeGithubComWenweihBitcoinRpcGolangProto1(l, v)\n}", "func (v *AdvFormData) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB83d7b77DecodeGoplaygroundMyjson3(l, v)\n}", "func (v *Message) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer18(l, v)\n}", "func (v *Teacher) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonF1627ba7DecodeGithubComDuchiporexiaGoutilsXmsgTests(l, v)\n}", "func (v *Invite) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer22(l, v)\n}", "func (v *CBPerson) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonE242b40eDecodeGithubComExampleSample2(l, v)\n}", "func (v *BidResponse) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson326edDecodeGithubComMxmCherryOpenrtb(l, v)\n}", "func (v *BidRequest) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson21(l, v)\n}", "func (v *Impression) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson12(l, v)\n}", "func (v *Msg) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeBackendInternalModels6(l, v)\n}", "func (v *BidResponse) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson326edDecodeGithubComApplifierGoOpenrtbOpenrtb2(l, v)\n}", "func (v *Info) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonC80ae7adDecodeGithubComDeiklovTechDbRomanovAndrGolangModels13(l, v)\n}", "func (v *MediumPayload) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonE242b40eDecodeGithubComExampleSample1(l, v)\n}", "func (v *Part) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer12(l, v)\n}", "func (v *ProductExtendedArr) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeBackendInternalModels4(l, v)\n}", "func (v *Whois) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer1(l, v)\n}", "func (v *App) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson25(l, v)\n}", "func (v *Content) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson18(l, v)\n}", "func (v *Responce) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6a975c40DecodeGithubComSerhio83DruidPkgStructs(l, v)\n}", "func (v *TransactionResponse) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonE82c8e88DecodeGithubComKamaiuOandaGoModel5(l, v)\n}", "func (v *ProductExtended) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeBackendInternalModels5(l, v)\n}", "func (v *Error) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonC5a4559bDecodeGithubComChromedpCdproto2(l, v)\n}", "func (v *BidResponse) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson20(l, v)\n}", "func (v *HireManager) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonAf94a8adDecodeGithubComGoParkMailRu20192ComandusInternalModel(l, v)\n}", "func (v *PlantainerShadowMetadataSt) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson5bd79fa1DecodeMevericcoreMcplantainer9(l, v)\n}", "func (v *User) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeBackendInternalModels(l, v)\n}", "func (v *RespStruct) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeDrhyuComIndexerModels1(l, v)\n}", "func (v *Item) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonD2b7633eDecodeDrhyuComIndexerModels2(l, v)\n}", "func (v *Annotation) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6a975c40DecodeGithubComSerhio83DruidPkgStructs3(l, v)\n}", "func (v *Fundamental) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca14(l, v)\n}", "func (v *BasicUser) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6601e8cdDecodeJsongen4(l, v)\n}", "func (v *Features) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer25(l, v)\n}", "func (v *Edge) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6601e8cdDecodeGithubComSkydiveProjectSkydiveGraffitiApiTypes2(l, v)\n}", "func (v *ShadowModelSt) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon5(l, v)\n}", "func (v *AdvForm) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB83d7b77DecodeGoplaygroundMyjson4(l, v)\n}", "func (v *binaryField) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson390b7126DecodeGithubComChancedPicker46(l, v)\n}", "func (v *ShadowUpdateMsgSt) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB7ed31d3DecodeMevericcoreMccommon1(l, v)\n}", "func (v *User) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson393a2a40DecodeCodegen(l, v)\n}", "func (v *InfoUser) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6601e8cdDecodeJsongen3(l, v)\n}", "func (v *Message) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonC5a4559bDecodeGithubComChromedpCdproto1(l, v)\n}", "func (v *Pmp) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson9(l, v)\n}", "func (v *MOTD) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer19(l, v)\n}", "func (v *Attack) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6601e8cdDecodeGithubComGoParkMailRu2018242GameServerTypes4(l, v)\n}", "func (v *moreLikeThisQuery) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson390b7126DecodeGithubComChancedPicker18(l, v)\n}", "func (v *ExportItem) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB83d7b77DecodeGoplaygroundMyjson1(l, v)\n}", "func (v *EventLoadEventFired) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonC5a4559bDecodeGithubComChromedpCdprotoPage70(l, v)\n}", "func (v *managerListener) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonEd74d837DecodeGithubComKihamoBoggartComponentsBoggartInternalHandlers(l, v)\n}", "func (v *WSResponse) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer2(l, v)\n}", "func (v *UnloadCheckResponse) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson6a975c40DecodeJsonBenchmark(l, v)\n}", "func (v *PbTestObject) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson5fcf962eDecodeGithubComJsonIteratorGoBenchmarkWith10IntFields(l, v)\n}", "func (v *Student) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonF1627ba7DecodeGithubComDuchiporexiaGoutilsXmsgTests1(l, v)\n}", "func (v *Device) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson15(l, v)\n}", "func (v *Messages) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer17(l, v)\n}", "func (v *User) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson2bc03518DecodeLangTaskOnBench(l, v)\n}", "func (v *BaseTickerInfo) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi117(l, v)\n}", "func (v *Topic) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson42239ddeDecodeGithubComKhliengDispatchServer5(l, v)\n}", "func (v *BaseLedgerInfo) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi127(l, v)\n}", "func (v *Banner) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson23(l, v)\n}", "func (v *APIError) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson3e8ab7adDecodeGithubComAlpacahqAlpacaTradeApiGoV3Alpaca24(l, v)\n}", "func (v *Bid) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson22(l, v)\n}", "func (v *Post) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson783c1624DecodeGithubComGobwasVk7(l, v)\n}", "func (v *BaseTradeInfo) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi116(l, v)\n}", "func (v *MusicianFullInformation) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson62dc445bDecode20211NoskoolTeamInternalAppMusiciansModels1(l, v)\n}", "func (v *matchRule) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson390b7126DecodeGithubComChancedPicker19(l, v)\n}", "func (v *managerHandlerDevice) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonEd74d837DecodeGithubComKihamoBoggartComponentsBoggartInternalHandlers1(l, v)\n}", "func (v *ResultReq) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson25363b2dDecodeGithubComDarkfoxs96OpenApiV3SdkOkexGoSdkApi54(l, v)\n}", "func (v *invocationMessage) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson2802b09fDecodeGithubComPhilippseithSignalr1(l, v)\n}", "func (v *fuzzyRule) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson390b7126DecodeGithubComChancedPicker34(l, v)\n}", "func (v *PlantainerShadowSt) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson5bd79fa1DecodeMevericcoreMcplantainer8(l, v)\n}", "func (v *completionMessage) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjson2802b09fDecodeGithubComPhilippseithSignalr5(l, v)\n}", "func (v *Source) UnmarshalEasyJSON(l *jlexer.Lexer) {\n\teasyjsonB27eec76DecodeGithubComTisonetOpenrtbEasyjson3(l, v)\n}" ]
[ "0.73405373", "0.72584677", "0.72040373", "0.71776104", "0.71510446", "0.7143438", "0.71413064", "0.71286225", "0.7112999", "0.7103849", "0.71005577", "0.7097653", "0.7085183", "0.70850646", "0.7081146", "0.7077145", "0.70403785", "0.70357895", "0.7030433", "0.7028725", "0.7021155", "0.70114094", "0.70109946", "0.70103574", "0.7002987", "0.69937176", "0.6981908", "0.6981736", "0.69811034", "0.6980795", "0.69711286", "0.6965327", "0.695678", "0.69543517", "0.6948873", "0.69404715", "0.69387776", "0.6935085", "0.6930436", "0.6922759", "0.6904652", "0.6894174", "0.68897486", "0.6889671", "0.6888647", "0.6887437", "0.6887124", "0.68862444", "0.68853265", "0.68804044", "0.6874087", "0.6870016", "0.6869092", "0.6868185", "0.6858964", "0.6846011", "0.68405616", "0.6836571", "0.6835831", "0.68291616", "0.6823791", "0.6822216", "0.6817067", "0.6815519", "0.68133044", "0.6812743", "0.6811037", "0.68107563", "0.6809271", "0.680744", "0.68065774", "0.68030846", "0.68029016", "0.67965585", "0.6794714", "0.678028", "0.67772484", "0.6772522", "0.67714006", "0.6769638", "0.67685604", "0.67657346", "0.6763771", "0.67634416", "0.6762939", "0.67570746", "0.6756749", "0.6754731", "0.6750861", "0.6749626", "0.6745531", "0.6744763", "0.6743289", "0.67418313", "0.6734197", "0.6732776", "0.67303044", "0.67287326", "0.67265445", "0.67261595" ]
0.73436594
0
People ... Create a router group to rs/crud/persons and relative routes
func People(engine *gin.Engine, midlewares ...gin.HandlerFunc) { personGroup := engine.Group("rs/crud/person") personGroup.GET("/:id", controllers.GetPerson) personGroup.GET("/", controllers.GetPagePerson) personGroup.PUT("/:id", controllers.PutPerson) personGroup.DELETE("/:id", controllers.DeletePerson) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func MakePersonHandlers(r *mux.Router, n negroni.Negroni, service person.UseCase) {\n\tr.Handle(\"/person\", n.With(\n\t\tnegroni.Wrap(findAllPersons(service)),\n\t)).Methods(\"GET\", \"OPTIONS\").Name(\"findAllPersons\")\n\n\tr.Handle(\"/person/{key}\", n.With(\n\t\tnegroni.Wrap(findPersonByKey(service)),\n\t)).Methods(\"GET\", \"OPTIONS\").Name(\"findPersonByKey\")\n\n\tr.Handle(\"/person\", n.With(\n\t\tnegroni.Wrap(personAdd(service)),\n\t)).Methods(\"POST\", \"OPTIONS\").Name(\"personAdd\")\n\n\tr.Handle(\"/persons\", n.With(\n\t\tnegroni.Wrap(personMultiAdd(service)),\n\t)).Methods(\"POST\", \"OPTIONS\").Name(\"personMultiAdd\")\n\n\tr.Handle(\"/person/{key}\", n.With(\n\t\tnegroni.Wrap(deletePerson(service)),\n\t)).Methods(\"DELETE\", \"OPTIONS\").Name(\"deletePerson\")\n\n}", "func RegisterRoutesPersons(mux *mux.Router, person interfaces.PersonDao) {\n\thandler := handlers.NewPersonHandler(person)\n\tmux.HandleFunc(\"/persons\", handler.CreatePerson).Methods(http.MethodPost)\n\tmux.HandleFunc(\"/persons/{id}\", handler.GetOne).Methods(http.MethodGet)\n\tmux.HandleFunc(\"/persons/signin\", handler.SignIn).Methods(http.MethodPost)\n\tmux.Handle(\"/persons/update\", middlewares.Authenticate(http.HandlerFunc(handler.Update))).Methods(http.MethodPut)\n\tmux.Handle(\"/persons/new-professor\", middlewares.Authenticate(middlewares.PersonRole(http.HandlerFunc(handler.CreateProfessor), 0))).Methods(http.MethodPost)\n\tmux.HandleFunc(\"/persons/section/{id}/{startDate}/{endDate}\", handler.GetAllBySectionIDAndDateRange).Methods(http.MethodGet)\n}", "func main() {\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"/people\", routes.GetPeople).Methods(\"GET\")\n\trouter.HandleFunc(\"/people/{id}\", routes.GetPerson).Methods(\"GET\")\n\trouter.HandleFunc(\"/people/{id}\", routes.CreatePerson).Methods(\"POST\")\n\trouter.HandleFunc(\"/people/{id}\", routes.DeletePerson).Methods(\"DELETE\")\n\tlog.Fatal(http.ListenAndServe(\":8080\", router))\n}", "func Router(route *gin.Engine) gin.IRoutes {\n\treturn route.Handle(\"GET\", common.Prefix+\"/person\", ControllerGetAll).\n\t\tHandle(\"GET\", common.Prefix+\"/person/:id\", ControllerGetByID).\n\t\tHandle(\"POST\", common.Prefix+\"/person\", ControllerCreate).\n\t\tHandle(\"PUT\", common.Prefix+\"/person/:id\", ControllerUpdate)\n}", "func (api *Api) setRouters() {\n\tapi.Post(\"/person\", api.handleRequest(handler.CreatePerson))\n\tapi.Patch(\"/person/{id}\", api.handleRequest(handler.UpdatePerson))\n\tapi.Put(\"/person/{id}\", api.handleRequest(handler.UpdatePerson))\n\tapi.Get(\"/person/{id}\", api.handleRequest(handler.GetPerson))\n\tapi.Get(\"/person\", api.handleRequest(handler.GetPersons))\n\tapi.Get(\"/person\", api.handleRequest(handler.GetPersons), \"page\", \"{page}\")\n}", "func HandlePerson(w http.ResponseWriter, r *http.Request) {\n\tkeys := r.URL.Query()[\"id\"]\n\tpersonID := keys[0]\n\n\ttmpl := template.Must(template.ParseFiles(\"views/detail-page.html\"))\n\tvar page model.DetailPageResponse\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tperson, pErr := model.GetInitialPerson(lib.BaseURL+\"people/\"+personID, &wg)\n\tif pErr != nil {\n\t\tfmt.Println(pErr.Error())\n\t}\n\twg.Wait()\n\n\tfmt.Println(\"person\", person)\n\tpage.PageTitle = \"Person\"\n\tpage.MainCard.Title = \"Name: \" + person.Name\n\tpage.MainCard.Body1 = \"Born: \" + person.BirthYear\n\tpage.MainCard.Body2 = \"Gender: \" + person.Gender\n\tpage.MainCard.Body3 = \"Height: \" + person.Height + \" CM\"\n\tpage.MainCard.Body4 = \"Mass: \" + person.Mass + \" KG\"\n\tpage.MainCard.Body5 = \"Eyes: \" + person.EyeColor + \" eyes\"\n\n\thomeworld, hErr := person.GetHomeworld()\n\tif hErr != nil {\n\t\tfmt.Println(hErr.Error())\n\t}\n\tpage.MainCard.SubTitle = \"Homeworld: \" + homeworld.Name\n\tfmt.Println(\"Homeworld\", homeworld)\n\n\t// vehicles\n\tif len(person.Vehicles) > 0 {\n\t\tvehicleChannel := make(chan []model.Vehicle)\n\t\tgo person.GetVehicles(vehicleChannel)\n\t\tvehicles := <-vehicleChannel\n\t\tpage.Cards1 = make([]model.SubCard, 0)\n\t\tfor _, vehicle := range vehicles {\n\t\t\tpage.Cards1 = append(page.Cards1, model.GetVehicleCard(vehicle))\n\t\t}\n\t}\n\n\tif len(person.Species) > 0 {\n\t\tspeciesChannel := make(chan []model.Species)\n\t\tgo person.GetSpecies(speciesChannel)\n\t\tspecies := <-speciesChannel\n\t\tpage.Cards2Title = \"Species\"\n\t\tpage.Cards2 = make([]model.SubCard, 0)\n\t\tfor _, specie := range species {\n\t\t\tpage.Cards2 = append(page.Cards2, model.GetSpeciesCard(specie))\n\t\t}\n\t}\n\n\t// starships\n\tif len(person.Starships) > 0 {\n\t\tstarshipChannel := make(chan []model.Starship)\n\t\tgo person.GetStarships(starshipChannel)\n\t\tstarships := <-starshipChannel\n\t\tpage.Cards3Title = \"Starships\"\n\t\tpage.Cards3 = make([]model.SubCard, 0)\n\t\tfor _, ship := range starships {\n\t\t\tpage.Cards3 = append(page.Cards3, model.GetStarshipCard(ship))\n\t\t}\n\t}\n\n\ttmpl.Execute(w, page)\n}", "func RegisterPersons(party iris.Party) {\n\tcrs := cors.New(cors.Options{\n\t\tAllowedOrigins: []string{\"*\"}, // allows everything, use that to change the hosts.\n\t\tAllowCredentials: true,\n\t\tAllowedMethods: []string{iris.MethodGet, iris.MethodPost, iris.MethodPut, iris.MethodDelete},\n\t})\n\tpersons := party.Party(\"/persons\", crs).AllowMethods(iris.MethodOptions)\n\t{\n\t\tpersons.Get(\"\", GetPersons)\n\t\tpersons.Get(\"/{id:int}\", GetPersonByID)\n\t\tpersons.Post(\"\", AddPerson)\n\t\tpersons.Put(\"/{id:int}\", UpdatePerson)\n\t\tpersons.Delete(\"/{id:int}\", DeletePerson)\n\t}\n}", "func Routes(r *gin.Engine) {\n\n\tv1 := r.Group(\"/v1\")\n\t{\n\t\t//// rutas publicas\n\t\tv1.GET(\"/testv1\", users.ServiceTest)\n\t\tv1.POST(\"/register\", users.Register)\n\t\tv1.POST(\"/login\", auth.HandleLogin)\n\t}\n\t//// rutas privadas\n\tv1.Use(middlewares.AuthHandler(\"\"))\n\t{\n\t\t// Companies\n\t\tcompaniesGroup := v1.Group(\"companies\")\n\t\tcompaniesGroup.GET(\"/\", company.GetAll)\n\t\tcompaniesGroup.POST(\"/create\", company.CreateNewCompany)\n\t\tcompaniesGroup.PUT(\"/changeStatus\", company.ChangeStatusCompany)\n\t\tcompaniesGroup.DELETE(\"/deleteCompany/:id\", company.DeleteCompany)\n\n\t\tcompaniesGroup.GET(\"/myCompany\", company.MyCompany)\n\t\tcompaniesGroup.GET(\"/myWorkShop\", company.MyWorkShop)\n\n\t\t// // Mechanic\n\t\tworkshops := v1.Group(\"workshop\")\n\t\tworkshops.GET(\"/\", workshop.Get)\n\t\tworkshops.GET(\"/search/:workshopID\", workshop.GetByID)\n\t\tworkshops.GET(\"/all\", workshop.GetAll)\n\t\tworkshops.POST(\"/create\", workshop.Create)\n\n\t\t// Mechanic\n\t\tmechanicGroup := v1.Group(\"mechanic\")\n\t\tmechanicGroup.POST(\"/create\", mechanic.Create)\n\t\tmechanicGroup.GET(\"/\", mechanic.Get)\n\t\tmechanicGroup.GET(\"/myMechanics\", mechanic.MyMechanics)\n\n\t\t// routines\n\t\troutine := v1.Group(\"routines\")\n\t\troutine.GET(\"\", routines.Get)\n\t\troutine.GET(\"/byWorkshop\", routines.GetByWorkshop)\n\t\troutine.GET(\"/byWorkshopID/:workshopID\", routines.GetByWorkshopID)\n\n\t\troutine.POST(\"/addRoutineByWorkshop\", routines.AddRoutineByWorkshop)\n\t\troutine.GET(\"/getTreatingMechanic/:workshopID/:vehicleID\", routines.GetTreatingMechanic)\n\n\t\tappointments := v1.Group(\"appointments\")\n\t\tappointments.GET(\"/\", appointment.GetAppointments)\n\n\t\t// users\n\t\tuser := v1.Group(\"user\")\n\t\tuser.GET(\"/\", users.GetDataUser)\n\t\tuser.GET(\"/myWorkShop\", users.GetDataWorkShopData)\n\t\tuser.PUT(\"/reset\", users.ResetPassword)\n\n\t\t// brands\n\t\tbrand := v1.Group(\"brands\")\n\t\tbrand.GET(\"\", brands.GetAll)\n\n\t\t// brands\n\t\tvehicle := v1.Group(\"vehicles\")\n\t\tvehicle.GET(\"\", vehicles.GetAllVehicles)\n\t\tvehicle.POST(\"\", vehicles.Create)\n\n\t}\n}", "func (r *RestAPI[T]) Router(router *gin.RouterGroup) {\n\trouter.GET(\"/\", r.list)\n\trouter.POST(\"\", r.create)\n\trouter.PUT(\"/:id\", r.replace)\n\trouter.DELETE(\"/:id\", r.delete)\n}", "func Routes(DB *gorm.DB, group echo.Group) {\n\t/*\n\t\tPasamos al controlador de la entidad el grupo de las rutas y le inyectamos la configuracion de base de datos\n\n\t\tWe pass to the heandler of the entity the group of the routes and we inject the database configuration\n\t*/\n\n\tv1.NewUserController(group, DB)\n\tv1.NewCharacterController(group, DB)\n\tv1.NewAwardController(group, DB)\n\tv1.NewTaskController(group, DB)\n\n}", "func RouteToV1(r *router.MyRouter) {\n\t// User\n\tr.HandlerFunc(\"POST\", \"/members/\", \"CreateMemberUser\", handler.CreateMemberUser)\n\tr.HandlerFunc(\"GET\", \"/members/\", \"ListMemberUsers\", handler.ListMemberUsers)\n\tr.HandlerFunc(\"GET\", \"/members/:mid/\", \"GetMemberUser\", handler.GetMemberUser)\n\tr.HandlerFunc(\"DELETE\", \"/members/:mid/\", \"DeleteMemberUser\", handler.DeleteMemberUser)\n\n\t// Token\n\tr.HandlerFunc(\"POST\", \"/oauth2/tokens/\", \"IssueToken\", handler.IssueToken)\n\tr.HandlerFunc(\"GET\", \"/oauth2/tokens/:tk/\", \"ValidateToken\", handler.ValidateToken)\n\tr.HandlerFunc(\"DELETE\", \"/oauth2/tokens/:tk/\", \"RevolkToken\", handler.RevolkToken)\n\n\t// Project\n\tr.HandlerFunc(\"POST\", \"/projects/\", \"CreateProject\", handler.CreateProject)\n\tr.HandlerFunc(\"GET\", \"/projects/\", \"ListDomainProjects\", handler.ListDomainProjects)\n\tr.HandlerFunc(\"GET\", \"/self/projects/\", \"ListUserProjects\", handler.ListUserProjects)\n\tr.HandlerFunc(\"GET\", \"/projects/:pid/\", \"GetProject\", handler.GetProject)\n\tr.HandlerFunc(\"DELETE\", \"/projects/:pid/\", \"DeleteProject\", handler.DeleteProject)\n\tr.HandlerFunc(\"GET\", \"/projects/:pid/members/\", \"ListProjectUser\", handler.ListProjectUser)\n\tr.HandlerFunc(\"POST\", \"/projects/:pid/members/\", \"AddUsersToProject\", handler.AddUsersToProject)\n\tr.HandlerFunc(\"DELETE\", \"/projects/:pid/members/\", \"RemoveUsersFromProject\", handler.RemoveUsersFromProject)\n\n\t// Application\n\tr.HandlerFunc(\"POST\", \"/applications/\", \"CreateApplication\", handler.CreateApplication)\n\tr.HandlerFunc(\"GET\", \"/applications/\", \"ListUserApplications\", handler.ListUserApplications)\n\tr.HandlerFunc(\"GET\", \"/applications/:aid/\", \"GetApplication\", handler.GetApplication)\n\tr.HandlerFunc(\"DELETE\", \"/applications/:aid/\", \"DeleteApplication\", handler.DeleteApplication)\n\t// // r.HandlerFunc(\"PUT\", \"/v1/users/:uid/applications/:aid/\", handler.UpdateApplication)\n\n\t// Service\n\tr.HandlerFunc(\"POST\", \"/services/\", \"CreateService\", handler.CreateService)\n\tr.HandlerFunc(\"GET\", \"/services/\", \"ListServices\", handler.ListServices)\n\tr.HandlerFunc(\"GET\", \"/services/:sid/\", \"GetService\", handler.GetService)\n\tr.HandlerFunc(\"DELETE\", \"/services/:sid/\", \"DeleteService\", handler.DeleteService)\n\tr.HandlerFunc(\"POST\", \"/features/\", \"RegistryServiceFeatures\", handler.RegistryServiceFeatures)\n\tr.HandlerFunc(\"GET\", \"/services/:sid/features/\", \"ListServiceFeatures\", handler.ListServiceFeatures)\n\n\t// Role\n\tr.HandlerFunc(\"POST\", \"/roles/\", \"CreateRole\", handler.CreateRole)\n\tr.HandlerFunc(\"GET\", \"/roles/\", \"ListRoles\", handler.ListRoles)\n\tr.HandlerFunc(\"GET\", \"/roles/:ri/\", \"GetRole\", handler.GetRole)\n\tr.HandlerFunc(\"DELETE\", \"/roles/:ri/\", \"DeleteRole\", handler.DeleteRole)\n\tr.HandlerFunc(\"POST\", \"/roles/:ri/features/\", \"AddFeaturesToRole\", handler.AddFeaturesToRole)\n\tr.HandlerFunc(\"DELETE\", \"/roles/:ri/features/\", \"RemoveFeaturesFromRole\", handler.RemoveFeaturesFromRole)\n\n\t// r.HandlerFunc(\"POST\", \"/v1/domains/users/\", \"CreateDomainUser\", handler.CreateDomainUser)\n\t// r.HandlerFunc(\"GET\", \"/v1/users/:uid/domains/\", \"ListUserDomain\", handler.ListUserDomain)\n\t// r.HandlerFunc(\"PUT\", \"/v1/users/:uid/password/\", \"SetUserPassword\", handler.SetUserPassword)\n\t// r.HandlerFunc(\"DELETE\", \"/v1/unregistry/\", \"UnRegistry\", handler.UnRegistry)\n\t// r.HandlerFunc(\"POST\", \"/v1/users/:uid/projects/\", \"AddProjectsToUser\", handler.AddProjectsToUser)\n\t// r.HandlerFunc(\"DELETE\", \"/v1/users/:uid/projects/\", \"RemoveProjectsFromUser\", handler.RemoveProjectsFromUser)\n\t// r.HandlerFunc(\"POST\", \"/v1/users/:uid/bind/roles/:rn/\", \"BindRole\", handler.BindRole)\n\t// r.HandlerFunc(\"POST\", \"/v1/users/:uid/unbind/roles/:rn/\", \"UnBindRole\", handler.UnBindRole)\n\t// r.HandlerFunc(\"POST\", \"/v1/invitations/\", \"InvitationsUser\", handler.InvitationsUser)\n\t// r.HandlerFunc(\"DELETE\", \"/v1/invitations/:code/\", \"RevolkInvitation\", handler.RevolkInvitation)\n\t// r.HandlerFunc(\"GET\", \"/v1/invitations/\", \"ListInvitationsRecords\", handler.ListInvitationsRecords)\n\t// r.HandlerFunc(\"GET\", \"/v1/invitations/:code/\", \"GetInvitationsRecord\", handler.GetInvitationsRecord)\n\t// r.HandlerFunc(\"POST\", \"/v1/registry/\", \"RegistryUser\", handler.RegistryUser)\n\t// r.HandlerFunc(\"POST\", \"/v1/verifycode/\", \"IssueVerifyCode\", handler.IssueVerifyCode)\n\t// r.HandlerFunc(\"POST\", \"/v1/invitations/users/:uid/code/:code/\", \"AcceptInvitation\", handler.AcceptInvitation)\n\t// r.HandlerFunc(\"PUT\", \"/v1/users/:uid/\", handler.UpdateUser)\n\t// r.HandlerFunc(\"POST\", \"/v1/default/projects/:pid/\", \"SetUserDefaultProject\", handler.SetUserDefaultProject)\n\n\tr.AddV1Root()\n}", "func PersonsIndex(c *gin.Context) {\r\n\tvar lis []models.Person\r\n\r\n\tdb, _ := c.Get(\"db\")\r\n\tconn := db.(gorm.DB)\r\n\r\n\t// Migrate the schema\r\n\tconn.AutoMigrate(&models.Person{})\r\n\r\n\tconn.Find(&lis)\r\n\tc.JSON(http.StatusOK, gin.H{\r\n\t\t\"msg\": \"thank you\",\r\n\t\t\"r\": lis,\r\n\t})\r\n\r\n}", "func makeRestRoutes(router *gin.Engine, controller *dependency.Dependency) {\n\tapi := router.Group(\"api\")\n\t{\n\t\t// link forward , hitting this route will cause the link to be resolved and forwarded in the browser\n\t\tapi.GET(\"forward/links/:id\", controller.ForwardLink)\n\t\t// get them the json record\n\t\tapi.GET(\"links/:id\", controller.FetchLink)\n\t\t// generate a new link\n\t\tapi.POST(\"links\", controller.ShortenLink)\n\t}\n}", "func peliculaRouter(pHandler *ph.Pelicula) http.Handler {\n\tr := chi.NewRouter()\n\tr.Get(\"/\", pHandler.Fetch)\n\tr.Get(\"/{id:[0-9]+}\", pHandler.GetByID)\n\tr.Post(\"/\", pHandler.Create)\n\tr.Put(\"/{id:[0-9]+}\", pHandler.Update)\n\tr.Delete(\"/{id:[0-9]+}\", pHandler.Delete)\n\treturn r\n}", "func Routes(router *gin.Engine) {\n\tuserGroup := router.Group(\"/users\")\n\t{\n\t\tuserGroup.GET(\"/\", usersroutes.NewUserRoutes().Show)\n\t\tuserGroup.POST(\"/\", usersroutes.NewUserRoutes().Create)\n\t\tuserGroup.OPTIONS(\"/\", usersroutes.NewUserRoutes().Options)\n\t}\n}", "func UsersRoutes(router *gin.Engine, controller *controllers.UsersController) {\n\tuserRoutes := router.Group(\"/users\")\n\t{\n\t\tuserRoutes.POST(\"/\", controller.CreateUserController)\n\t}\n}", "func (projectController *ProjectController) Routes(base *gin.RouterGroup, authNormal *jwt.GinJWTMiddleware) *gin.RouterGroup {\n\n\t// Projects - Rutas\n\tprojectRouter := base.Group(\"/projects\") //, middleware.SetRoles(RolAdmin, RolUser), authNormal.MiddlewareFunc())\n\t{\n\t\tprojectRouter.GET(\"\", projectController.GetAll())\n\t\t// Al agregar asociar con usuario\n\t\tprojectRouter.POST(\"\", authNormal.MiddlewareFunc(), projectController.Create())\n\t\tprojectRouter.GET(\"/:id\", projectController.One())\n\t\t// Verificar en handler que el perro sea dueño de usuario\n\t\tprojectRouter.PUT(\"/:id\", authNormal.MiddlewareFunc(), projectController.Update())\n\t\t// Solo admin puede eliminar\n\t\tprojectRouter.DELETE(\"/:id\", middleware.SetRoles(RolAdmin), authNormal.MiddlewareFunc(), projectController.Delete())\n\t}\n\treturn projectRouter\n}", "func Routes(router *gin.RouterGroup) {\n\tr := &pipeRoutes{}\n\n\trouter.GET(\"/\", r.get)\n\trouter.GET(\"/:pipe-id\", r.get)\n\trouter.DELETE(\"/:pipe-id\", r.delete)\n\trouter.POST(\"/\", r.post)\n}", "func GetPersonEndpoint(w http.ResponseWriter, req *http.Request) {\n\tparams := mux.Vars(req)\n\tfor _, item := range people {\n\t\tif item.ID == params[\"id\"] {\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(&Person{})\n}", "func registerRoutes() {\n\tuserRoutes()\n\troleRoutes()\n}", "func SetupRouter() *gin.Engine {\n\tr := gin.Default()\n\tgrp1 := r.Group(\"/user-api\")\n\t{\n\t\tgrp1.GET(\"user\", Controllers.GetUsers)\n\t\tgrp1.POST(\"user\", Controllers.CreateUser)\n\t\tgrp1.GET(\"user/:id\", Controllers.GetUserByID)\n\t\tgrp1.PUT(\"user/:id\", Controllers.UpdateUser)\n\t\tgrp1.DELETE(\"user/:id\", Controllers.DeleteUser)\n\t}\n\tgrp2 := r.Group(\"/category-api\")\n\t{\n\t\tgrp2.GET(\"categories\", Controllers.GetCategories)\n\t}\n\tgrp3 := r.Group(\"/food-api\")\n\t{\n\t\tgrp3.GET(\"foods/:id\", Controllers.GetFoods)\n\t}\n\n\treturn r\n}", "func (h Handler) Routes(e *echo.Group) {\n\te.GET(\"\", h.Find)\n\te.GET(\"/:gameID\", h.Retrieve)\n\te.POST(\"\", h.Create)\n\te.PATCH(\"/:gameID\", h.Apply)\n\n}", "func main() {\n\t// Init router\n\trouter := mux.NewRouter()\n\n\t// Hardcoded data - @todo: add database\n/*\treservations = append(reservations, Reservation{ID: \"1\", StartTime: \"438227\", EndTime: \"438227\", CarID: \"23\", GarageID: \"231\"})\n\treservations = append(reservations, Reservation{ID: \"2\", StartTime: \"438227\", EndTime: \"438227\", CarID: \"11\", GarageID: \"232\"})\n\tusers = append(users, User{ID: \"1\", Username: \"filik\", Email: \"yo@dot\", Password: \"1234\"})\n\tusers = append(users, User{ID: \"1\", Username: \"filik\", Email: \"yo@dot\", Password: \"1234\"})\n\tcars = append(cars, Car{ID: \"1\", UserID: \"23\", Model: \"BMW\"})\n\tcars = append(cars, Car{ID: \"2\", UserID: \"23\", Model: \"MERCEDES\"})\n\tgarages = append(garages, Garage{ID: \"1\", Name: \"1st\", MaxCars: \"5\"})\n\tgarages = append(garages, Garage{ID: \"2\", Name: \"2nd\", MaxCars: \"3\"})\n\thistory = append(history, History{ID: \"1\", ReservationID: \"2\"})\n*/\n\t// Reservation route handles & endpoints\n\trouter.HandleFunc(\"/reservations\", GetReservations).Methods(\"GET\")\n\trouter.HandleFunc(\"/reservations/\", GetReservations).Methods(\"GET\")\n\trouter.HandleFunc(\"/reservations/{id}\", GetReservation).Methods(\"GET\")\n\trouter.HandleFunc(\"/reservations/\", CreateReservation).Methods(\"POST\")\n\trouter.HandleFunc(\"/reservations\", CreateReservation).Methods(\"POST\")\n\t//router.HandleFunc(\"/reservations/{id}\", UpdateReservation).Methods(\"PUT\")\n\trouter.HandleFunc(\"/reservations/{id}\", DeleteReservation).Methods(\"DELETE\")\n\trouter.HandleFunc(\"/reservations-by-user/{id}\", GetReservationsByUser).Methods(\"GET\")\n\n\t// Users route handles & endpoints\n\trouter.HandleFunc(\"/users\", GetUsers).Methods(\"GET\")\n\trouter.HandleFunc(\"/users/\", GetUsers).Methods(\"GET\")\n\trouter.HandleFunc(\"/users/{id}\", GetUser).Methods(\"GET\")\n\trouter.HandleFunc(\"/users\", CreateUser).Methods(\"POST\")\n\trouter.HandleFunc(\"/users/\", CreateUser).Methods(\"POST\")\n\t//router.HandleFunc(\"/users/{id}\", UpdateUser).Methods(\"PUT\")\n\trouter.HandleFunc(\"/users/{id}\", DeleteUser).Methods(\"DELETE\")\n\n\t// Garages route handles & endpoints\n\trouter.HandleFunc(\"/garages\", GetGarages).Methods(\"GET\")\n\trouter.HandleFunc(\"/garages/\", GetGarages).Methods(\"GET\")\n\trouter.HandleFunc(\"/garages/{id}\", GetGarage).Methods(\"GET\")\n\trouter.HandleFunc(\"/garages/\", CreateGarage).Methods(\"POST\")\n\trouter.HandleFunc(\"/garages\", CreateGarage).Methods(\"POST\")\n\t//router.HandleFunc(\"/garages/{id}\", UpdateGarage).Methods(\"PUT\")\n\trouter.HandleFunc(\"/garages/{id}\", DeleteGarage).Methods(\"DELETE\")\n\n\t// Cars route handles & endpoints\n\trouter.HandleFunc(\"/cars\", GetCars).Methods(\"GET\")\n\trouter.HandleFunc(\"/cars/\", GetCars).Methods(\"GET\")\n\trouter.HandleFunc(\"/cars/{id}\", GetCar).Methods(\"GET\")\n\trouter.HandleFunc(\"/cars\", CreateCar).Methods(\"POST\")\n\trouter.HandleFunc(\"/cars\", CreateCar).Methods(\"POST\")\n\trouter.HandleFunc(\"/get-cars-by-user/{id}\", GetCarsByUser).Methods(\"GET\")\n\t//router.HandleFunc(\"/cars/{id}\", UpdateCar).Methods(\"PUT\")\n\trouter.HandleFunc(\"/cars/{id}\", DeleteCar).Methods(\"DELETE\")\n\n\t// History route handler & endpoint\n\trouter.HandleFunc(\"/history/\", GetHistory).Methods(\"GET\")\n\n\t// Start server\n\tlog.Fatal(http.ListenAndServe(\":8888\", router))\n}", "func Router(g *gin.RouterGroup) {\n\tcontroller := controllers.UserController{}\n\t{\n\t\tg.GET(\"/users\", controller.GetUsers)\n\t\tg.GET(\"/user/:id\", controller.GetUser)\n\t\tg.POST(\"/user\", controller.CreateUser)\n\t}\n}", "func (api *api) RegisterRouting(g *echo.Group) {\n\n\tgrp := g.Group(\"/v2/products\")\n\tgrp.GET(\"\", api.Service.List)\n\tgrp.GET(\"/:id\", api.Service.Get)\n\tgrp.POST(\"\", api.Service.Create)\n\tgrp.PUT(\"/:id\", api.Service.Update)\n\tgrp.DELETE(\"/:id\", api.Service.Delete)\n\n}", "func (p *Endpoint) Routes(router component.IRouter) {\n\trouter.Post(\"/v1/user\", p.Create)\n\trouter.Get(\"/v1/user/:user_id\", p.Show)\n\trouter.Get(\"/v1/userSelf\", p.ShowSelf)\n\trouter.Get(\"/v1/user\", p.Index)\n\trouter.Put(\"/v1/user/:user_id\", p.Update)\n\trouter.Delete(\"/v1/user/:user_id\", p.Destroy)\n\trouter.Delete(\"/v1/user\", p.DestroyAll)\n}", "func ApplyRoutes(r *gin.RouterGroup) {\n\tposts := r.Group(\"/users\")\n\t{\n\t\tposts.GET(\"/\", list)\n\t}\n}", "func Router(r *gin.Engine) {\n\t// db := common.LoadDatabase()\n\tr.Any(\"/api/v1/location/*path1\", deflt)\n\t// r.GET(\"/user/list\", func(c *gin.Context) {\n\t// \tc.String(http.StatusOK, \"wow\")\n\t// })\n}", "func (ctl *AuthorController) register() {\n\tAuthors := ctl.router.Group(\"/Authors\")\n\n\tAuthors.GET(\"\", ctl.ListAuthor)\n\n\t// CRUD\n\tAuthors.POST(\"\", ctl.CreateAuthor)\n\tAuthors.GET(\":id\", ctl.GetAuthor)\n\tAuthors.PUT(\":id\", ctl.UpdateAuthor)\n\tAuthors.DELETE(\":id\", ctl.DeleteAuthor)\n}", "func generateUserAPIRoutes(router *mux.Router) {\n\tusers := router.PathPrefix(\"/users\").Subrouter()\n\tusers.Use(helpers.LoggingMiddleware)\n\tusers.HandleFunc(\"\", user.GetAll).Methods(\"GET\") // GET Request to handle all data present in the Database\n\n\tsub := router.PathPrefix(\"/user\").Subrouter()\n\tsub.Use(helpers.LoggingMiddleware)\n\t\n\tsub.HandleFunc(\"\", user.GetUser).Methods(\"GET\")\n}", "func Router(db *connectordb.Database, prefix *mux.Router) *mux.Router {\n\tif prefix == nil {\n\t\tprefix = mux.NewRouter()\n\t}\n\n\t//Allow for the application to match /path and /path/ to the same place.\n\tprefix.StrictSlash(true)\n\n\tprefix.HandleFunc(\"/\", restcore.Authenticator(ListUsers, db)).Queries(\"q\", \"ls\")\n\n\t//User CRUD\n\tprefix.HandleFunc(\"/{user}\", restcore.Authenticator(ListDevices, db)).Methods(\"GET\").Queries(\"q\", \"ls\")\n\tprefix.HandleFunc(\"/{user}\", restcore.Authenticator(ListDevices, db)).Methods(\"GET\").Queries(\"q\", \"devices\")\n\tprefix.HandleFunc(\"/{user}\", restcore.Authenticator(ListUserStreams, db)).Methods(\"GET\").Queries(\"q\", \"streams\")\n\tprefix.HandleFunc(\"/{user}\", restcore.Authenticator(ReadUser, db)).Methods(\"GET\")\n\tprefix.HandleFunc(\"/{user}\", restcore.Authenticator(CreateUser, db)).Methods(\"POST\")\n\tprefix.HandleFunc(\"/{user}\", restcore.Authenticator(UpdateUser, db)).Methods(\"PUT\")\n\tprefix.HandleFunc(\"/{user}\", restcore.Authenticator(DeleteUser, db)).Methods(\"DELETE\")\n\n\t//Device CRUD\n\tprefix.HandleFunc(\"/{user}/{device}\", restcore.Authenticator(ListStreams, db)).Methods(\"GET\").Queries(\"q\", \"ls\")\n\tprefix.HandleFunc(\"/{user}/{device}\", restcore.Authenticator(ListStreams, db)).Methods(\"GET\").Queries(\"q\", \"streams\")\n\tprefix.HandleFunc(\"/{user}/{device}\", restcore.Authenticator(ReadDevice, db)).Methods(\"GET\")\n\tprefix.HandleFunc(\"/{user}/{device}\", restcore.Authenticator(CreateDevice, db)).Methods(\"POST\")\n\tprefix.HandleFunc(\"/{user}/{device}\", restcore.Authenticator(UpdateDevice, db)).Methods(\"PUT\")\n\tprefix.HandleFunc(\"/{user}/{device}\", restcore.Authenticator(DeleteDevice, db)).Methods(\"DELETE\")\n\n\t//Stream CRUD\n\tprefix.HandleFunc(\"/{user}/{device}/{stream}\", restcore.Authenticator(ReadStream, db)).Methods(\"GET\")\n\tprefix.HandleFunc(\"/{user}/{device}/{stream}\", restcore.Authenticator(CreateStream, db)).Methods(\"POST\")\n\tprefix.HandleFunc(\"/{user}/{device}/{stream}\", restcore.Authenticator(UpdateStream, db)).Methods(\"PUT\")\n\tprefix.HandleFunc(\"/{user}/{device}/{stream}\", restcore.Authenticator(DeleteStream, db)).Methods(\"DELETE\")\n\n\tprefix.HandleFunc(\"/{user}/{device}/{stream}/data\", restcore.Authenticator(StreamLength, db)).Methods(\"GET\").Queries(\"q\", \"length\")\n\tprefix.HandleFunc(\"/{user}/{device}/{stream}/data\", restcore.Authenticator(StreamTime2Index, db)).Methods(\"GET\").Queries(\"q\", \"time2index\")\n\tprefix.HandleFunc(\"/{user}/{device}/{stream}/data\", restcore.Authenticator(StreamRange, db)).Methods(\"GET\")\n\tprefix.HandleFunc(\"/{user}/{device}/{stream}/data\", restcore.Authenticator(WriteStream, db)).Methods(\"POST\") //Restamp off\n\tprefix.HandleFunc(\"/{user}/{device}/{stream}/data\", restcore.Authenticator(WriteStream, db)).Methods(\"PUT\") //Restamp on\n\n\treturn prefix\n}", "func Router(r *gin.Engine) error {\n\n\t// helth check\n\tr.GET(\"/helth\", func(c *gin.Context) {\n\t\t// apm.TraceSeg(c, \"/helth\")\n\n\t\tc.JSON(200, gin.H{\n\t\t\t\"message\": \"helth check ok\",\n\t\t})\n\t})\n\n\t// Simple group\n\tapi := r.Group(\"/todo\")\n\t{\n\t\t// Entity の操作\n\t\tapi.POST(\"/task\", todo.Add)\n\t\tapi.PATCH(\"/task\", todo.Update)\n\t\tapi.GET(\"/task\", todo.Select)\n\n\t\t// Task event\n\t\tapi.POST(\"/task/done/:id\", todo.Done)\n\t\tapi.DELETE(\"/task/delete\", todo.Delete)\n\t}\n\n\treturn nil\n}", "func AddPeople(w http.ResponseWriter, r *http.Request) {\n\tmyDb, err := db.StartDB(\"mydb.db\")\n\tif err != nil {\n\t\tfmt.Printf(\"Fail in open database: %v\\n\", err)\n\t\treturn\n\t}\n\n\t// Verify token\n\ttoken := r.Header.Get(\"AuthToken\")\n\tif (!myDb.IsLogIn([]byte(token))) {\n\t\tfmt.Printf(\"Unauthorized: %v\\n\", err)\n\t\t// 401: Unauthorized\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t// Add a people\n\tvars := mux.Vars(r)\n\tpeopleId, err := strconv.Atoi(vars[\"peopleId\"])\n\n\tbody, err := ioutil.ReadAll(r.Body)\n if err != nil {\n\t\tfmt.Printf(\"Read body error: %v\\n\", err)\n\t\tw.WriteHeader(http.StatusNotFound)\n\t}\n\t\n\tif err := myDb.AddObj(\"people\", []byte(strconv.Itoa(peopleId)),[]byte(body)); err != nil {\n\t\tfmt.Printf(\"Read body error: %v\\n\", err)\n\t\tw.WriteHeader(http.StatusNotFound)\n\t}\n\t\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n}", "func PublicRoutes(a *fiber.App) {\n\t// Create routes group.\n\troute := a.Group(\"/api/v1\")\n\n\t// Routes for GET method:\n\troute.Get(\"/books\", controllers.GetBooks) // get list of all books\n\troute.Get(\"/book/:id\", controllers.GetBook) // get one book by ID\n\n\t// Routes for POST method:\n\troute.Post(\"/user/sign/up\", controllers.UserSignUp) // register a new user\n\troute.Post(\"/user/sign/in\", controllers.UserSignIn) // auth, return Access & Refresh tokens\n}", "func SetupRouter() *gin.Engine {\n\tr := gin.Default()\n\tgrp1 := r.Group(\"/todolist\")\n\t{\n\t\tgrp1.GET(\"task\", controllers.GetAllTasks)\n\t\tgrp1.POST(\"task\", controllers.CreateTask)\n\t\tgrp1.GET(\"task/:id\", controllers.GetTaskByID)\n\t\t//grp1.GET(\"task/:taskstatus\", controllers.GetTaskByTaskstatus)\n\t\tgrp1.PUT(\"task/:id\", controllers.UpdateTask)\n\t\tgrp1.DELETE(\"task/:id\", controllers.DeleteTask)\n\t}\n\treturn r\n}", "func initalizeRoutes() {\n\n\tv1 := app.Group(\"/v1\")\n\n\t// Auth controller routes\n\taccountRoutes := v1.Group(\"/account\")\n\taccountRoutes.POST(\"/register\", accountController.Register)\n\taccountRoutes.POST(\"/login\", accountController.Login)\n\taccountRoutes.POST(\"/refresh-token\", accountController.RefreshToken)\n\n\t// Post controller routes\n\tpostRoutes := v1.Group(\"/posts\").Use(middleware.Authorization())\n\tpostRoutes.GET(\"/\", postController.GetAll)\n\n}", "func (c *Controller) AddRoutes(router *mux.Router) *mux.Router {\n\tfmt.Println(&c.Repo.users)\n\tbasePath := \"/api\"\n\trouter.HandleFunc(basePath+\"/login\", c.login).Methods(\"POST\")\n\trouter.HandleFunc(basePath+\"/register\", c.register).Methods(\"POST\")\n\trouter.HandleFunc(basePath+\"/users\", c.createUser).Methods(\"POST\")\n\trouter.HandleFunc(basePath+\"/users\", c.listUsers).Methods(\"GET\")\n\trouter.HandleFunc(basePath+\"/users/{id}\", c.getUser).Methods(\"GET\")\n\trouter.HandleFunc(basePath+\"/users/{id}\", c.updateUser).Methods(\"PUT\")\n\trouter.HandleFunc(basePath+\"/users/{id}\", c.deleteUser).Methods(\"DELETE\")\n\treturn router\n}", "func endpointManagement(r common.Router) common.Router {\n\t// programatically set swagger info\n\tdocs.SwaggerInfo.Title = \"gin swagger test\"\n\tdocs.SwaggerInfo.Description = \"This is a sample server for Swagger.!!!!!!\"\n\tdocs.SwaggerInfo.Version = \"1.0\"\n\tdocs.SwaggerInfo.Host = \"localhost:9000\"\n\tdocs.SwaggerInfo.BasePath = \"/v1\"\n\n\tr.Version = r.Engine.Group(\"/v1\")\n\n\t//SECTION x endpoints by function\n\tuser.NewUserV1Router(r, \"/user\")\n\tauth.NewAuthV1Router(r, \"/auth\")\n\n\tr.Engine.GET(\"/swagger/*any\", ginSwagger.WrapHandler(swaggerFiles.Handler))\n\n\treturn r\n}", "func main() {\n router := mux.NewRouter()\n router.HandleFunc(\"/payments\", GetPayments).Methods(\"GET\")\n router.HandleFunc(\"/payment/{id}\", GetPayment).Methods(\"GET\")\n router.HandleFunc(\"/payment/create/{id}\", CreatePayment).Methods(\"POST\")\n router.HandleFunc(\"/payment/{id}\", DeletePayment).Methods(\"DELETE\")\n router.HandleFunc(\"/payment/edit/{id}\", ModifyPayment).Methods(\"PATCH\")\n log.Fatal(http.ListenAndServe(\":8000\", router))\n}", "func main() {\n\trouter := mux.NewRouter().StrictSlash(true)\n\tsub := router.PathPrefix(\"/api/v1\").Subrouter()\n\tsub.Methods(\"GET\").Path(\"/companies\").HandlerFunc(handler.GetCompanies)\n\tsub.Methods(\"POST\").Path(\"/companies\").HandlerFunc(handler.SaveCompany)\n\tsub.Methods(\"GET\").Path(\"/companies/{name}\").HandlerFunc(handler.GetCompany)\n\tsub.Methods(\"PUT\").Path(\"/companies/{name}\").HandlerFunc(handler.UpdateCompany)\n\tsub.Methods(\"DELETE\").Path(\"/companies/{name}\").HandlerFunc(handler.DeleteCompany)\n\n\tlog.Fatal(http.ListenAndServe(\":3000\", router))\n}", "func Router() chi.Router {\n\tr := chi.NewRouter()\n\n\tr.Get(\"/\", list)\n\tr.Get(\"/{user_id}/permissions\", userpermissions)\n\n\treturn r\n}", "func init() {\n\t// system.Router.HandleFunc(\"/app/get/list/{crud}\", HandleListGeneric)\n}", "func CreateRouter(handlerFunc http.HandlerFunc) *mux.Router {\n router := mux.NewRouter()\n\n config := dots_config.GetSystemConfig()\n prefixPath := config.ClientRestfulApiConfiguration.RestfulApiPath\n\n restfulHandlerFunc := createRestfulHandlerFunc(handlerFunc)\n\n // router.HandleFunc(\"/test\", restfulHandlerFunc).Methods(\"GET\")\n router.HandleFunc(prefixPath + MITIGATION_PATH + \"/cuid={cuid}\", restfulHandlerFunc).Methods(\"GET\")\n router.HandleFunc(prefixPath + MITIGATION_PATH + \"/cuid={cuid}/mid={mid}\", restfulHandlerFunc).Methods(\"GET\")\n router.HandleFunc(prefixPath + MITIGATION_PATH + \"/cuid={cuid}/mid={mid}\", restfulHandlerFunc).Methods(\"PUT\")\n router.HandleFunc(prefixPath + MITIGATION_PATH + \"/cuid={cuid}/mid={mid}\", restfulHandlerFunc).Methods(\"DELETE\")\n\n return router\n}", "func CreatePerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tparams := mux.Vars(r)\n\tvar person Person\n\t_ = json.NewDecoder(r.Body).Decode(&person)\n\tperson.ID = params[\"id\"]\n\tpeople = append(people, person)\n\tjson.NewEncoder(w).Encode(people)\n}", "func HandleAddPerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Body Read Error : %v\", err), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tvar person db.Person\n\terr = json.Unmarshal(reqBody, &person)\n\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Request Body parse error : %v\", err), http.StatusBadRequest)\n\t\treturn\n\t}\n\tfmt.Println(\"new person\", person)\n\t_, err = Db.Exec(\"INSERT INTO people(name,city,contactNo,photoUrl) values(?,?,?,?)\", person.Name, person.City, person.ContactNo, person.PhotoUrl)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"ERROR in creating person %s\", err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tvar newPerson db.Person\n\tres, err := Db.Query(\"SELECT * FROM RD.people order by id Desc limit 1\")\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"ERROR in creating person %s\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\tdefer res.Close()\n\tfor res.Next() {\n\t\terr = res.Scan(&newPerson.Id, &newPerson.Name, &newPerson.City, &newPerson.ContactNo, &newPerson.PhotoUrl)\n\t\tif err != nil {\n\t\t\thttp.Error(w, fmt.Sprintf(\"ERROR in creating person %s\", err.Error()), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\tjson.NewEncoder(w).Encode(newPerson)\n}", "func GetAllPerson(c *gin.Context) {\n\tperson, _ := models.LoadPeople()\n\tc.JSON(http.StatusOK, person)\n\n}", "func (a *App) Resource(controllerName string, nested ...*route) *route {\n\troute := a.newRoute(controllerName, nil)\n\troute.subroutes = nested\n\troute.buildPatterns(\"\")\n\treturn route\n}", "func Route(mux *http.ServeMux) {\n\n\tmux.HandleFunc(\"/studyplan/create\", createStudyPlan)\n\tmux.HandleFunc(\"/subject/create\", createSubject)\n\tmux.HandleFunc(\"/career/create\", createCareer)\n\tmux.HandleFunc(\"/teacher/create\", createTeacher)\n\tmux.HandleFunc(\"/student/create\", createStudent)\n\n\tmux.HandleFunc(\"/studyplan/getall\", getAllStudyPlan)\n\tmux.HandleFunc(\"/subject/getall\", getAllSubjects)\n\tmux.HandleFunc(\"/career/getall\", getAllCareers)\n\tmux.HandleFunc(\"/teacher/getall\", getAllTeachers)\n\tmux.HandleFunc(\"/student/getall\", getAllStudents)\n\n\tmux.HandleFunc(\"/studyplan\", getStudyPlanById)\n\tmux.HandleFunc(\"/subject\", getSubjectById)\n\tmux.HandleFunc(\"/career\", getCareerById)\n\tmux.HandleFunc(\"/teacher\", getTeacherById)\n\tmux.HandleFunc(\"/student\", getStudentById)\n\n\tmux.HandleFunc(\"/studyplan/delete\", deleteStudyPlan)\n\tmux.HandleFunc(\"/subject/delete\", deleteSubject)\n\tmux.HandleFunc(\"/career/delete\", deleteCareer)\n\tmux.HandleFunc(\"/teacher/delete\", deleteTeacher)\n\tmux.HandleFunc(\"/student/delete\", deleteStudent)\n\n\tmux.HandleFunc(\"/studyplan/update\", UpdateStudyPlan)\n\tmux.HandleFunc(\"/subject/update\", UpdateSubject)\n\tmux.HandleFunc(\"/career/update\", updateCareer)\n\tmux.HandleFunc(\"/teacher/update\", updateTeacher)\n\tmux.HandleFunc(\"/student/update\", updateStudent)\n\t/* mux.HandleFunc(\"/v1/persons/getall\", middleware.Log(h.getAll))\n\tmux.HandleFunc(\"/v1/persons/update\", middleware.Log(h.update))\n\tmux.HandleFunc(\"/v1/persons/delete\", middleware.Log(h.delete))\n\tmux.HandleFunc(\"/v1/persons/getbyid\", middleware.Log(h.getById)) */\n}", "func Routes(app *fiber.App, service Service) {\n\tapi := app.Group(\"/api/v1\")\n\n\tapi.Get(\"/health\", func(c *fiber.Ctx) error {\n\t\treturn c.Status(http.StatusOK).\n\t\t\tJSON(map[string]interface{}{\n\t\t\t\t\"health\": \"ok\",\n\t\t\t\t\"status\": http.StatusOK,\n\t\t\t})\n\t})\n\n\t// public endpoint\n\tapi.Get(\"/token/new\", GetNewAccessToken)\n\tapi.Get(\"/travels\", service.getTravels)\n\tapi.Get(\"/travels/:id\", service.getTravel)\n\n\t// private endpoint\n\tapi.Post(\"/travels\", JWTProtected(), service.createTravel)\n\tapi.Put(\"/travels/:id\", JWTProtected(), service.updateTravel)\n\tapi.Delete(\"/travels/:id\", JWTProtected(), service.deleteTravel)\n}", "func (s *Server) setupRoutes() {\n\ts.Router.Static(\"/app\", \"./public\")\n\trouter := s.ApiRouter\n\n\t// This handler will match /user/john but will not match neither /user/ or /user\n\trouter.GET(\"/apps\", func(c *gin.Context) {\n\t\tapps, err := getAllApps()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tc.JSON(200, apps)\n\t})\n\n\t// This handler will match /user/john but will not match neither /user/ or /user\n\trouter.GET(\"/apps/:id\", func(c *gin.Context) {\n\t\tid := c.Param(\"id\")\n\t\tidInt, err := strconv.Atoi(id)\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tapp, err := getApp(uint(idInt))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tc.JSON(200, app)\n\t})\n\n\t// This handler will match /user/john but will not match neither /user/ or /user\n\trouter.GET(\"/apps/:id/history\", func(c *gin.Context) {\n\t\tid := getId(c.Param(\"id\"))\n\n\t\thistories, err := getAppHistory(uint(id))\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tc.JSON(200, histories)\n\t})\n\n\trouter.POST(\"/apps\", func(c *gin.Context) {\n\t\tvar app = domain.App{}\n\t\tif err := c.BindJSON(&app); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\terr := insertApp(&app)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tregisterCheck(app)\n\t\t\tc.JSON(http.StatusOK, app)\n\t\t}\n\t})\n\n\trouter.PUT(\"/apps/:id\", func(c *gin.Context) {\n\t\tid := getId(c.Param(\"id\"))\n\n\t\tvar app domain.App\n\t\tif err := c.BindJSON(&app); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\toldApp, _ := getApp(uint(id))\n\n\t\terr := updateApp(uint(id), app)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tif app.CheckStatus != oldApp.CheckStatus {\n\t\t\t\tlastApp, _ := getApp(uint(id))\n\t\t\t\tupdateCheck(lastApp)\n\t\t\t}\n\t\t\tc.JSON(http.StatusOK, app)\n\t\t}\n\t})\n\n\trouter.DELETE(\"/apps/:id\", func(c *gin.Context) {\n\t\tid := getId(c.Param(\"id\"))\n\n\t\terr := deleteApp(uint(id))\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\t} else {\n\t\t\tc.JSON(http.StatusOK, gin.H{\"status\": \"ok\"})\n\t\t}\n\t})\n}", "func SetupRouter() *gin.Engine {\n\tr := gin.Default()\n\n\tusers := r.Group(\"/users\")\n\t{\n\t\tusers.GET(\"/\", controllers.GetUsers)\n\t\tusers.GET(\"/:id\", controllers.GetUser)\n\t\tusers.POST(\"/\", controllers.CreateUser)\n\t\tusers.PATCH(\"/:id\", controllers.UpdateUser)\n\t\tusers.DELETE(\"/:id\", controllers.DeleteUser)\n\t}\n\n\treturn r\n}", "func SetupRoutes(app *fiber.App) {\n\tapi := app.Group(\"api/v1/\")\n\tusers := app.Group(\"/auth/v1\")\n}", "func AccountRouters(e *gin.Engine, u usecase.UseCase) {\n\te.POST(\"/accounts\", CreateAccount(u))\n\te.GET(\"/accounts/:accountId\", GetAccount(u))\n}", "func SetEmployeeRoutes(router *mux.Router) *mux.Router {\n\tempRouter := mux.NewRouter()\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/add\", controllers.AddEmployee).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/child/add\", controllers.AddChildEmployee).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/\", controllers.GetEmployees).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/org/{orgId}\", controllers.GetEmployeessByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/employee/{empId}\", controllers.GetEmployeesByMgr).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/departments/{deptId}\", controllers.GetEmployeesByDept).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/branches/{branchId}\", controllers.GetEmployeesByBranchMethods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/{id}\", controllers.GetEmployee).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/users/{userId}\", controllers.GetEmployeeByUser).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/edit/{id}\", controllers.EditEmployeeByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/user/edit/{id}\", controllers.EditEmployeeByUser).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/biodata/add\", controllers.AddBiodataByEmp).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/pid/add\", controllers.AddPIDByBio).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/health/detail/add\", controllers.AddHealthDetByBio).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/work/experience/add\", controllers.AddWorkExpByBio).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/education/add\", controllers.AddEduByBio).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/biodatas/employees/{id}\", controllers.GetBiosByEmp).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/biodatas/edit/{id}\", controllers.GetBio).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/biodatas/employee/edit/{empId}\", controllers.GetBioByEmp).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/biodatas/{id}\", controllers.EditBioByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/biodatas/employee/{empId}\", controllers.EditBioByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/pids/biodatas/{bioId}\", controllers.GetPIDsByBio).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/pids/{id}\", controllers.GetPID).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/pids/biodata/{bioId}\", controllers.GetPIDByBio).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/pids/biodata/edit/{bioId}\", controllers.EditPIDByBio).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/pids/edit/{id}\", controllers.EditPIDByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/health/details/biodatas/{bioId}\", controllers.GetHealthDetsByBio).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/health/details/{id}\", controllers.GetHealthDetail).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/health/details/biodata/{bioId}\", controllers.GetHealthDetailByBio).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/health/details/biodata/edit/{bioId}\", controllers.EditHealthDetailByBio).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/health/details/edit/{id}\", controllers.EditHealthDetailByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/work/experiences/biodatas/{bioId}\", controllers.GetWorkExpsByBio).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/work/experiences/{id}\", controllers.GetWorkExperience).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/work/experiences/biodata/{bioId}\", controllers.GetWorkExperienceByBio).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/work/experiences/biodata/edit/{bioId}\", controllers.EditWorkExperieceByBio).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/work/experiences/edit/{id}\", controllers.EditWorkExperieceByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/educations/biodatas/{bioId}\", controllers.GetEdusByBio).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/educations/{id}\", controllers.GetEducation).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/educations/biodata/{bioId}\", controllers.GetEduByBio).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/educations/biodata/edit/{bioId}\", controllers.EditEduByBio).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/educations/{id}\", controllers.EditEduByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/expense/claims/add\", controllers.AddExpenseClaimByEmp).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/leave/allocations/add\", controllers.AddLeaveAllocationByEmp).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/leave/applications/add\", controllers.AddLeaveApplicationByEmp).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/leave/blocklist/add\", controllers.AddLeaveBlockListByOrg).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/holiday/list/add\", controllers.AddHolidayListByEmp).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/appraisals/add\", controllers.AddAppraisalByEmp).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/exit/add\", controllers.AddExitByEmp).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/expense/claims/org/{orgId}\", controllers.GetExpenseClaimsByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/expense/claims/managers/{mgrId}\", controllers.GetExpenseClaimsByMgr).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/expense/claims/employees/{empId}\", controllers.GetExpenseClaimsByEmp).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/expense/claims/{id}\", controllers.GetExpenseClaim).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/expense/claims/managers/edit/{mgrId}\", controllers.EditExpenseClaimByMgr).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/expense/claims/employees/edit/{empId}\", controllers.EditExpenseClaimByEmp).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/leave/applications/orgs/{orgId}\", controllers.GetLeaveApplicationsByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/leave/applications/managers/{mgrId}\", controllers.GetLeaveApplicationsByMgr).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/leave/applications/employees/{empId}\", controllers.GetLeaveApplicationsByEmp).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/leave/applications/{id}\", controllers.GetLeaveApplication).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/leave/applications/edit/{id}\", controllers.EditLeaveApplicationByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/leave/blocklists/orgs/{orgId}\", controllers.GetLeaveBlockListsByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/leave/blocklists/{id}\", controllers.GetLeaveBlockList).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/leave/blocklists/{id}\", controllers.EditLeaveBlockListByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/holiday/lists/orgs/{orgId}\", controllers.GetHolidayListsByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/holiday/lists/{id}\", controllers.GetHolidayList).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/holiday/lists/edit/{id}\", controllers.EditHolidayListByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/appraisals/orgs/{orgId}\", controllers.GetAppraisalsByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/appraisals/managers/{mgrId}\", controllers.GetAppraisalsByMgr).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/holiday/lists/edit/{id}\", controllers.GetEditHolidayListByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/appraisals/edit/{id}\", controllers.EditAppraisalByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/exits/orgs/{orgId}\", controllers.GetExitsByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/exits/managers/{mgrId}\", controllers.GetExitsByMgr).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/exits/{id}\", controllers.GetExit).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/exits/edit/{id}\", controllers.EditExitByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/components/add\", controllers.AddSalaryComponent).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/employees/add\", controllers.AddSalaryEmployees).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/structures/add\", controllers.AddSalaryStructure).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/activity/types/add\", controllers.AddActivityType).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/working/hour/add\", controllers.AddWorkingHour).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/operation/add\", controllers.AddOperation).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/workstation/add\", controllers.AddWorkstation).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/timesheet/add\", controllers.AddTimesheet).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salaryslip/add\", controllers.AddSalarySlip).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/activity/cost/add\", controllers.AddActivityCost).Methods(\"POST\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/components/org/{orgId}\", controllers.GetSalaryComponentsByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/employees/org/{orgId}\", controllers.GetSalaryEmployeesByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/structures/org/{orgId}\", controllers.GetSalaryStructuresByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/components/{id}\", controllers.GetSalaryComponent).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/employees/{id}\", controllers.GetSalaryEmployee).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/structures/{id}\", controllers.GetSalaryStructure).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/components/edit/{id}\", controllers.EditSalaryComponentByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/employees/edit/{id}\", controllers.EditSalaryEmployeeByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/structures/edit/{id}\", controllers.EditSalaryStructureByAdmin).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/structures/accounts/{acctId}\", controllers.GetSalaryStructuresByAcct).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salary/structures/managers/{mgrId}\", controllers.GetSalaryStructuresByMgr).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/activity/types/org/{orgId}\", controllers.GetActivityTypesByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/activity/types/{id}\", controllers.GetActivityType).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/activity/types/edit/{id}\", controllers.EditActivityTypeByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/operations/org/{orgId}\", controllers.GetOperationsByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/operations/{id}\", controllers.GetOperation).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/operations/edit/{id}\", controllers.EditOperationByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/working/hours/org/{orgId}\", controllers.GetWorkingHoursByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/working/hours/{id}\", controllers.GetworkingHour).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/working/hours/edit/{id}\", controllers.EditWorkingHourByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/workstations/org/{orgId}\", controllers.GetWorkstationsByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/workstations/{id}\", controllers.GetWorkstation).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/workstations/edit/{id}\", controllers.EditWorkstationByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/timesheets/org/{orgId}\", controllers.GettTimesheetsByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/timesheets/employees/{empId}\", controllers.GettTimesheetsByEmp).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/timesheets/managers/{mgrId}\", controllers.GettTimesheetsByMgr).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/timesheets/{id}\", controllers.GetTimesheet).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/timesheets/edit/{id}\", controllers.EditTimesheetByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salaryslips/org/{orgId}\", controllers.GetSalarySlipsByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salaryslips/managers/{mgrId}\", controllers.GetSalarySlipsByMgr).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salaryslips/employees/{empId}\", controllers.GetSalarySlipsByEmp).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salaryslips/{id}\", controllers.GetSalarySlip).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/salaryslips/edit/{id}\", controllers.EditSalarySlipByAdmin).Methods(\"PUT\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/activity/costs/org/{orgId}\", controllers.GetActivityCostsByOrg).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/activity/costs/type/{typeId}\", controllers.GetActivityCostsByType).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/activity/costs/employees/{empId}\", controllers.GetActivityCostsByEmp).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/activity/costs/{id}\", controllers.GetActivityCost).Methods(\"GET\")\n\tempRouter.HandleFunc(\"/api/v1/orgs/employees/activity/costs/edit/{id}\", controllers.EditActivityCostByAdmin).Methods(\"PUT\")\n\trouter.PathPrefix(\"/api/v1/admin/org/employees/\").Handler(negroni.New(\n\t\tnegroni.HandlerFunc(common.Authorize),\n\t\tnegroni.Wrap(empRouter),\n\t))\n\treturn router\n}", "func AppendUsersAPI(router *mux.Router) {\n\trouter.Handle(\"/\", server.AuthenticateWithUser(server.GetAllUsers)).Methods(\"GET\")\n\trouter.Handle(\"/\", server.AuthenticateWithUser(server.CreateUser)).Methods(\"POST\")\n\trouter.Handle(\"/{userId:[a-f\\\\d]{24}}\", server.AuthenticateWithUser(server.GetUserByID)).Methods(\"GET\")\n\trouter.Handle(\"/{userId:[a-f\\\\d]{24}}\", server.AuthenticateWithUser(server.UpdateUser)).Methods(\"POST\")\n\trouter.Handle(\"/{userId:[a-f\\\\d]{24}}\", server.AuthenticateWithUser(server.DeleteUser)).Methods(\"DELETE\")\n\trouter.Handle(\"/{userId:[a-f\\\\d]{24}}/termofservices\", server.AuthenticateWithUser(server.TermOfServicesAcceptedByUser)).Methods(\"POST\")\n\trouter.Handle(\"/register\", server.Wrap(server.RegisterUser)).Methods(\"POST\")\n\trouter.Handle(\"/technicians\", server.AuthenticateWithUser(server.GetAllTechnicians)).Methods(\"GET\")\n\trouter.Handle(\"/workers\", server.AuthenticateWithUser(server.GetAllWorkers)).Methods(\"GET\")\n\trouter.Handle(\"/cooperative/{cooperativeId:[a-f\\\\d]{24}}\", server.AuthenticateWithUser(server.UserMatchRoles(constants.RoleTechnician, constants.RoleAdmin, constants.RoleWorker), server.GetClientsByCooperativeID)).Methods(\"GET\")\n}", "func UsersRoute(route *mux.Route) *mux.Router {\n\tr := route.Subrouter()\n\treturn r\n}", "func (ctl *ManagerController) register() {\n\tmanagers := ctl.router.Group(\"/managers\")\n\n\tmanagers.GET(\"\", ctl.ListManager)\n\n\t// CRUD\n\tmanagers.POST(\"\", ctl.CreateManager)\n\tmanagers.GET(\":id\", ctl.GetManager)\n\tmanagers.PUT(\":id\", ctl.UpdateManager)\n\tmanagers.DELETE(\":id\", ctl.DeleteManager)\n}", "func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) {\n // this line is used by starport scaffolding # 1\n\t\tr.HandleFunc(\"/policingnetworkcosmos/judgement\", createJudgementHandler(cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/judgement\", listJudgementHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/judgement/{key}\", getJudgementHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/judgement\", setJudgementHandler(cliCtx)).Methods(\"PUT\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/judgement\", deleteJudgementHandler(cliCtx)).Methods(\"DELETE\")\n\n\t\t\n\t\tr.HandleFunc(\"/policingnetworkcosmos/chargesheet\", createChargesheetHandler(cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/chargesheet\", listChargesheetHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/chargesheet/{key}\", getChargesheetHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/chargesheet\", setChargesheetHandler(cliCtx)).Methods(\"PUT\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/chargesheet\", deleteChargesheetHandler(cliCtx)).Methods(\"DELETE\")\n\n\t\t\n\t\tr.HandleFunc(\"/policingnetworkcosmos/evidence\", createEvidenceHandler(cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/evidence\", listEvidenceHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/evidence/{key}\", getEvidenceHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/evidence\", setEvidenceHandler(cliCtx)).Methods(\"PUT\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/evidence\", deleteEvidenceHandler(cliCtx)).Methods(\"DELETE\")\n\n\t\t\n\t\tr.HandleFunc(\"/policingnetworkcosmos/investigation\", createInvestigationHandler(cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/investigation\", listInvestigationHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/investigation/{key}\", getInvestigationHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/investigation\", setInvestigationHandler(cliCtx)).Methods(\"PUT\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/investigation\", deleteInvestigationHandler(cliCtx)).Methods(\"DELETE\")\n\n\t\t\n\t\tr.HandleFunc(\"/policingnetworkcosmos/fir\", createFirHandler(cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/fir\", listFirHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/fir/{key}\", getFirHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/fir\", setFirHandler(cliCtx)).Methods(\"PUT\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/fir\", deleteFirHandler(cliCtx)).Methods(\"DELETE\")\n\n\t\t\n\t\tr.HandleFunc(\"/policingnetworkcosmos/profile\", createProfileHandler(cliCtx)).Methods(\"POST\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/profile\", listProfileHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/profile/{key}\", getProfileHandler(cliCtx, \"policingnetworkcosmos\")).Methods(\"GET\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/profile\", setProfileHandler(cliCtx)).Methods(\"PUT\")\n\t\tr.HandleFunc(\"/policingnetworkcosmos/profile\", deleteProfileHandler(cliCtx)).Methods(\"DELETE\")\n\n\t\t\n}", "func SetupRouter() *gin.Engine {\n\tr := gin.Default()\n\trouter := r.Group(\"/\")\n\t{\n\t\trouter.GET(\"customers\", Controllers.GetCustomers)\n\t\trouter.POST(\"customers\", Controllers.AddCustomerDetails)\n\t\trouter.GET(\"customers/:id\", Controllers.GetCustomerByID)\n\n\t\trouter.GET(\"customers/orders/:id\", Controllers.GetOrdersByCustomerID)\n\t\trouter.PUT(\"customers/:id\", Controllers.UpdateCustomerDetails)\n\t\trouter.DELETE(\"customers/:id\", Controllers.DeleteCustomerDetails)\n\n\t\trouter.GET(\"products\", Controllers.GetProducts)\n\n\t\trouter.POST(\"products\", Controllers.AddProductDetails)\n\t\trouter.GET(\"products/:id\", Controllers.GetProductByID)\n\t\trouter.GET(\"products/orders/:id\", Controllers.GetOrdersByProductID)\n\t\t// update it to patch\n\t\trouter.PUT(\"products/:id\", Controllers.UpdateProductDetails)\n\t\trouter.DELETE(\"products/:id\", Controllers.DeleteProductDetails)\n\n\t\trouter.GET(\"orders\", Controllers.GetOrders)\n\n\t\t//fetch the customer and product\n\t\trouter.POST(\"orders\", Controllers.PlaceOrderDetails)\n\t\trouter.GET(\"orders/:id\", Controllers.GetOrderByID)\n\t\trouter.PUT(\"order/:id\", Controllers.UpdateOrderDetails)\n\t\trouter.DELETE(\"order/:id\", Controllers.DeleteOrderDetails)\n\t}\n\n\treturn r\n}", "func ApplyRoutes(r *gin.RouterGroup) {\n\tpassengerlocation := r.Group(\"/passengerlocation\")\n\t{\n\t\tpassengerlocation.POST(\"/\", create)\n\t\tpassengerlocation.GET(\"/\", list)\n\t\tpassengerlocation.GET(\"/:id\", read)\n\t\tpassengerlocation.DELETE(\"/:id\", remove)\n\t\tpassengerlocation.PATCH(\"/:id\", update)\n\t}\n}", "func NewPeopleAPI(db types.Store) *PeopleAPI {\n\tpeopleAPI := &PeopleAPI{db: db}\n\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"/people\", peopleAPI.get).Methods(\"GET\")\n\tpeopleAPI.Router = router\n\n\treturn peopleAPI\n}", "func setupRouter() *gin.Engine {\n\tc := gin.Default()\n\tclient := c.Group(\"/apx\")\n\t{\n\t\tclient.GET(\"/user\", controllers.GetAllUser)\n\t\tclient.GET(\"/user/:id\", controllers.GetUserByID)\n\t\tclient.DELETE(\"/user/:id\", controllers.DeleteUserByID)\n\t\tclient.POST(\"/user\", controllers.CreateUser)\n\t\tclient.PUT(\"/user/:id\", controllers.UpdateUserByID)\n\t}\n\treturn c\n}", "func GetPeopleEndpoint(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"content-type\", \"application/json\")\n\tvar people []Person\n\tcollection := client.Database(\"villagepeople\").Collection(\"people\")\n\tctx, _ := context.WithTimeout(context.Background(), 10*time.Second)\n\tcursor, err := collection.Find(ctx, bson.M{})\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(`{ \"message\": \"` + err.Error() + `\" }`))\n\t\treturn\n\t}\n\n\tdefer cursor.Close(ctx)\n\tfor cursor.Next(ctx) {\n\t\tvar person Person\n\t\tcursor.Decode(&person)\n\t\tpeople = append(people, person)\n\t}\n\tif err := cursor.Err(); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(`{ \"message\": \"` + err.Error() + `\" }`))\n\t\treturn\n\t}\n\tjson.NewEncoder(w).Encode(people)\n}", "func registerUserRoutes(api iris.Party) {\n\tapi.Post(\"/users\", service.UserRegister).Name = \"UserRegister\"\n\n\tuserRoutes := api.Party(\"/users\")\n\tuserRoutes.Use(middlewares.CheckLoginStatus)\n\n\tuserRoutes.Patch(\"/password\", service.ChangePassword).Name = \"ChangePassword\"\n\t// User Operation url\n\t// userRoutes.Delete(\"/{userId:int min(1)}\", handler)\n}", "func GetPersonRelations(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tid := r.URL.Query().Get(\"id\")\n\tif id == \"\" {\n\t\thttp.Error(w, \"id parameter is not found\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tvar relations []db.Relation\n\trows, err := Db.Query(\"SELECT * FROM relations where p1=?\", id)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Error in fetching all Persons %s\", err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tfor rows.Next() {\n\t\tvar r db.Relation\n\t\terr := rows.Scan(&r.P1, &r.P2, &r.Name)\n\t\tif err != nil {\n\t\t\thttp.Error(w, fmt.Sprintf(\"Error in fetching all Persons %s\", err.Error()), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\trelations = append(relations, r)\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(relations)\n}", "func SetupRouter() *gin.Engine {\n\tr := gin.Default()\n\tgrp1 := r.Group(\"/user-api\")\n\t{\n\t\tgrp1.GET(\"products\", Controllers.GetUsers)\n\t\tgrp1.POST(\"product\", Controllers.CreateProd)\n\t\tgrp1.GET(\"product/:id\", Controllers.GetProdByID)\n\t\tgrp1.PATCH(\"product/:id\", Controllers.UpdateProd)\n\t\tgrp1.DELETE(\"product/:id\", Controllers.DeleteUser)\n\t\tgrp1.POST(\"order\", Controllers.CreateOrder)\n\t}\n\treturn r\n}", "func SetRouters(m *macaron.Macaron) {\n\tm.Get(\"/\", handler.Home)\n\tm.Group(\"/login\", func() {\n\t\tm.Get(\"\", handler.Login)\n\t\tm.Post(\"\", binding.Bind(handler.SignIn{}), handler.LoginPost)\n\t})\n\tm.Group(\"/category\", func() {\n\t\tm.Get(\"\", handler.GetCategories)\n\t})\n\tm.Group(\"/topic\", func() {\n\t\tm.Get(\"\", handler.GetTopics)\n\t\tm.Get(\"/add\", handler.TopicAdd)\n\t\tm.Post(\"\", binding.Bind(handler.TopicAddForm{}), handler.TopicPost)\n\n\t\tm.Get(\"/:topicId\", handler.TopicView)\n\t\tm.Get(\"/modify\", handler.ModifyTopic)\n\t\t// m.Put(\"\", binding.Bind(handler.TopicModifyForm{}), handler.TopicPut)\n\t\t// m.Delete(\"/:topicId\", handler.DeleteTopic)\n\t})\n\t// m.Group(\"/v1\", func() {\n\t// \tm.Get(\"/\", handler.IndexV1Handler)\n\t// \tm.Group(\"/topic\", func() {\n\t// \t\tm.Get(\"\", handler.GetTopics)\n\t// \t\tm.Post(\"\", handler.PostTopic)\n\n\t// \t\tm.Get(\"/:topic\", handler.GetTopic)\n\t// \t\tm.Put(\"/:topic\", handler.PutTopic)\n\t// \t\tm.Delete(\"/:topic\", handler.DeleteTopic)\n\t// \t})\n\t// \tm.Group(\"/categories\", func() {\n\t// \t\tm.Get(\"\", handler.GetCategories)\n\t// \t\tm.Post(\"\", handler.PostCategory)\n\n\t// \t\tm.Get(\"/:category\", handler.GetCategory)\n\t// \t\tm.Put(\"/:category\", handler.PutCategory)\n\t// \t\tm.Delete(\"/:category\", handler.DeleteCategory)\n\t// \t})\n\t// })\n}", "func InitRouter(b *Bloodlines) {\n\tb.router = gin.Default()\n\tb.router.Use(handlers.GetCors())\n\n\tcontent := b.router.Group(\"/api/content\")\n\t{\n\t\tcontent.Use(b.content.GetJWT())\n\t\tcontent.Use(b.content.Time())\n\t\tcontent.POST(\"\", b.content.New)\n\t\tcontent.GET(\"\", b.content.ViewAll)\n\t\tcontent.GET(\"/:contentId\", b.content.View)\n\t\tcontent.PUT(\"/:contentId\", b.content.Update)\n\t\tcontent.DELETE(\"/:contentId\", b.content.Deactivate)\n\t}\n\n\treceipt := b.router.Group(\"/api/receipt\")\n\t{\n\t\treceipt.Use(b.receipt.GetJWT())\n\t\treceipt.Use(b.receipt.Time())\n\t\treceipt.GET(\"\", b.receipt.ViewAll)\n\t\treceipt.POST(\"/send\", b.receipt.Send)\n\t\treceipt.GET(\"/:receiptId\", b.receipt.View)\n\t}\n\n\tjob := b.router.Group(\"/api/job\")\n\t{\n\t\tjob.Use(b.job.GetJWT())\n\t\tjob.Use(b.job.Time())\n\t\tjob.GET(\"\", b.job.ViewAll)\n\t\tjob.POST(\"\", b.job.New)\n\t\tjob.GET(\"/:jobId\", b.job.View)\n\t\tjob.PUT(\"/:jobId\", b.job.Update)\n\t\tjob.DELETE(\"/:jobId\", b.job.Stop)\n\t}\n\n\ttrigger := b.router.Group(\"/api/trigger\")\n\t{\n\t\ttrigger.Use(b.trigger.GetJWT())\n\t\ttrigger.Use(b.trigger.Time())\n\t\ttrigger.POST(\"\", b.trigger.New)\n\t\ttrigger.GET(\"\", b.trigger.ViewAll)\n\t\ttrigger.GET(\"/:key\", b.trigger.View)\n\t\ttrigger.PUT(\"/:key\", b.trigger.Update)\n\t\ttrigger.DELETE(\"/:key\", b.trigger.Remove)\n\t\ttrigger.POST(\"/:key/activate\", b.trigger.Activate)\n\t}\n\n\tpref := b.router.Group(\"/api/preference\")\n\t{\n\t\tpref.Use(b.preference.Time())\n\t\tpref.Use(b.preference.GetJWT())\n\t\tpref.POST(\"\", b.preference.New)\n\t\tpref.GET(\"/:userId\", b.preference.View)\n\t\tpref.PATCH(\"/:userId\", b.preference.Update)\n\t\tpref.DELETE(\"/:userId\", b.preference.Deactivate)\n\t}\n\n\tfor _, w := range b.workers {\n\t\tw.Consume()\n\t}\n}", "func LoadRoute() *gin.Engine {\n\tr := gin.Default()\n\n\t// create controller\n\tvar (\n\t\tsqliteRepo = db.NewSQLiteRepository(\"./dbsocmed.db\")\n\t\trelationController = relation.NewController(sqliteRepo)\n\t)\n\n\tr.Use(Cors())\n\tv1 := r.Group(\"api/v1\")\n\t{\n\t\tv1.POST(\"/friendconnection\", relationController.PostFriendConnection)\n\t\tv1.POST(\"/friendlist\", relationController.PostFriendList)\n\t\tv1.POST(\"/friendcommonlist\", relationController.PostFriendCommonList)\n\t\tv1.POST(\"/friendsubscribe\", relationController.PostFriendSubscribe)\n\t\tv1.POST(\"/friendblock\", relationController.PostFriendBlock)\n\t\tv1.POST(\"/friendupdates\", relationController.PostFriendUpdates)\n\t}\n\n\treturn r\n}", "func Router(e *echo.Echo) {\n\th := NewHandler()\n\tg := e.Group(\"/admin\")\n\t{\n\t\tg.GET(\"/\", h.IndexPage)\n\t\tg.GET(\"/list\", h.ListPage)\n\t\tg.GET(\"/customer/list\", h.CustomerListPage)\n\t\tg.GET(\"/customer/chat/:customerID\", h.CustomerChatPage)\n\t\t//g.GET(\"/products/:productId\", h.ProductPage)\n\t}\n}", "func (ctl *PatientrecordController) register() {\n\tpatientrecords := ctl.router.Group(\"/patientrecords\")\n \n\tpatientrecords.GET(\"\", ctl.ListPatientrecord)\n \n\t// CRUD\n\tpatientrecords.POST(\"\", ctl.CreatePatientrecord)\n\tpatientrecords.GET(\":id\", ctl.GetPatientrecord)\n\tpatientrecords.PUT(\":id\", ctl.UpdatePatientrecord)\n\tpatientrecords.DELETE(\":id\", ctl.DeletePatientrecord)\n }", "func (r *ManagerResource) Routes() http.Handler {\n\trouter := chi.NewRouter()\n\t// router.Use(render.SetContentType(render.ContentTypeJSON))\n\n\tcors := cors.New(cors.Options{\n\t\t// AllowedOrigins: []string{\"https://foo.com\"}, // Use this to allow specific origin hosts\n\t\tAllowedOrigins: []string{\"*\"},\n\t\t// AllowOriginFunc: func(r *http.Request, origin string) bool { return true },\n\t\tAllowedMethods: []string{\"GET\", \"POST\", \"PUT\", \"DELETE\", \"OPTIONS\"},\n\t\tAllowedHeaders: []string{\"Accept\", \"Authorization\", \"Content-Type\", \"X-CSRF-Token\"},\n\t\tExposedHeaders: []string{\"Link\"},\n\t\tAllowCredentials: true,\n\t\tMaxAge: 300, // Maximum value not ignored by any of major browsers\n\t})\n\n\trouter.Use(cors.Handler)\n\n\tprivKey, err := crypto.HexToECDSA(r.config.Keys.Admin)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Failed to load key\")\n\t}\n\n\tec, err := ethereum.CreateEthClient(r.config.Infura.URL + r.config.Infura.Key)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Failed to initialize ethereum client\")\n\t}\n\n\tauth := bind.NewKeyedTransactor(privKey)\n\n\tvaultManagerContract, err := vaultmanager.NewManager(ec, r.config.Contracts.VaultManagerAddress, auth)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Failed to create vault manager\")\n\t}\n\n\trouter.Get(\"/get-all-vaults\", r.getAllAddresses(vaultManagerContract, ec))\n\trouter.Post(\"/add-vault\", r.addNewVault(vaultManagerContract))\n\n\tlog.WithFields(log.Fields{\"Contract\": \"Vault Manager\", \"Address\": r.config.Contracts.VaultManagerAddress}).Info(\"Created manager abstraction\")\n\n\treturn router\n}", "func Route(router *gin.Engine) {\n\tnpc := router.Group(\"/npcs\")\n\t{\n\t\tnpc.DELETE(\"/:id\", delete)\n\t\tnpc.GET(\"/\", getMany)\n\t\tnpc.GET(\"/:id\", getOne)\n\t\tnpc.POST(\"/\", create)\n\t\tnpc.POST(\"/generate\", generate)\n\t}\n}", "func DeletePerson(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(req)\n\tid, _ := strconv.Atoi(params[\"id\"])\n\tfor index, person := range models.People {\n\t\tif person.ID == id {\n\t\t\tmodels.People = append(models.People[:index], models.People[index+1:]...)\n\t\t}\n\t}\n}", "func GetPerson(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tfor _, item := range people {\n\t\tif item.ID == params[\"id\"] {\n\t\t\tjson.NewEncoder(w).Encode(item)\n\t\t\treturn\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tjson.NewEncoder(w).Encode(&model.Person{})\n\t//r = mux.Vars(r)\n}", "func (a *App) initializeRoutes() {\n\t// Root\n\ta.Router.HandleFunc(\"/\", authn(a.getRoot)).Methods(\"GET\")\n\t// AuthZ and AuthN\n\ta.Router.HandleFunc(\"/login\", a.getLogin).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/login\", a.processLogin).Methods(\"POST\")\n\ta.Router.HandleFunc(\"/logout\", a.processLogout).Methods(\"GET\")\n\t// Images and stuff\n\ta.Router.PathPrefix(\"/resources/\").Handler(http.StripPrefix(\"/resources/\", http.FileServer(http.Dir(\"./resources/\"))))\n\t// Contacts\n\ta.Router.HandleFunc(\"/contacts\", authn(a.getContacts)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/contact/{id:[0-9]+}\", authn(a.editContact)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/contact/create\", authn(a.createContact)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/contact/save\", authn(a.saveContact)).Methods(\"POST\")\n\ta.Router.HandleFunc(\"/contact/delete/{id:[0-9]+}\", authn(a.deleteContact)).Methods(\"GET\")\n\t// Customers\n\ta.Router.HandleFunc(\"/customers\", authn(a.getCustomers)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/customer/{id:[0-9]+}\", authn(a.editCustomer)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/customer/create\", authn(a.createCustomer)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/customer/save\", authn(a.saveCustomer)).Methods(\"POST\")\n\ta.Router.HandleFunc(\"/customer/delete/{id:[0-9]+}\", a.deleteCustomer).Methods(\"GET\")\n\t// Projects\n\ta.Router.HandleFunc(\"/projects\", authn(a.getProjects)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/project/{id:[0-9]+}\", authn(a.editProject)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/project/create\", authn(a.createProject)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/project/save\", authn(a.saveProject)).Methods(\"POST\")\n\ta.Router.HandleFunc(\"/project/delete/{id:[0-9]+}\", authn(a.deleteProject)).Methods(\"GET\")\n\t// Dashboard\n\ta.Router.HandleFunc(\"/dashboard\", authn(a.getDashboard)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/dashboard/notifications\", authn(a.getDashboardNotifications)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/dashboard/numberofprojects\", authn(a.getDashboardNumberOfProjects)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/dashboard/numberofhappy\", authn(a.getDashboardHappyCustomer)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/dashboard/completedtask\", authn(a.getDashboardCompletedTask)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/dashboard/resources\", authn(a.getDashboardResources)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/dashboard/tasks\", authn(a.getDashboardProjectTasksForUser)).Methods(\"GET\")\n\t// System Notification\n\ta.Router.HandleFunc(\"/notifications\", authn(a.getSystemNotifications)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/notification/{id:[0-9]+}\", authn(a.editSystemNotification)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/notification/create\", authn(a.createSystemNotification)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/notification/save\", authn(a.saveSystemNotification)).Methods(\"POST\")\n\ta.Router.HandleFunc(\"/notification/delete/{id:[0-9]+}\", authn(a.deleteSystemNotification)).Methods(\"GET\")\n\t// Internal Resources\n\ta.Router.HandleFunc(\"/resources\", authn(a.getResources)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/resource/{id:[0-9]+}\", authn(a.editResource)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/resource/create\", authn(a.createResource)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/resource/save\", authn(a.saveResource)).Methods(\"POST\")\n\ta.Router.HandleFunc(\"/resource/delete/{id:[0-9]+}\", authn(a.deleteResource)).Methods(\"GET\")\n\t// Project Task\n\ta.Router.HandleFunc(\"/tasks\", authn(a.getProjectTasks)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/task/{id:[0-9]+}\", authn(a.editProjectTask)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/task/create\", authn(a.createProjectTask)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/task/save\", authn(a.saveProjectTask)).Methods(\"POST\")\n\ta.Router.HandleFunc(\"/task/delete/{id:[0-9]+}\", authn(a.deleteProjectTask)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/task/attachment\", authn(a.getAttachment)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/mytask/{id:[0-9]+}\", authn(a.getUserTasks)).Methods(\"GET\")\n\t// Settings\n\ta.Router.HandleFunc(\"/settings\", authn(a.getSettings)).Methods(\"GET\")\n\t// System Backup\n\ta.Router.HandleFunc(\"/backup\", authn(a.getBackup)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/backup/start\", authn(a.startBackup)).Methods(\"POST\")\n\t// Application Users\n\ta.Router.HandleFunc(\"/users\", authn(a.getUsers)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/user/create\", authn(a.createUser)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/user/save\", authn(a.saveUser)).Methods(\"POST\")\n\ta.Router.HandleFunc(\"/user/{id:[0-9]+}\", authn(a.editUser)).Methods(\"GET\")\n\ta.Router.HandleFunc(\"/user/delete/{id:[0-9]+}\", authn(a.deleteUser)).Methods(\"GET\")\n\t// Static Files\n\ta.Router.PathPrefix(\"/public/\").Handler(http.StripPrefix(\"/public/\", http.FileServer(rice.MustFindBox(\"public\").HTTPBox())))\n}", "func (s *Server) setupRoutes(devMode bool) {\n\ts.Router.NoRoute(NoRoute)\n\tv1 := s.Router.Group(\"/api/v1\")\n\tv1.GET(\"/healthcheck\", s.Healthcheck)\n\n\tv1.GET(\"/articles\", s.GetArticles)\n\tv1.POST(\"/articles\", s.AddArticle)\n\tv1.POST(\"/articles:batch\", s.AddArticles)\n\n\t// Profiler\n\t// URL: https://<IP>:<PORT>/debug/pprof/\n\tif devMode {\n\t\ts.Logger.Info(\"activating pprof (devmode on)\", log.Field(\"type\", \"debug\"))\n\t\tpprof.Register(s.Router)\n\t}\n}", "func SetupRoutes(r chi.Router, s *Service) {\n\tr.Route(\"/api/pet\", func(r chi.Router) {\n\t\tr.Post(\"/\", s.PostPet)\n\t\tr.Route(\"/{id}\", func(r chi.Router) {\n\t\t\tr.Use(urlParamContextSaverMiddleware(\"id\", idKey))\n\t\t\tr.Get(\"/\", s.GetPet)\n\t\t\tr.Put(\"/\", s.PutPet)\n\t\t\tr.Delete(\"/\", s.DeletePet)\n\t\t})\n\t})\n}", "func initializeRoutes(port string) {\n\t/*\n\t\tAll the urls will be mentioned and configured.\n\t*/\n\t/*\n\t\turl : /test\n\t*/\n\tr.GET(\"/test\", showHomePage)\n\t/*\n\t\turl : /\n\t*/\n\tr.GET(\"/\", showHomePage)\n\t/*\n\t\tDefining group route for users\n\t*/\n\tuserRoutes := r.Group(\"/user\")\n\t{\n\t\t/*\n\t\t\turl : /user/\n\t\t*/\n\t\tuserRoutes.GET(\"/\", showHomePage)\n\t\t/*\n\t\t\turl : /user/login (method is get)\n\t\t*/\n\t\tuserRoutes.GET(\"/login\", showLoginPage)\n\t\t/*\n\t\t\turl : /user/login (method is post)\n\t\t*/\n\t\tuserRoutes.POST(\"/login\", performLogin)\n\t\t/*\n\t\t\turl : /user/jsonresponse\n\t\t*/\n\t\tuserRoutes.GET(\"/jsonresponse\", jsonresponse)\n\t}\n\tfmt.Println(\"-------Starting server-------------\")\n}", "func UserCabV1Routes(router *gin.Engine) {\n\n loginRouter := router.Group(\"/v1/new\")\n {\n //for new user login\n loginRouter.POST(\"login\", newUserLogin)\n }\n\n\tuserRouter := router.Group(\"/v1/user\")\n\t{\n userRouter.Use(ValidateUserRequestAndFetchUser())\n\n //user can book a cab\n userRouter.POST(\"/book\", bookCab)\n\n //user's all past rides\n userRouter.GET(\"/rides\", getUserRides)\n }\n\n}", "func mapUrls() {\n\t// Ping Test\n\trouter.GET(\"/gin/ping\", ping.Ping)\n\n\t// User Routes\n\trouter.GET(\"/gin/user/:user_id\", users.Get)\n\trouter.GET(\"/gin/internal/users/search\", users.Search)\n\trouter.POST(\"/gin/user/new\", users.Create)\n\trouter.PUT(\"/gin/user/:user_id\", users.Update)\n\trouter.PATCH(\"/gin/user/:user_id\", users.Update)\n\trouter.DELETE(\"/gin/user/:user_id\", users.Delete)\n}", "func SetupRouter() *mux.Router {\n\trouter := mux.NewRouter()\n\n\tcontentManager, err := services.NewContentManagerService()\n\tif err != nil {\n\t\tlog.Fatalf(\"Creating the ContentManagerService Failed %s\", err)\n\t}\n\n\trouter.HandleFunc(\"/articles\", contentManager.CreateAnArticle).Methods(\"POST\")\n\trouter.HandleFunc(\"/articles/{uuid}\", contentManager.RetrieveAnArticle).Methods(\"GET\")\n\trouter.HandleFunc(\"/articles/{uuid}\", contentManager.DeleteAnArticle).Methods(\"DELETE\")\n\trouter.HandleFunc(\"/articles/{uuid}\", contentManager.UpdateAnArticle).Methods(\"PUT\")\n\n\trouter.HandleFunc(\"/articles/search-by-topic/{topic}\", contentManager.SearchArticlesByTopic).Methods(\"GET\")\n\trouter.HandleFunc(\"/articles/search-by-status/{status}\", contentManager.SearchArticlesByStatus).Methods(\"GET\")\n\trouter.HandleFunc(\"/articles\", contentManager.ListAllArticles).Methods(\"GET\")\n\n\trouter.HandleFunc(\"/articles/tags\", contentManager.CreateATag).Methods(\"POST\")\n\trouter.HandleFunc(\"/articles/tags/{uuid}\", contentManager.RenameATag).Methods(\"PUT\")\n\trouter.HandleFunc(\"/articles/tags/{uuid}\", contentManager.RetrieveATag).Methods(\"GET\")\n\trouter.HandleFunc(\"/articles/all/tags\", contentManager.ListAllTags).Methods(\"GET\")\n\n\t/* attach a tag to an article, remove a tag from an article\n\trouter.HandleFunc(\"/articles/{article-uuid}/tags/{tag-uuid}\", contentManager.AttachTagToArticle).Methods(\"POST\")\n\trouter.HandleFunc(\"/articles/{article-uuid}/tags/{tag-uuid}\", contentManager.RemoveTagFromArticle).Methods(\"DELETE\")\n\t*/\n\n\treturn router\n}", "func Router() chi.Router {\n\tr := chi.NewRouter()\n\n\tentity := \"claims\"\n\n\tr.With(util.CheckKetoPolicy(entity, \"get\")).Get(\"/\", list)\n\tr.With(util.CheckKetoPolicy(entity, \"create\")).Post(\"/\", create)\n\n\tr.Route(\"/{claim_id}\", func(r chi.Router) {\n\t\tr.With(util.CheckKetoPolicy(entity, \"get\")).Get(\"/\", details)\n\t\tr.With(util.CheckKetoPolicy(entity, \"update\")).Put(\"/\", update)\n\t\tr.With(util.CheckKetoPolicy(entity, \"delete\")).Delete(\"/\", delete)\n\t})\n\n\treturn r\n\n}", "func configureRoutes() *mux.Router {\n\t// establish router\n\trouter := mux.NewRouter()\n\n\t// add routes\n\t// Basic service endpoints\n\trouter.HandleFunc(\"/\", home).Methods(\"GET\", \"OPTIONS\", \"POST\", \"PUT\", \"DELETE\")\n\trouter.HandleFunc(\"/ping\", ping).Methods(\"GET\", \"OPTIONS\")\n\trouter.HandleFunc(\"/register\", register).Methods(\"POST\", \"OPTIONS\")\n\trouter.HandleFunc(\"/auth\", auth).Methods(\"GET\", \"OPTIONS\")\n\n\t// Basic image creation endpoint\n\trouter.HandleFunc(\"/image\", addImage).Methods(\"POST\", \"OPTIONS\")\n\n\t// Image data endpoints\n\trouter.HandleFunc(\"/image/{uid:[0-9]+}/{fileId}\", getImage).Methods(\"GET\", \"OPTIONS\")\n\trouter.HandleFunc(\"/image/{uid:[0-9]+}/{fileId}\", delImage).Methods(\"DELETE\", \"OPTIONS\")\n\trouter.HandleFunc(\"/image/{uid:[0-9]+}/{fileId}\", updateImage).Methods(\"PUT\", \"OPTIONS\")\n\n\t// Image meta query methods\n\trouter.HandleFunc(\"/image/meta?\", imageMetaRequest).Queries(\n\t\t\"page\", \"{page:[0-9]+}\",\n\t\t\"id\", \"{id:[0-9]+}\",\n\t\t\"uid\", \"{uid:[0-9]+}\",\n\t\t\"title\", \"{title}\",\n\t\t\"encoding\", \"{encoding}\",\n\t\t\"shareable\", \"{shareable)\").Methods(\"GET\")\n\trouter.HandleFunc(\"/image/meta\", imageMetaRequest).Methods(\"GET\", \"OPTIONS\")\n\n\treturn router\n}", "func HandlePeople(w http.ResponseWriter, r *http.Request) {\n\tdb := PGSQLConnect()\n\n\trows := db.Query(FetchUsers, []interface{}{})\n\n\tvar response Response\n\tvar users []User\n\n\tfor rows.Next() {\n\t\tvar user User\n\n\t\terr := rows.Scan(&user.ID, &user.Name, &user.Mail, &user.Phone,\n\t\t\t&user.Birth,\n\t\t\t&user.Type)\n\n\t\tswitch err {\n\t\tcase sql.ErrNoRows:\n\t\t\tresponse.Status = StatusError\n\n\t\t\terrorMessage := fmt.Sprintf(\"Database request error, \"+\n\t\t\t\t\"notify the developer about %v.\", err.Error())\n\n\t\t\te := Error{\n\t\t\t\tCode: ErrorDatabaseResponse,\n\t\t\t\tDescription: errorMessage,\n\t\t\t}\n\n\t\t\tresponse.Content = e\n\t\t\tbreak\n\t\tcase nil:\n\t\t\tresponse.Status = StatusOk\n\n\t\t\tusers = append(users, user)\n\n\t\t\tresponse.Content = users\n\t\t}\n\t}\n\tmessage, err := json.Marshal(response)\n\n\tif err != nil {\n\t\tReport500(&w,\n\t\t\tfmt.Sprintf(\"[!] Error encoding data to json. Reason %v\", err))\n\t}\n\n\tw.Write(message)\n}", "func SvcPeople(w http.ResponseWriter, r *http.Request, d *ServiceData) {\n\tconst funcname = \"SvcPeople\"\n\tvar err error\n\tlib.Console(\"Entered %s\\n\", funcname)\n\t// lib.Console(\"Request: %s: BID = %d, ID = %d\\n\", d.wsSearchReq.Cmd, d.BID, d.ID)\n\n\tswitch d.wsSearchReq.Cmd {\n\tcase \"get\":\n\t\tif d.ID, err = SvcExtractIDFromURI(r.RequestURI, \"ID\", 3, w); err != nil {\n\t\t\tSvcErrorReturn(w, err, funcname)\n\t\t\treturn\n\t\t}\n\t\tgetPerson(w, r, d)\n\t\tbreak\n\tcase \"getlist\":\n\t\tgetPersonList(w, r, d)\n\t\tbreak\n\n\t// case \"save\":\n\t// \tsavePerson(w, r, d)\n\t// \tbreak\n\t// case \"delete\":\n\t// \tdeletePerson(w, r, d)\n\t// \tbreak\n\n\tdefault:\n\t\terr = fmt.Errorf(\"Unhandled command: %s\", d.wsSearchReq.Cmd)\n\t\tSvcErrorReturn(w, err, funcname)\n\t\treturn\n\t}\n}", "func assignRoutes(router *mux.Router) *mux.Router {\n\tvar logger log.Logger\n\t{\n\t\tlogger = log.NewLogfmtLogger(os.Stderr)\n\t\tlogger = log.NewSyncLogger(logger)\n\t\tlogger = level.NewFilter(logger, level.AllowDebug())\n\t\tlogger = log.With(logger,\n\t\t\t\"svc:\", \"pilot-management\",\n\t\t\t\"ts:\", log.DefaultTimestampUTC,\n\t\t\t\"caller:\", log.DefaultCaller,\n\t\t)\n\t}\n\n\tlevel.Info(logger).Log(\"msg\", \"service started\")\n\tdefer level.Info(logger).Log(\"msg\", \"service ended\")\n\n\tservice := impl.MakeServiceImpl(logger)\n\n\toptions := []httpTransport.ServerOption{\n\t\thttpTransport.ServerErrorEncoder(EncodeErrorResponse),\n\t\thttpTransport.ServerErrorLogger(logger),\n\t}\n\n\tstatusHandler := httpTransport.NewServer(\n\t\tMakeStatusEndpoint(service),\n\t\tDecodeStatusRequest,\n\t\tEncodeResponse,\n\t)\n\n\tlistPilotsHandler := httpTransport.NewServer(\n\t\tMakeListPilotsEndpoint(service),\n\t\tDecodeListPilotsRequest,\n\t\tEncodeResponse,\n\t\toptions...,\n\t)\n\n\tgetPilotHandler := httpTransport.NewServer(\n\t\tMakeGetPilotEndpoint(service),\n\t\tDecodeGetPilotRequest,\n\t\tEncodeResponse,\n\t\toptions...,\n\t)\n\n\tCreatePilotHandler := httpTransport.NewServer(\n\t\tMakeCreatePilotEndpoint(service),\n\t\tDecodeCreatePilotRequest,\n\t\tEncodeResponse,\n\t\toptions...,\n\t)\n\n\tUpdatePilotHandler := httpTransport.NewServer(\n\t\tMakeUpdatePilotEndpoint(service),\n\t\tDecodeUpdatePilotRequest,\n\t\tEncodeResponse,\n\t\toptions...,\n\t)\n\n\tDeletePilotHandler := httpTransport.NewServer(\n\t\tMakeDeletePilotEndpoint(service),\n\t\tDecodeDeletePilotRequest,\n\t\tEncodeResponse,\n\t\toptions...,\n\t)\n\n\tChangePilotStatusHandler := httpTransport.NewServer(\n\t\tMakeChangePilotStatusEndpoint(service),\n\t\tDecodeChangePilotStatusRequest,\n\t\tEncodeResponse,\n\t\toptions...,\n\t)\n\n\trouter.Handle(\"/supply/pilots/status\", statusHandler).Methods(\"GET\")\n\trouter.Handle(\"/supply/pilots\", listPilotsHandler).Methods(\"GET\")\n\trouter.Handle(\"/supply/pilots/{id}\", getPilotHandler).Methods(\"GET\")\n\trouter.Handle(\"/supply/pilots\", CreatePilotHandler).Methods(\"POST\")\n\trouter.Handle(\"/supply/pilots/{id}\", UpdatePilotHandler).Methods(\"PATCH\")\n\trouter.Handle(\"/supply/pilots/{id}\", DeletePilotHandler).Methods(\"DELETE\")\n\trouter.Handle(\"/supply/pilots/{id}/{status}\", ChangePilotStatusHandler).Methods(\"PATCH\")\n\treturn router\n}", "func createPerson(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tnewID := ps.ByName(\"id\")\n\tvar newPerson person\n\t_ = json.NewDecoder(r.Body).Decode(&newPerson)\n\tnewPerson.ID = string(newID)\n\tpeople = append(people, newPerson)\n\tjson.NewEncoder(w).Encode(people)\n}", "func RegisterStaffEndpoints(router *gin.RouterGroup) {\n\tstaffRouter := router.Group(\"\")\n\t// Annonymous Routes\n\tstaffRouter.POST(\"/login\", staffLogin)\n\n\t// Admin Routes\n\tstaffRouter.Use(middlewares.LoginRequire())\n\t{\n\t\tstaffRouter.GET(\"\", getStaffList)\n\t\tstaffRouter.GET(\"/admins\", getAdminList)\n\t\tstaffRouter.GET(\"/check/:uname/station/:sID\", checkIfUsernameExist)\n\t\tstaffRouter.GET(\"/roles\", getStaffRoleList)\n\t\tstaffRouter.GET(\"/multistation/station/:sID\", getUserByStation)\n\t\tstaffRouter.GET(\"/multistation/room/:rID\", getUserByRoom)\n\t}\n\n\tstaffRouter.Use(middlewares.SuperAdminRequired())\n\t{\n\t\tstaffRouter.GET(\"/info/:staffID\", getStaffInfomation)\n\t\tstaffRouter.POST(\"/create\", createStaff)\n\t\tstaffRouter.POST(\"/upload/image\", uploadImage)\n\t\tstaffRouter.POST(\"/reorder\", reorderStaff)\n\t\tstaffRouter.POST(\"/edit/:staffID\", editStaff)\n\t}\n}", "func initRoutes() {\r\n\trouter.Use(setUserStatus())\r\n\r\n\trouter.GET(\"/contact\", showContactForm)\r\n\trouter.POST(\"/contact\", contactPost)\r\n\trouter.GET(\"/admin\", ensureLoggedIn(), func(c *gin.Context) {\r\n\t\tc.Redirect(307, \"/admin/job_openings\")\r\n\t})\r\n\trouter.GET(\"/test\", func(c *gin.Context) {\r\n\t\tc.HTML(200, \"test.html\", nil)\r\n\t})\r\n\r\n\t// Admin Handler\r\n\tadminRoutes := router.Group(\"/admin\")\r\n\t{\r\n\t\t// Login-Logut\r\n\t\tadminRoutes.GET(\"/login\", ensureNotLoggedIn(), showLoginPage)\r\n\t\tadminRoutes.GET(\"/logout\", ensureLoggedIn(), logout)\r\n\r\n\t\t// JOB-Details\r\n\t\tadminRoutes.POST(\"/job_openings\", ensureNotLoggedIn(), performLogin)\r\n\t\tadminRoutes.GET(\"/job_openings\", ensureLoggedIn(), showIndexPage)\r\n\r\n\t\tadminRoutes.GET(\"/add_new_job\", ensureLoggedIn(), showNewJobPage)\r\n\t\tadminRoutes.POST(\"/add_new_job\", ensureLoggedIn(), addNewJob)\r\n\t\tadminRoutes.GET(\"/edit\", ensureLoggedIn(), showEditPage)\r\n\t\tadminRoutes.POST(\"/edit\", ensureLoggedIn(), editPage)\r\n\t\tadminRoutes.GET(\"/delete/:id\", ensureLoggedIn(), deleteJobList)\r\n\r\n\t\t// Blog-Details\r\n\t\tadminRoutes.GET(\"/blogs\", ensureLoggedIn(), showBlogs)\r\n\t\tadminRoutes.GET(\"/add_blog\", ensureLoggedIn(), showAddBlogPage)\r\n\t\tadminRoutes.POST(\"/add_blog\", ensureLoggedIn(), AddBlogPage)\r\n\t\tadminRoutes.GET(\"/editBlog\", ensureLoggedIn(), showEditBlogPage)\r\n\t\tadminRoutes.POST(\"/editBlog\", ensureLoggedIn(), editBlog)\r\n\t\tadminRoutes.GET(\"/blogs/delete/:id\", ensureLoggedIn(), deleteBlog)\r\n\r\n\t\t// Category\r\n\t\tadminRoutes.GET(\"/categories\", ensureLoggedIn(), showCategories)\r\n\t\tadminRoutes.POST(\"/categories\", ensureLoggedIn(), addCategory)\r\n\t\tadminRoutes.POST(\"/categorieEdit/:id\", ensureLoggedIn(), editCategory)\r\n\t\tadminRoutes.GET(\"/categories/delete/:id\", ensureLoggedIn(), deleteCategory)\r\n\r\n\t\t// Tag\r\n\t\tadminRoutes.GET(\"/tags\", ensureLoggedIn(), showTags)\r\n\t\tadminRoutes.POST(\"/tags\", ensureLoggedIn(), addTag)\r\n\t\tadminRoutes.POST(\"/tags/edit/:id\", ensureLoggedIn(), editTag)\r\n\t\tadminRoutes.GET(\"/tags/delete/:id\", ensureLoggedIn(), deleteTag)\r\n\t}\r\n}", "func (ctl *RentController) register() {\n\trents := ctl.router.Group(\"/rents\")\n\n\trents.GET(\"\", ctl.ListRent)\n\n\t// CRUD\n\trents.POST(\"\", ctl.CreateRent)\n\trents.GET(\":id\", ctl.GetRent)\n\trents.PUT(\":id\", ctl.UpdateRent)\n\trents.DELETE(\":id\", ctl.DeleteRent)\n}", "func (ctl *ResearchController) register() {\n\tresearches := ctl.router.Group(\"/researches\")\n\tresearches.GET(\"\", ctl.ListResearch)\n\n searchresearchs := ctl.router.Group(\"/searchresearchs\")\n\tsearchresearchs.GET(\"\",ctl.GetSearchResearch)\n\n\t// CRUD\n\tresearches.POST(\"\", ctl.CreateResearch)\n\tresearches.GET(\":id\", ctl.GetResearch)\n\tresearches.PUT(\":id\", ctl.UpdateResearch)\n\tresearches.DELETE(\":id\", ctl.DeleteResearch)\n}", "func createRoutes(pHandler pingInterface.Handler, cHandler customerDomain.Handler) {\n\tv1 := router.Group(baseRouteV1)\n\t{\n\t\tv1.GET(\"ping\", pHandler.Ping)\n\t\tv1.POST(\"customers\", cHandler.Create)\n\t}\n}", "func MapRouteBySchema(server *Server, dataStore db.DB, s *schema.Schema) {\n\tif s.IsAbstract() {\n\t\treturn\n\t}\n\troute := server.martini\n\n\tsingleURL := s.GetSingleURL()\n\tpluralURL := s.GetPluralURL()\n\tsingleURLWithParents := s.GetSingleURLWithParents()\n\tpluralURLWithParents := s.GetPluralURLWithParents()\n\n\t//load extension environments\n\tenvironmentManager := extension.GetManager()\n\tif _, ok := environmentManager.GetEnvironment(s.ID); !ok {\n\t\tenv, err := server.NewEnvironmentForPath(s.ID, pluralURL)\n\t\tif err != nil {\n\t\t\tlog.Fatal(fmt.Sprintf(\"[%s] %v\", pluralURL, err))\n\t\t}\n\t\tenvironmentManager.RegisterEnvironment(s.ID, env)\n\t}\n\n\tlog.Debug(\"[Plural Path] %s\", pluralURL)\n\tlog.Debug(\"[Singular Path] %s\", singleURL)\n\tlog.Debug(\"[Plural Path With Parents] %s\", pluralURLWithParents)\n\tlog.Debug(\"[Singular Path With Parents] %s\", singleURLWithParents)\n\n\t//setup list route\n\tgetPluralFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {\n\t\taddJSONContentTypeHeader(w)\n\t\tfillInContext(context, dataStore, r, w, s, p, server.sync, identityService, nil)\n\t\tif err := resources.GetMultipleResources(context, dataStore, s, r.URL.Query()); err != nil {\n\t\t\thandleError(w, err)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Add(\"X-Total-Count\", fmt.Sprint(context[\"total\"]))\n\t\troutes.ServeJson(w, context[\"response\"])\n\t}\n\troute.Get(pluralURL, middleware.Authorization(schema.ActionRead), getPluralFunc)\n\troute.Get(pluralURLWithParents, middleware.Authorization(schema.ActionRead), func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {\n\t\taddParamToQuery(r, schema.FormatParentID(s.Parent), p[s.Parent])\n\t\tgetPluralFunc(w, r, p, identityService, context)\n\t})\n\n\t//setup show route\n\tgetSingleFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {\n\t\taddJSONContentTypeHeader(w)\n\t\tfillInContext(context, dataStore, r, w, s, p, server.sync, identityService, nil)\n\t\tid := p[\"id\"]\n\t\tif err := resources.GetSingleResource(context, dataStore, s, id); err != nil {\n\t\t\thandleError(w, err)\n\t\t\treturn\n\t\t}\n\t\troutes.ServeJson(w, context[\"response\"])\n\t}\n\troute.Get(singleURL, middleware.Authorization(schema.ActionRead), getSingleFunc)\n\troute.Get(singleURLWithParents, middleware.Authorization(schema.ActionRead), func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {\n\t\taddParamToQuery(r, schema.FormatParentID(s.Parent), p[s.Parent])\n\t\tgetSingleFunc(w, r, p, identityService, context)\n\t})\n\n\t//setup delete route\n\tdeleteSingleFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {\n\t\taddJSONContentTypeHeader(w)\n\t\tfillInContext(context, dataStore, r, w, s, p, server.sync, identityService, nil)\n\t\tid := p[\"id\"]\n\t\tif err := resources.DeleteResource(context, dataStore, s, id); err != nil {\n\t\t\thandleError(w, err)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusNoContent)\n\t}\n\troute.Delete(singleURL, middleware.Authorization(schema.ActionDelete), deleteSingleFunc)\n\troute.Delete(singleURLWithParents, middleware.Authorization(schema.ActionDelete), func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {\n\t\taddParamToQuery(r, schema.FormatParentID(s.Parent), p[s.Parent])\n\t\tdeleteSingleFunc(w, r, p, identityService, context)\n\t})\n\n\t//setup create route\n\tpostPluralFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {\n\t\taddJSONContentTypeHeader(w)\n\t\tdataMap, err := middleware.ReadJSON(r)\n\t\tif err != nil {\n\t\t\thandleError(w, resources.NewResourceError(err, fmt.Sprintf(\"Failed to parse data: %s\", err), resources.WrongData))\n\t\t\treturn\n\t\t}\n\t\tdataMap = removeResourceWrapper(s, dataMap)\n\t\tfillInContext(context, dataStore, r, w, s, p, server.sync, identityService, dataMap)\n\t\tif s.Parent != \"\" {\n\t\t\tif _, ok := dataMap[s.ParentID()]; !ok {\n\t\t\t\tqueryParams := r.URL.Query()\n\t\t\t\tparentIDParam := queryParams.Get(s.ParentID())\n\t\t\t\tif parentIDParam != \"\" {\n\t\t\t\t\tdataMap[s.ParentID()] = parentIDParam\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := resources.CreateResource(context, dataStore, s, dataMap); err != nil {\n\t\t\thandleError(w, err)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusCreated)\n\t\troutes.ServeJson(w, context[\"response\"])\n\t}\n\troute.Post(pluralURL, middleware.Authorization(schema.ActionCreate), postPluralFunc)\n\troute.Post(pluralURLWithParents, middleware.Authorization(schema.ActionCreate),\n\t\tfunc(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {\n\t\t\taddParamToQuery(r, schema.FormatParentID(s.Parent), p[s.Parent])\n\t\t\tpostPluralFunc(w, r, p, identityService, context)\n\t\t})\n\n\t//setup create or update route\n\tputSingleFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {\n\t\taddJSONContentTypeHeader(w)\n\t\tid := p[\"id\"]\n\t\tdataMap, err := middleware.ReadJSON(r)\n\t\tif err != nil {\n\t\t\thandleError(w, resources.NewResourceError(err, fmt.Sprintf(\"Failed to parse data: %s\", err), resources.WrongData))\n\t\t\treturn\n\t\t}\n\t\tdataMap = removeResourceWrapper(s, dataMap)\n\t\tfillInContext(context, dataStore, r, w, s, p, server.sync, identityService, dataMap)\n\t\tif isCreated, err := resources.CreateOrUpdateResource(\n\t\t\tcontext, dataStore, s, id, dataMap); err != nil {\n\t\t\thandleError(w, err)\n\t\t\treturn\n\t\t} else if isCreated {\n\t\t\tw.WriteHeader(http.StatusCreated)\n\t\t}\n\t\troutes.ServeJson(w, context[\"response\"])\n\t}\n\troute.Put(singleURL, middleware.Authorization(schema.ActionUpdate), putSingleFunc)\n\troute.Put(singleURLWithParents, middleware.Authorization(schema.ActionUpdate),\n\t\tfunc(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {\n\t\t\taddParamToQuery(r, schema.FormatParentID(s.Parent), p[s.Parent])\n\t\t\tputSingleFunc(w, r, p, identityService, context)\n\t\t})\n\n\t//setup update route\n\tpatchSingleFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {\n\t\taddJSONContentTypeHeader(w)\n\t\tid := p[\"id\"]\n\t\tdataMap, err := middleware.ReadJSON(r)\n\t\tif err != nil {\n\t\t\thandleError(w, resources.NewResourceError(err, fmt.Sprintf(\"Failed to parse data: %s\", err), resources.WrongData))\n\t\t\treturn\n\t\t}\n\t\tdataMap = removeResourceWrapper(s, dataMap)\n\t\tfillInContext(context, dataStore, r, w, s, p, server.sync, identityService, dataMap)\n\t\tif err := resources.UpdateResource(\n\t\t\tcontext, dataStore, s, id, dataMap); err != nil {\n\t\t\thandleError(w, err)\n\t\t\treturn\n\t\t}\n\t\troutes.ServeJson(w, context[\"response\"])\n\t}\n\troute.Patch(singleURL, middleware.Authorization(schema.ActionUpdate), patchSingleFunc)\n\troute.Patch(singleURLWithParents, middleware.Authorization(schema.ActionUpdate),\n\t\tfunc(w http.ResponseWriter, r *http.Request, p martini.Params, identityService middleware.IdentityService, context middleware.Context) {\n\t\t\taddParamToQuery(r, schema.FormatParentID(s.Parent), p[s.Parent])\n\t\t\tpatchSingleFunc(w, r, p, identityService, context)\n\t\t})\n\n\t//Custom action support\n\tfor _, actionExt := range s.Actions {\n\t\taction := actionExt\n\t\tActionFunc := func(w http.ResponseWriter, r *http.Request, p martini.Params,\n\t\t\tidentityService middleware.IdentityService, auth schema.Authorization, context middleware.Context) {\n\t\t\taddJSONContentTypeHeader(w)\n\t\t\tid := p[\"id\"]\n\t\t\tinput := make(map[string]interface{})\n\t\t\tif action.InputSchema != nil && action.Protocol == \"\" {\n\t\t\t\tvar err error\n\t\t\t\tinput, err = middleware.ReadJSON(r)\n\t\t\t\tif err != nil {\n\t\t\t\t\thandleError(w, resources.NewResourceError(err, fmt.Sprintf(\"Failed to parse data: %s\", err), resources.WrongData))\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tfillInContext(context, dataStore, r, w, s, p, server.sync, identityService, input)\n\n\t\t\tif err := resources.ActionResource(context, dataStore, s, action, id, input); err != nil {\n\t\t\t\thandleError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif response, ok := context[\"response\"]; ok {\n\t\t\t\troutes.ServeJson(w, response)\n\t\t\t}\n\t\t}\n\t\troute.AddRoute(action.Method, s.GetActionURL(action.Path), middleware.Authorization(action.ID), ActionFunc)\n\t\tif s.ParentSchema != nil {\n\t\t\troute.AddRoute(action.Method, s.GetActionURLWithParents(action.Path), middleware.Authorization(action.ID), ActionFunc)\n\t\t}\n\t}\n}", "func mapRoutes() {\n\t//http.HandleFunc(\"/user\", controllers.GetUser)\n}", "func ApplyRoutes(r *gin.RouterGroup) {\n\tclients := r.Group(\"/clients\")\n\t{\n\t\tclients.POST(\"/\", middlewares.Authorized, create)\n\t\tclients.GET(\"/\", middlewares.Authorized, list)\n\t}\n}", "func Index(w http.ResponseWriter, r *http.Request) {\r\n\t\r\n\tdb := Database.Dbconn()\r\n\tselDB, err := db.Query(\"SELECT * FROM employee.dbo.employee\")\r\n\tif err != nil {\r\n\t\tpanic(err.Error())\r\n\t}\r\n\r\n\tper := persona{}\r\n\tres := []persona{}\r\n\r\n\tfor selDB.Next() {\r\n\t\tvar id string\r\n\t\tvar name string\r\n\t\tvar location string\r\n\r\n\t\terr = selDB.Scan(&id, &name, &location)\r\n\t\tif err != nil {\r\n\t\t\tpanic(err.Error())\r\n\t\t}\r\n\t\tper.Id = id\r\n\t\tper.Name = name\r\n\t\tper.Location = location\r\n\r\n\t\tres = append(res, per)\r\n\t}\r\n\ttmpl.ExecuteTemplate(w, \"Index\", res)\r\n\tdefer db.Close()\r\n}", "func main() {\n\trouter := gin.Default()\n\n\t// This handler will match /user/john but will not match /user/ or /user\n\trouter.GET(\"/user/:name\", func(c *gin.Context) {\n\t\tname := c.Param(\"name\")\n\t\tc.String(http.StatusOK, \"Hello %s\", name)\n\t})\n\n\t// However, this one will match /user/john/ and also /user/john/send\n\t// If no other routers match /user/john, it will redirect to /user/john/\n\trouter.GET(\"/user/:name/*action\", func(c *gin.Context) {\n\t\tname := c.Param(\"name\")\n\t\taction := c.Param(\"action\")\n\t\tmessage := name + \" is \" + action\n\t\tc.String(http.StatusOK, message)\n\t})\n\n\t// Query string parameters are parsed using the existing underlying request object.\n\t// The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe\n\trouter.GET(\"/hola\", func(c *gin.Context) {\n\t\tnombre := c.DefaultQuery(\"nombre\", \"Guest\")\n\t\tapellido := c.Query(\"apellido\") // shortcut for c.Request.URL.Query().Get(\"lastname\")\n\n\t\tc.String(http.StatusOK, \"Hello %s %s\", nombre, apellido)\n\t})\n\trouter.Run(\":8080\")\n}", "func (ctl *EquipmentrentalController) register() {\n\tEqrentals := ctl.router.Group(\"/equipmentrentals\")\n\tEqrentalss := ctl.router.Group(\"/equipmentrentalbymembers\")\n\tEqrentalss.GET(\"\", ctl.GetEquipmentrentalbyMember)\n\tEqrentals.GET(\"\", ctl.ListEquipmentrental)\n\n\t// CRUD\n\tEqrentals.POST(\"\", ctl.CreateEquipmentrental)\n\tEqrentals.GET(\":id\", ctl.GetEquipmentrental)\n}", "func BookRoutes(rg *gin.RouterGroup, db *repo.LibraryDatabase) {\n\tbooksRouter := rg.Group(\"/books\")\n\n\tbooksRouter.POST(\"/\", addBookHandler(db))\n\tbooksRouter.GET(\"/on-hold\", getBooksOnHoldHandler(db))\n}" ]
[ "0.67869747", "0.67589456", "0.6640335", "0.6442103", "0.58659965", "0.56205046", "0.55636376", "0.5562881", "0.5536978", "0.5526658", "0.5520917", "0.54956365", "0.54703736", "0.54550976", "0.5444999", "0.54362804", "0.5415051", "0.53973025", "0.5367491", "0.53587633", "0.5330962", "0.53066117", "0.5304349", "0.5298595", "0.5286063", "0.5281689", "0.52792364", "0.5273156", "0.5271949", "0.5270754", "0.526977", "0.5261317", "0.5259778", "0.5250543", "0.52504647", "0.52363575", "0.5222265", "0.5218962", "0.520191", "0.51981306", "0.5197458", "0.5196607", "0.51920646", "0.51907635", "0.51806426", "0.5178173", "0.5165723", "0.5160037", "0.5155291", "0.5153615", "0.51532704", "0.51492506", "0.51275706", "0.512239", "0.51201403", "0.5116595", "0.51094747", "0.51052123", "0.510178", "0.510103", "0.50999933", "0.5098664", "0.50962466", "0.5087349", "0.5079172", "0.5077427", "0.507645", "0.5065957", "0.5065576", "0.5058524", "0.5055165", "0.5050777", "0.5042191", "0.50417763", "0.5039951", "0.5038658", "0.5038352", "0.50370294", "0.50333416", "0.50330365", "0.5024405", "0.5016505", "0.5014372", "0.5010624", "0.5003089", "0.49858627", "0.49835917", "0.49821696", "0.49781796", "0.49725932", "0.49694163", "0.4967652", "0.49596676", "0.49544808", "0.49539414", "0.4951012", "0.49462226", "0.49458176", "0.49430287", "0.49420232" ]
0.74560905
0
Validate validates this io k8s api core v1 scoped resource selector requirement
func (m *IoK8sAPICoreV1ScopedResourceSelectorRequirement) Validate(formats strfmt.Registry) error { var res []error if err := m.validateOperator(formats); err != nil { res = append(res, err) } if err := m.validateScopeName(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pr *ResourceDescription) Validate() error {\n\tif len(pr.Kinds) == 0 {\n\t\treturn errors.New(\"The Kind is not specified\")\n\t}\n\n\tif pr.Selector != nil {\n\t\tselector, err := metav1.LabelSelectorAsSelector(pr.Selector)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trequirements, _ := selector.Requirements()\n\t\tif len(requirements) == 0 {\n\t\t\treturn errors.New(\"The requirements are not specified in selector\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *JsonToMetadata_Selector) Validate() error {\n\treturn m.validate(false)\n}", "func (s *Selector) Validate(ver, path string, ignoreStatus, ignoreSpec bool) []error {\n\treturn nil\n}", "func (t *OpenconfigSystem_System_Logging_Console_Selectors_Selector) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_Console_Selectors_Selector\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (i LabelSelectorInput) Validate() error {\n\treturn validation.ValidateStruct(&i,\n\t\tvalidation.Field(&i.Key, validation.In(\"global_subaccount_id\")),\n\t)\n}", "func (s *OpenconfigOfficeAp_System_Logging_Console_Selectors_Selector) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Logging_Console_Selectors_Selector\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors_Selector) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors_Selector\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *IoK8sAPICoreV1TopologySelectorLabelRequirement) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateValues(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func validateEndpointRequestResource(req *request.Request, resource arn.Resource) error {\n\tresReq := s3shared.ResourceRequest{Request: req, Resource: resource}\n\n\tif len(resReq.Request.ClientInfo.PartitionID) != 0 && resReq.IsCrossPartition() {\n\t\treturn s3shared.NewClientPartitionMismatchError(resource,\n\t\t\treq.ClientInfo.PartitionID, aws.StringValue(req.Config.Region), nil)\n\t}\n\n\tif !resReq.AllowCrossRegion() && resReq.IsCrossRegion() {\n\t\treturn s3shared.NewClientRegionMismatchError(resource,\n\t\t\treq.ClientInfo.PartitionID, aws.StringValue(req.Config.Region), nil)\n\t}\n\n\t// Accelerate not supported\n\tif aws.BoolValue(req.Config.S3UseAccelerate) {\n\t\treturn s3shared.NewClientConfiguredForAccelerateError(resource,\n\t\t\treq.ClientInfo.PartitionID, aws.StringValue(req.Config.Region), nil)\n\t}\n\treturn nil\n}", "func (m LabelSelectorOperator) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *IoK8sAPICoreV1ResourceQuotaSpec) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateHard(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateScopeSelector(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *IoK8sApimachineryPkgApisMetaV1LabelSelectorRequirement) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateKey(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOperator(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (opts resourceOptions) validate() error {\n\t// Check that the required flags did not get a flag as their value.\n\t// We can safely look for a '-' as the first char as none of the fields accepts it.\n\t// NOTE: We must do this for all the required flags first or we may output the wrong\n\t// error as flags may seem to be missing because Cobra assigned them to another flag.\n\tif strings.HasPrefix(opts.Group, \"-\") {\n\t\treturn fmt.Errorf(groupPresent)\n\t}\n\tif strings.HasPrefix(opts.Version, \"-\") {\n\t\treturn fmt.Errorf(versionPresent)\n\t}\n\tif strings.HasPrefix(opts.Kind, \"-\") {\n\t\treturn fmt.Errorf(kindPresent)\n\t}\n\n\t// We do not check here if the GVK values are empty because that would\n\t// make them mandatory and some plugins may want to set default values.\n\t// Instead, this is checked by resource.GVK.Validate()\n\n\treturn nil\n}", "func ValidateControllerRegistrationSpec(spec *core.ControllerRegistrationSpec, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tvar (\n\t\tresourcesPath = fldPath.Child(\"resources\")\n\t\tdeploymentPath = fldPath.Child(\"deployment\")\n\n\t\tresources = make(map[string]string, len(spec.Resources))\n\t\tcontrolsResourcesPrimarily = false\n\t)\n\n\tfor i, resource := range spec.Resources {\n\t\tidxPath := resourcesPath.Index(i)\n\n\t\tif len(resource.Kind) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"kind\"), \"field is required\"))\n\t\t}\n\n\t\tif !extensionsv1alpha1.ExtensionKinds.Has(resource.Kind) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(idxPath.Child(\"kind\"), resource.Kind, extensionsv1alpha1.ExtensionKinds.UnsortedList()))\n\t\t}\n\n\t\tif len(resource.Type) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"type\"), \"field is required\"))\n\t\t}\n\t\tif t, ok := resources[resource.Kind]; ok && t == resource.Type {\n\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath, common.ExtensionID(resource.Kind, resource.Type)))\n\t\t}\n\t\tif resource.Kind != extensionsv1alpha1.ExtensionResource {\n\t\t\tif resource.GloballyEnabled != nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(idxPath.Child(\"globallyEnabled\"), fmt.Sprintf(\"field must not be set when kind != %s\", extensionsv1alpha1.ExtensionResource)))\n\t\t\t}\n\t\t\tif resource.ReconcileTimeout != nil {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(idxPath.Child(\"reconcileTimeout\"), fmt.Sprintf(\"field must not be set when kind != %s\", extensionsv1alpha1.ExtensionResource)))\n\t\t\t}\n\t\t}\n\n\t\tresources[resource.Kind] = resource.Type\n\t\tif resource.Primary == nil || *resource.Primary {\n\t\t\tcontrolsResourcesPrimarily = true\n\t\t}\n\t}\n\n\tif spec.Deployment != nil {\n\t\tif policy := spec.Deployment.Policy; policy != nil && !availablePolicies.Has(string(*policy)) {\n\t\t\tallErrs = append(allErrs, field.NotSupported(deploymentPath.Child(\"policy\"), *policy, availablePolicies.List()))\n\t\t}\n\n\t\tif spec.Deployment.SeedSelector != nil {\n\t\t\tif controlsResourcesPrimarily {\n\t\t\t\tallErrs = append(allErrs, field.Forbidden(deploymentPath.Child(\"seedSelector\"), \"specifying a seed selector is not allowed when controlling resources primarily\"))\n\t\t\t}\n\n\t\t\tallErrs = append(allErrs, metav1validation.ValidateLabelSelector(spec.Deployment.SeedSelector, deploymentPath.Child(\"seedSelector\"))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}", "func (t *OpenconfigSystem_System_Logging_Console_Selectors_Selector_Config) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_Console_Selectors_Selector_Config\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors_Selector) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors_Selector\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *OpenconfigSystem_System_Logging_Console_Selectors_Selector_State) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_Console_Selectors_Selector_State\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *ScaledObjectReconciler) checkTargetResourceIsScalable(logger logr.Logger, scaledObject *kedav1alpha1.ScaledObject) (kedav1alpha1.GroupVersionKindResource, error) {\n\tgvkr, err := kedautil.ParseGVKR(r.restMapper, scaledObject.Spec.ScaleTargetRef.APIVersion, scaledObject.Spec.ScaleTargetRef.Kind)\n\tif err != nil {\n\t\tlogger.Error(err, \"Failed to parse Group, Version, Kind, Resource\", \"apiVersion\", scaledObject.Spec.ScaleTargetRef.APIVersion, \"kind\", scaledObject.Spec.ScaleTargetRef.Kind)\n\t\treturn gvkr, err\n\t}\n\tgvkString := gvkr.GVKString()\n\tlogger.V(1).Info(\"Parsed Group, Version, Kind, Resource\", \"GVK\", gvkString, \"Resource\", gvkr.Resource)\n\n\t// let's try to detect /scale subresource\n\tscale, errScale := (*r.scaleClient).Scales(scaledObject.Namespace).Get(context.TODO(), gvkr.GroupResource(), scaledObject.Spec.ScaleTargetRef.Name, metav1.GetOptions{})\n\tif errScale != nil {\n\t\t// not able to get /scale subresource -> let's check if the resource even exist in the cluster\n\t\tunstruct := &unstructured.Unstructured{}\n\t\tunstruct.SetGroupVersionKind(gvkr.GroupVersionKind())\n\t\tif err := r.Client.Get(context.TODO(), client.ObjectKey{Namespace: scaledObject.Namespace, Name: scaledObject.Spec.ScaleTargetRef.Name}, unstruct); err != nil {\n\t\t\t// resource doesn't exist\n\t\t\tlogger.Error(err, \"Target resource doesn't exist\", \"resource\", gvkString, \"name\", scaledObject.Spec.ScaleTargetRef.Name)\n\t\t\treturn gvkr, err\n\t\t}\n\t\t// resource exist but doesn't expose /scale subresource\n\t\tlogger.Error(errScale, \"Target resource doesn't expose /scale subresource\", \"resource\", gvkString, \"name\", scaledObject.Spec.ScaleTargetRef.Name)\n\t\treturn gvkr, errScale\n\t}\n\n\t// if it is not already present in ScaledObject Status:\n\t// - store discovered GVK and GVKR\n\t// - store original scaleTarget's replica count (before scaling with KEDA)\n\tif scaledObject.Status.ScaleTargetKind != gvkString || scaledObject.Status.OriginalReplicaCount == nil {\n\t\tstatus := scaledObject.Status.DeepCopy()\n\t\tif scaledObject.Status.ScaleTargetKind != gvkString {\n\t\t\tstatus.ScaleTargetKind = gvkString\n\t\t\tstatus.ScaleTargetGVKR = &gvkr\n\t\t}\n\t\tif scaledObject.Status.OriginalReplicaCount == nil {\n\t\t\tstatus.OriginalReplicaCount = &scale.Spec.Replicas\n\t\t}\n\n\t\tif err := kedacontrollerutil.UpdateScaledObjectStatus(r.Client, logger, scaledObject, status); err != nil {\n\t\t\treturn gvkr, err\n\t\t}\n\t\tlogger.Info(\"Detected resource targeted for scaling\", \"resource\", gvkString, \"name\", scaledObject.Spec.ScaleTargetRef.Name)\n\t}\n\n\treturn gvkr, nil\n}", "func validateResource(request resource.Quantity, limit resource.Quantity, resourceName corev1.ResourceName) []error {\n\tvalidationErrors := make([]error, 0)\n\tif !limit.IsZero() && request.Cmp(limit) > 0 {\n\t\tvalidationErrors = append(validationErrors, errors.Errorf(\"Request must be less than or equal to %s limit\", resourceName))\n\t}\n\tif request.Cmp(resource.Quantity{}) < 0 {\n\t\tvalidationErrors = append(validationErrors, errors.Errorf(\"Resource %s request value must be non negative\", resourceName))\n\t}\n\tif limit.Cmp(resource.Quantity{}) < 0 {\n\t\tvalidationErrors = append(validationErrors, errors.Errorf(\"Resource %s limit value must be non negative\", resourceName))\n\t}\n\n\treturn validationErrors\n}", "func (r *ResourceSpec) Valid() bool {\n\tif r.Name == \"\" {\n\t\tfmt.Println(\"no resource spec label\")\n\t\treturn false\n\t}\n\n\tfor _, c := range r.Credentials {\n\t\tif !c.Valid() {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (t *OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors_Selector_Config) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors_Selector_Config\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func resourceVolterraK8SPodSecurityPolicy() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceVolterraK8SPodSecurityPolicyCreate,\n\t\tRead: resourceVolterraK8SPodSecurityPolicyRead,\n\t\tUpdate: resourceVolterraK8SPodSecurityPolicyUpdate,\n\t\tDelete: resourceVolterraK8SPodSecurityPolicyDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\"annotations\": {\n\t\t\t\tType: schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"description\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"disable\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"labels\": {\n\t\t\t\tType: schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"namespace\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"psp_spec\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"allow_privilege_escalation\": {\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"allowed_capabilities\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"capabilities\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_allowed_capabilities\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"allowed_csi_drivers\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"allowed_flex_volumes\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"allowed_host_paths\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"path_prefix\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"read_only\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"allowed_proc_mounts\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"allowed_unsafe_sysctls\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"default_allow_privilege_escalation\": {\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"default_capabilities\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"capabilities\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_default_capabilities\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"drop_capabilities\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"capabilities\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_drop_capabilities\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"forbidden_sysctls\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"fs_group_strategy_options\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"id_ranges\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"max_id\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"min_id\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"rule\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_fs_groups\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_run_as_group\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"run_as_group\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"id_ranges\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"max_id\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"min_id\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"rule\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"host_ipc\": {\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"host_network\": {\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"host_pid\": {\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"host_port_ranges\": {\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"privileged\": {\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"read_only_root_filesystem\": {\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_runtime_class\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"runtime_class\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"allowed_runtime_class_names\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"default_runtime_class_name\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_se_linux_options\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"se_linux_options\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"level\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"role\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"rule\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"type\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"user\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_supplemental_groups\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"supplemental_groups\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"id_ranges\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"max_id\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"min_id\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"rule\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"no_run_as_user\": {\n\n\t\t\t\t\t\t\tType: schema.TypeBool,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"run_as_user\": {\n\n\t\t\t\t\t\t\tType: schema.TypeSet,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"id_ranges\": {\n\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"max_id\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\t\t\t\"min_id\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"rule\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"volumes\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"yaml\": {\n\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t},\n\t}\n}", "func (m *ResourceControlUpdateRequest) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidResource(api *kit.API, lookupOrgByResourceID func(context.Context, influxdb.ID) (influxdb.ID, error)) kit.Middleware {\n\treturn func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t\tstatusW := kit.NewStatusResponseWriter(w)\n\t\t\tid, err := influxdb.IDFromString(chi.URLParam(r, \"id\"))\n\t\t\tif err != nil {\n\t\t\t\tapi.Err(w, ErrCorruptID(err))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tctx := r.Context()\n\n\t\t\torgID, err := lookupOrgByResourceID(ctx, *id)\n\t\t\tif err != nil {\n\t\t\t\tapi.Err(w, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tnext.ServeHTTP(statusW, r.WithContext(context.WithValue(ctx, ctxOrgKey, orgID)))\n\t\t}\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func (t *OpenconfigSystem_System_Logging_Console_Selectors) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_Console_Selectors\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *Resource) Valid() bool {\n\tif r.Name == \"\" {\n\t\tfmt.Println(\"no resource spec label\")\n\t\treturn false\n\t}\n\n\tfor _, c := range r.Credentials {\n\t\tif !c.Valid() {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (s *OpenconfigOfficeAp_System_Logging_Console_Selectors) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Logging_Console_Selectors\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func validateNodeSelector(version int, s string) {\n\t_, err := selector.Parse(s)\n\tif err != nil {\n\t\tlog.Errorf(\"Invalid node selector '%s' for version %d: %s\", s, version, err)\n\t\tutils.Terminate()\n\t}\n}", "func (s *OpenconfigOfficeAp_System_Logging_Console_Selectors_Selector_State) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Logging_Console_Selectors_Selector_State\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (d *sequenceValidator) ValidateResource(resource *datautils.Resource) *models.ErrorResponseErrors {\n\n\tif !resource.IsCollection() && !resource.IsObject() {\n\t\t// Nothing to do here, this is not a Collection or Object\n\t\treturn nil\n\t}\n\n\t// Load the member resource\n\tstructuralMd := resource.Structural()\n\tif !structuralMd.HasKey(\"hasMemberOrders\") {\n\t\t// Nothing to do here, there are no orders to validate\n\t\treturn nil\n\t}\n\tif !structuralMd.HasKey(\"hasMember\") {\n\t\t// Must have hasMember if they have hasMemberOrders\n\t\treturn d.buildErrors(\"Resource has 'hasMemberOrders' but does not have 'hasMember'\", \"structural.hasMember\")\n\t}\n\tmemberOrders := structuralMd.GetA(\"hasMemberOrders\")\n\tmemberIds := structuralMd.GetA(\"hasMember\").GetS()\n\n\tfor _, order := range memberOrders.GetObj() {\n\t\t// check that order.members is a subset of memberIds\n\t\tmembersOfOrder := order.GetA(\"members\").GetS()\n\t\tif !subset(membersOfOrder, memberIds) {\n\t\t\treturn d.buildErrors(\"'hasMemberOrders.members' must be a subset of 'hasMember'\", \"structural.hasMemberOrders.member\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (nco *NamespaceCreateOptions) Validate(ctx context.Context) error {\n\treturn dfutil.ValidateK8sResourceName(\"namespace name\", nco.namespaceName)\n}", "func validateController(ctx context.Context, c clientset.Interface, containerImage string, replicas int, containername string, testname string, validator validatorFn, ns string) {\n\tcontainerImage = trimDockerRegistry(containerImage)\n\tgetPodsTemplate := \"--template={{range.items}}{{.metadata.name}} {{end}}\"\n\n\tgetContainerStateTemplate := fmt.Sprintf(`--template={{if (exists . \"status\" \"containerStatuses\")}}{{range .status.containerStatuses}}{{if (and (eq .name \"%s\") (exists . \"state\" \"running\"))}}true{{end}}{{end}}{{end}}`, containername)\n\n\tgetImageTemplate := fmt.Sprintf(`--template={{if (exists . \"spec\" \"containers\")}}{{range .spec.containers}}{{if eq .name \"%s\"}}{{.image}}{{end}}{{end}}{{end}}`, containername)\n\n\tginkgo.By(fmt.Sprintf(\"waiting for all containers in %s pods to come up.\", testname)) //testname should be selector\nwaitLoop:\n\tfor start := time.Now(); time.Since(start) < framework.PodStartTimeout && ctx.Err() == nil; time.Sleep(5 * time.Second) {\n\t\tgetPodsOutput := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"pods\", \"-o\", \"template\", getPodsTemplate, \"-l\", testname)\n\t\tpods := strings.Fields(getPodsOutput)\n\t\tif numPods := len(pods); numPods != replicas {\n\t\t\tginkgo.By(fmt.Sprintf(\"Replicas for %s: expected=%d actual=%d\", testname, replicas, numPods))\n\t\t\tcontinue\n\t\t}\n\t\tvar runningPods []string\n\t\tfor _, podID := range pods {\n\t\t\trunning := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"pods\", podID, \"-o\", \"template\", getContainerStateTemplate)\n\t\t\tif running != \"true\" {\n\t\t\t\tframework.Logf(\"%s is created but not running\", podID)\n\t\t\t\tcontinue waitLoop\n\t\t\t}\n\n\t\t\tcurrentImage := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"pods\", podID, \"-o\", \"template\", getImageTemplate)\n\t\t\tcurrentImage = trimDockerRegistry(currentImage)\n\t\t\tif currentImage != containerImage {\n\t\t\t\tframework.Logf(\"%s is created but running wrong image; expected: %s, actual: %s\", podID, containerImage, currentImage)\n\t\t\t\tcontinue waitLoop\n\t\t\t}\n\n\t\t\t// Call the generic validator function here.\n\t\t\t// This might validate for example, that (1) getting a url works and (2) url is serving correct content.\n\t\t\tif err := validator(ctx, c, podID); err != nil {\n\t\t\t\tframework.Logf(\"%s is running right image but validator function failed: %v\", podID, err)\n\t\t\t\tcontinue waitLoop\n\t\t\t}\n\n\t\t\tframework.Logf(\"%s is verified up and running\", podID)\n\t\t\trunningPods = append(runningPods, podID)\n\t\t}\n\t\t// If we reach here, then all our checks passed.\n\t\tif len(runningPods) == replicas {\n\t\t\treturn\n\t\t}\n\t}\n\t// Reaching here means that one of more checks failed multiple times. Assuming its not a race condition, something is broken.\n\tframework.Failf(\"Timed out after %v seconds waiting for %s pods to reach valid state\", framework.PodStartTimeout.Seconds(), testname)\n}", "func (t *OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *ServiceCreateOptions) Validate() (err error) {\n\t// if we are in interactive mode, all values are already valid\n\tif o.interactive {\n\t\treturn nil\n\t}\n\n\t// we want to find an Operator only if something's passed to the crd flag on CLI\n\tif experimental.IsExperimentalModeEnabled() {\n\t\t// if the user wants to create service from a file, we check for\n\t\t// existence of file and validate if the requested operator and CR\n\t\t// exist on the cluster\n\t\tif o.fromFile != \"\" {\n\t\t\tif _, err := os.Stat(o.fromFile); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"unable to find specified file\")\n\t\t\t}\n\n\t\t\t// Parse the file to find Operator and CR info\n\t\t\tfileContents, err := ioutil.ReadFile(o.fromFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// var jsonCR map[string]interface{}\n\t\t\terr = yaml.Unmarshal(fileContents, &o.CustomResourceDefinition)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Check if the operator and the CR exist on cluster\n\t\t\to.CustomResource = o.CustomResourceDefinition[\"kind\"].(string)\n\t\t\tcsvs, err := o.KClient.GetClusterServiceVersionList()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcsv, err := doesCRExist(o.CustomResource, csvs)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Could not find specified service/custom resource: %s\\nPlease check the \\\"kind\\\" field in the yaml (it's case-sensitive)\", o.CustomResource)\n\t\t\t}\n\n\t\t\t// all is well, let's populate the fields required for creating operator backed service\n\t\t\to.group, o.version = groupVersionALMExample(o.CustomResourceDefinition)\n\t\t\to.resource = resourceFromCSV(csv, o.CustomResource)\n\t\t\to.ServiceName, err = serviceNameFromCRD(o.CustomResourceDefinition, o.ServiceName)\n\t\t\treturn err\n\t\t}\n\t\tif o.CustomResource != \"\" {\n\t\t\t// make sure that CSV of the specified ServiceType exists\n\t\t\tcsv, err := o.KClient.GetClusterServiceVersion(o.ServiceType)\n\t\t\tif err != nil {\n\t\t\t\t// error only occurs when OperatorHub is not installed.\n\t\t\t\t// k8s does't have it installed by default but OCP does\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tvar almExamples []map[string]interface{}\n\t\t\tval, ok := csv.Annotations[\"alm-examples\"]\n\t\t\tif ok {\n\t\t\t\terr = json.Unmarshal([]byte(val), &almExamples)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"unable to unmarshal alm-examples\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// There's no alm examples in the CSV's definition\n\t\t\t\treturn fmt.Errorf(\"Could not find alm-examples in operator's definition.\\nPlease provide a file containing yaml specification to start the %s service from %s operator\", o.CustomResource, o.ServiceName)\n\t\t\t}\n\n\t\t\talmExample, err := getAlmExample(almExamples, o.CustomResource, o.ServiceType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\to.CustomResourceDefinition = almExample\n\t\t\to.group, o.version = groupVersionALMExample(almExample)\n\t\t\to.resource = resourceFromCSV(csv, o.CustomResource)\n\t\t\to.ServiceName, err = serviceNameFromCRD(o.CustomResourceDefinition, o.ServiceName)\n\t\t\treturn err\n\t\t} else {\n\t\t\t// prevent user from executing `odo service create <operator-name>`\n\t\t\t// because the correct way is to execute `odo service\n\t\t\t// <operator-name> --crd <crd-name>`\n\t\t\tcsvs, err := o.KClient.GetClusterServiceVersionList()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfor _, csv := range csvs.Items {\n\t\t\t\tif csv.Name == o.ServiceType {\n\t\t\t\t\t// this is satisfied if user has specified operator but not\n\t\t\t\t\t// a CRD name\n\t\t\t\t\treturn errors.New(\"Please specify service name along with the operator name\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// make sure the service type exists\n\tclassPtr, err := o.Client.GetClusterServiceClass(o.ServiceType)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to create service because Service Catalog is not enabled in your cluster\")\n\t}\n\tif classPtr == nil {\n\t\treturn fmt.Errorf(\"service %v doesn't exist\\nRun 'odo catalog list services' to see a list of supported services.\\n\", o.ServiceType)\n\t}\n\n\t// check plan\n\tplans, err := o.Client.GetMatchingPlans(*classPtr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(o.Plan) == 0 {\n\t\t// when the plan has not been supplied, if there is only one available plan, we select it\n\t\tif len(plans) == 1 {\n\t\t\tfor k := range plans {\n\t\t\t\to.Plan = k\n\t\t\t}\n\t\t\tklog.V(4).Infof(\"Plan %s was automatically selected since it's the only one available for service %s\", o.Plan, o.ServiceType)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"no plan was supplied for service %v.\\nPlease select one of: %v\\n\", o.ServiceType, strings.Join(ui.GetServicePlanNames(plans), \",\"))\n\t\t}\n\t} else {\n\t\t// when the plan has been supplied, we need to make sure it exists\n\t\tif _, ok := plans[o.Plan]; !ok {\n\t\t\treturn fmt.Errorf(\"plan %s is invalid for service %v.\\nPlease select one of: %v\\n\", o.Plan, o.ServiceType, strings.Join(ui.GetServicePlanNames(plans), \",\"))\n\t\t}\n\t}\n\t//validate service name\n\treturn o.validateServiceName(o.ServiceName)\n}", "func (t *OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors_Selector_State) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Selectors_Selector_State\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *Reconciler) validateNSTemplateTier(tierName string) error {\n\tif tierName == \"\" {\n\t\treturn fmt.Errorf(\"tierName cannot be blank\")\n\t}\n\t// check if requested tier exists\n\ttier := &toolchainv1alpha1.NSTemplateTier{}\n\tif err := r.Client.Get(context.TODO(), types.NamespacedName{\n\t\tNamespace: r.Namespace,\n\t\tName: tierName,\n\t}, tier); err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn err\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\treturn errs.Wrap(err, \"unable to get the current NSTemplateTier\")\n\t}\n\treturn nil\n}", "func ValidateNodeSelectorRequirement(rq core.NodeSelectorRequirement, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tswitch rq.Operator {\n\tcase core.NodeSelectorOpIn, core.NodeSelectorOpNotIn:\n\t\tif len(rq.Values) == 0 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"values\"), \"must be specified when `operator` is 'In' or 'NotIn'\"))\n\t\t}\n\tcase core.NodeSelectorOpExists, core.NodeSelectorOpDoesNotExist:\n\t\tif len(rq.Values) > 0 {\n\t\t\tallErrs = append(allErrs, field.Forbidden(fldPath.Child(\"values\"), \"may not be specified when `operator` is 'Exists' or 'DoesNotExist'\"))\n\t\t}\n\n\tcase core.NodeSelectorOpGt, core.NodeSelectorOpLt:\n\t\tif len(rq.Values) != 1 {\n\t\t\tallErrs = append(allErrs, field.Required(fldPath.Child(\"values\"), \"must be specified single value when `operator` is 'Lt' or 'Gt'\"))\n\t\t}\n\tdefault:\n\t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"operator\"), rq.Operator, \"not a valid selector operator\"))\n\t}\n\n\tallErrs = append(allErrs, unversionedvalidation.ValidateLabelName(rq.Key, fldPath.Child(\"key\"))...)\n\n\treturn allErrs\n}", "func (sel *CFNSelector) Resources(msg, finalMsg, help, body string) ([]template.CFNResource, error) {\n\ttpl := struct {\n\t\tResources map[string]struct {\n\t\t\tType string `yaml:\"Type\"`\n\t\t} `yaml:\"Resources\"`\n\t}{}\n\tif err := yaml.Unmarshal([]byte(body), &tpl); err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshal CloudFormation template: %v\", err)\n\t}\n\n\t// Prompt for a selection.\n\tvar options []prompt.Option\n\tfor name, resource := range tpl.Resources {\n\t\tif resource.Type == \"AWS::Lambda::Function\" || strings.HasPrefix(resource.Type, \"Custom::\") {\n\t\t\tcontinue\n\t\t}\n\t\toptions = append(options, prompt.Option{\n\t\t\tValue: name,\n\t\t\tHint: resource.Type,\n\t\t})\n\t}\n\tsort.Slice(options, func(i, j int) bool { // Sort options by resource type, if they're the same resource type then sort by logicalID.\n\t\tif options[i].Hint == options[j].Hint {\n\t\t\treturn options[i].Value < options[j].Value\n\t\t}\n\t\treturn options[i].Hint < options[j].Hint\n\t})\n\tlogicalIDs, err := sel.prompt.MultiSelectOptions(msg, help, options, prompt.WithFinalMessage(finalMsg))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"select CloudFormation resources: %v\", err)\n\t}\n\n\t// Transform to template.CFNResource\n\tout := make([]template.CFNResource, len(logicalIDs))\n\tfor i, logicalID := range logicalIDs {\n\t\tout[i] = template.CFNResource{\n\t\t\tType: template.CFNType(tpl.Resources[logicalID].Type),\n\t\t\tLogicalID: logicalID,\n\t\t}\n\t}\n\treturn out, nil\n}", "func (s *OpenconfigOfficeAp_System_Logging_Console_Selectors_Selector_Config) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Logging_Console_Selectors_Selector_Config\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ResourceOwnerOf(obj runtime.Object) Func {\n\treturn func(ownerObj runtime.Object) bool {\n\t\treturn metav1.IsControlledBy(obj.(metav1.Object), ownerObj.(metav1.Object))\n\t}\n}", "func (s *Synk) Init() error {\n\tvTrue := true\n\tcrd := &apiextensions.CustomResourceDefinition{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"apiextensions.k8s.io/v1\",\n\t\t\tKind: \"CustomResourceDefinition\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"resourcesets.apps.cloudrobotics.com\",\n\t\t},\n\t\tSpec: apiextensions.CustomResourceDefinitionSpec{\n\t\t\tGroup: \"apps.cloudrobotics.com\",\n\t\t\tNames: apiextensions.CustomResourceDefinitionNames{\n\t\t\t\tKind: \"ResourceSet\",\n\t\t\t\tPlural: \"resourcesets\",\n\t\t\t\tSingular: \"resourceset\",\n\t\t\t},\n\t\t\tScope: apiextensions.ClusterScoped,\n\t\t\tVersions: []apiextensions.CustomResourceDefinitionVersion{{\n\t\t\t\tName: \"v1alpha1\",\n\t\t\t\tServed: true,\n\t\t\t\tStorage: true,\n\t\t\t\t// TODO(ensonic): replace with the actual schema\n\t\t\t\tSchema: &apiextensions.CustomResourceValidation{\n\t\t\t\t\tOpenAPIV3Schema: &apiextensions.JSONSchemaProps{\n\t\t\t\t\t\tType: \"object\",\n\t\t\t\t\t\tProperties: map[string]apiextensions.JSONSchemaProps{\n\t\t\t\t\t\t\t\"spec\": {\n\t\t\t\t\t\t\t\tType: \"object\",\n\t\t\t\t\t\t\t\tXPreserveUnknownFields: &vTrue,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\"status\": {\n\t\t\t\t\t\t\t\tType: \"object\",\n\t\t\t\t\t\t\t\tXPreserveUnknownFields: &vTrue,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}},\n\t\t},\n\t}\n\tvar u unstructured.Unstructured\n\tif err := convert(crd, &u); err != nil {\n\t\treturn err\n\t}\n\tif _, err := s.applyOne(context.Background(), &u, nil); err != nil {\n\t\treturn errors.Wrap(err, \"create ResourceSet CRD\")\n\t}\n\n\terr := backoff.Retry(\n\t\tfunc() error {\n\t\t\ts.discovery.Invalidate()\n\t\t\tok, err := s.crdAvailable(&u)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\treturn errors.New(\"crd not available\")\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tbackoff.WithMaxRetries(backoff.NewConstantBackOff(2*time.Second), 60),\n\t)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"wait for ResourceSet CRD\")\n\t}\n\n\treturn nil\n}", "func ValidateResource(r RextResourceDef) (hasError bool) {\n\tif len(r.GetType()) == 0 {\n\t\thasError = true\n\t\tlog.Errorln(\"type is required in metric config\")\n\t}\n\tif len(r.GetResourcePATH(\"\")) == 0 {\n\t\thasError = true\n\t\tlog.Errorln(\"resource path is required in metric config\")\n\t}\n\tif r.GetDecoder() == nil {\n\t\thasError = true\n\t\tlog.Errorln(\"decoder is required in metric config\")\n\t} else if r.GetDecoder().Validate() {\n\t\thasError = true\n\t}\n\tif r.GetAuth(nil) != nil {\n\t\tif r.GetAuth(nil).Validate() {\n\t\t\thasError = true\n\t\t}\n\t}\n\tfor _, mtrDef := range r.GetMetricDefs() {\n\t\tif mtrDef.Validate() {\n\t\t\thasError = true\n\t\t}\n\t}\n\treturn hasError\n}", "func (e EndpointResource) Validate() error {\n\treturn validator.New().Struct(e)\n}", "func IsResourceQuotaScopeValidForResource(scope corev1.ResourceQuotaScope, resource string) bool {\n\tswitch scope {\n\tcase corev1.ResourceQuotaScopeTerminating, corev1.ResourceQuotaScopeNotTerminating, corev1.ResourceQuotaScopeNotBestEffort, corev1.ResourceQuotaScopePriorityClass:\n\t\treturn podObjectCountQuotaResources.Has(resource) || podComputeQuotaResources.Has(resource)\n\tcase corev1.ResourceQuotaScopeBestEffort:\n\t\treturn podObjectCountQuotaResources.Has(resource)\n\tdefault:\n\t\treturn true\n\t}\n}", "func isResourceReady(dynamicClient dynamic.Interface, obj *MetaResource) (bool, error) {\n\t// get the resource's name, namespace and gvr\n\tname := obj.Name\n\tnamespace := obj.Namespace\n\tgvk := obj.GroupVersionKind()\n\tgvr, _ := meta.UnsafeGuessKindToResource(gvk)\n\t// use the helper functions to convert the resource to a KResource duck\n\ttif := &duck.TypedInformerFactory{Client: dynamicClient, Type: &duckv1alpha1.KResource{}}\n\t_, lister, err := tif.Get(gvr)\n\tif err != nil {\n\t\t// Return error to stop the polling.\n\t\treturn false, err\n\t}\n\tuntyped, err := lister.ByNamespace(namespace).Get(name)\n\tif k8serrors.IsNotFound(err) {\n\t\t// Return false as we are not done yet.\n\t\t// We swallow the error to keep on polling.\n\t\t// It should only happen if we wait for the auto-created resources, like default Broker.\n\t\treturn false, nil\n\t} else if err != nil {\n\t\t// Return error to stop the polling.\n\t\treturn false, err\n\t}\n\tkr := untyped.(*duckv1alpha1.KResource)\n\treturn kr.Status.GetCondition(duckv1alpha1.ConditionReady).IsTrue(), nil\n}", "func validateResourceList(resourceList core.ResourceList, upperBound core.ResourceList, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor resourceName, quantity := range resourceList {\n\t\tresPath := fldPath.Key(string(resourceName))\n\t\t// Validate resource name.\n\t\tallErrs = append(allErrs, validateResourceName(&resourceName, resPath)...)\n\t\t// Validate resource quantity.\n\t\tallErrs = append(allErrs, corevalidation.ValidateResourceQuantityValue(string(resourceName), quantity, resPath)...)\n\t\tif upperBound != nil {\n\t\t\t// Check that request <= limit.\n\t\t\tupperBoundQuantity, exists := upperBound[resourceName]\n\t\t\tif exists && quantity.Cmp(upperBoundQuantity) > 0 {\n\t\t\t\tallErrs = append(allErrs, field.Invalid(fldPath, quantity.String(),\n\t\t\t\t\t\"must be less than or equal to the upper bound\"))\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}", "func CheckResource(nsId string, resourceType string, resourceId string) (bool, error) {\n\n\t// Check parameters' emptiness\n\tif nsId == \"\" {\n\t\terr := fmt.Errorf(\"CheckResource failed; nsId given is null.\")\n\t\treturn false, err\n\t} else if resourceType == \"\" {\n\t\terr := fmt.Errorf(\"CheckResource failed; resourceType given is null.\")\n\t\treturn false, err\n\t} else if resourceId == \"\" {\n\t\terr := fmt.Errorf(\"CheckResource failed; resourceId given is null.\")\n\t\treturn false, err\n\t}\n\n\t// Check resourceType's validity\n\tif resourceType == common.StrImage ||\n\t\tresourceType == common.StrSSHKey ||\n\t\tresourceType == common.StrSpec ||\n\t\tresourceType == common.StrVNet ||\n\t\tresourceType == common.StrSecurityGroup {\n\t\t//resourceType == \"subnet\" ||\n\t\t//resourceType == \"publicIp\" ||\n\t\t//resourceType == \"vNic\" {\n\t\t// continue\n\t} else {\n\t\terr := fmt.Errorf(\"invalid resource type\")\n\t\treturn false, err\n\t}\n\n\terr := common.CheckString(nsId)\n\tif err != nil {\n\t\tcommon.CBLog.Error(err)\n\t\treturn false, err\n\t}\n\n\terr = common.CheckString(resourceId)\n\tif err != nil {\n\t\tcommon.CBLog.Error(err)\n\t\treturn false, err\n\t}\n\n\tfmt.Println(\"[Check resource] \" + resourceType + \", \" + resourceId)\n\n\tkey := common.GenResourceKey(nsId, resourceType, resourceId)\n\t//fmt.Println(key)\n\n\tkeyValue, err := common.CBStore.Get(key)\n\tif err != nil {\n\t\tcommon.CBLog.Error(err)\n\t\treturn false, err\n\t}\n\tif keyValue != nil {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n\n}", "func matchesSelector(req *runtimehooksv1.GeneratePatchesRequestItem, templateVariables map[string]apiextensionsv1.JSON, selector clusterv1.PatchSelector) bool {\n\tgvk := req.Object.Object.GetObjectKind().GroupVersionKind()\n\n\t// Check if the apiVersion and kind are matching.\n\tif gvk.GroupVersion().String() != selector.APIVersion {\n\t\treturn false\n\t}\n\tif gvk.Kind != selector.Kind {\n\t\treturn false\n\t}\n\n\t// Check if the request is for an InfrastructureCluster.\n\tif selector.MatchResources.InfrastructureCluster {\n\t\t// Cluster.spec.infrastructureRef holds the InfrastructureCluster.\n\t\tif req.HolderReference.Kind == \"Cluster\" && req.HolderReference.FieldPath == \"spec.infrastructureRef\" {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// Check if the request is for a ControlPlane or the InfrastructureMachineTemplate of a ControlPlane.\n\tif selector.MatchResources.ControlPlane {\n\t\t// Cluster.spec.controlPlaneRef holds the ControlPlane.\n\t\tif req.HolderReference.Kind == \"Cluster\" && req.HolderReference.FieldPath == \"spec.controlPlaneRef\" {\n\t\t\treturn true\n\t\t}\n\t\t// *.spec.machineTemplate.infrastructureRef holds the InfrastructureMachineTemplate of a ControlPlane.\n\t\t// Note: this field path is only used in this context.\n\t\tif req.HolderReference.FieldPath == strings.Join(contract.ControlPlane().MachineTemplate().InfrastructureRef().Path(), \".\") {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// Check if the request is for a BootstrapConfigTemplate or an InfrastructureMachineTemplate\n\t// of one of the configured MachineDeploymentClasses.\n\tif selector.MatchResources.MachineDeploymentClass != nil {\n\t\t// MachineDeployment.spec.template.spec.bootstrap.configRef or\n\t\t// MachineDeployment.spec.template.spec.infrastructureRef holds the BootstrapConfigTemplate or\n\t\t// InfrastructureMachineTemplate.\n\t\tif req.HolderReference.Kind == \"MachineDeployment\" &&\n\t\t\t(req.HolderReference.FieldPath == \"spec.template.spec.bootstrap.configRef\" ||\n\t\t\t\treq.HolderReference.FieldPath == \"spec.template.spec.infrastructureRef\") {\n\t\t\t// Read the builtin.machineDeployment.class variable.\n\t\t\ttemplateMDClassJSON, err := patchvariables.GetVariableValue(templateVariables, \"builtin.machineDeployment.class\")\n\n\t\t\t// If the builtin variable could be read.\n\t\t\tif err == nil {\n\t\t\t\t// If templateMDClass matches one of the configured MachineDeploymentClasses.\n\t\t\t\tfor _, mdClass := range selector.MatchResources.MachineDeploymentClass.Names {\n\t\t\t\t\t// We have to quote mdClass as templateMDClassJSON is a JSON string (e.g. \"default-worker\").\n\t\t\t\t\tif mdClass == \"*\" || string(templateMDClassJSON.Raw) == strconv.Quote(mdClass) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t\tunquoted, _ := strconv.Unquote(string(templateMDClassJSON.Raw))\n\t\t\t\t\tif strings.HasPrefix(mdClass, \"*\") && strings.HasSuffix(unquoted, strings.TrimPrefix(mdClass, \"*\")) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t\tif strings.HasSuffix(mdClass, \"*\") && strings.HasPrefix(unquoted, strings.TrimSuffix(mdClass, \"*\")) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check if the request is for a BootstrapConfigTemplate or an InfrastructureMachinePoolTemplate\n\t// of one of the configured MachinePoolClasses.\n\tif selector.MatchResources.MachinePoolClass != nil {\n\t\tif req.HolderReference.Kind == \"MachinePool\" &&\n\t\t\t(req.HolderReference.FieldPath == \"spec.template.spec.bootstrap.configRef\" ||\n\t\t\t\treq.HolderReference.FieldPath == \"spec.template.spec.infrastructureRef\") {\n\t\t\t// Read the builtin.machinePool.class variable.\n\t\t\ttemplateMPClassJSON, err := patchvariables.GetVariableValue(templateVariables, \"builtin.machinePool.class\")\n\n\t\t\t// If the builtin variable could be read.\n\t\t\tif err == nil {\n\t\t\t\t// If templateMPClass matches one of the configured MachinePoolClasses.\n\t\t\t\tfor _, mpClass := range selector.MatchResources.MachinePoolClass.Names {\n\t\t\t\t\t// We have to quote mpClass as templateMPClassJSON is a JSON string (e.g. \"default-worker\").\n\t\t\t\t\tif mpClass == \"*\" || string(templateMPClassJSON.Raw) == strconv.Quote(mpClass) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t\tunquoted, _ := strconv.Unquote(string(templateMPClassJSON.Raw))\n\t\t\t\t\tif strings.HasPrefix(mpClass, \"*\") && strings.HasSuffix(unquoted, strings.TrimPrefix(mpClass, \"*\")) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t\tif strings.HasSuffix(mpClass, \"*\") && strings.HasPrefix(unquoted, strings.TrimSuffix(mpClass, \"*\")) {\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}", "func (s *RedisSpec) ObserveSelectors(rsrc interface{}) []ResourceSelector {\n\tr := rsrc.(*AirflowCluster)\n\tselector := selectorLabels(r, ValueAirflowComponentRedis)\n\trsrcSelectos := []ResourceSelector{\n\t\t{&resources.StatefulSet{}, selector},\n\t\t{&resources.Service{}, selector},\n\t\t{&resources.Secret{}, selector},\n\t\t{&resources.PodDisruptionBudget{}, selector},\n\t}\n\t//if s.VolumeClaimTemplate != nil {\n\t//\trsrcSelectos = append(rsrcSelectos, ResourceSelector{s.VolumeClaimTemplate, nil})\n\t//}\n\treturn rsrcSelectos\n}", "func validateFromResourceType(resourceType string) (string, error) {\n\tname, err := k8s.CanonicalResourceNameFromFriendlyName(resourceType)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif name == k8s.Authority {\n\t\treturn \"\", errors.New(\"cannot query traffic --from an authority\")\n\t}\n\treturn name, nil\n}", "func ResourceOwnedBy(owner runtime.Object) Func {\n\treturn func(obj runtime.Object) bool {\n\t\treturn metav1.IsControlledBy(obj.(metav1.Object), owner.(metav1.Object))\n\t}\n}", "func TestValidateResource(t *testing.T) {\n\trunPolicyPackIntegrationTest(t, \"validate_resource\", NodeJS, nil, []policyTestScenario{\n\t\t// Test scenario 1: no resources.\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 2: no violations.\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 3: violates the first policy.\n\t\t{\n\t\t\tWantErrors: []string{\n\t\t\t\t\"[mandatory] validate-resource-test-policy v0.0.1 dynamic-no-state-with-value-1 (pulumi-nodejs:dynamic:Resource: a)\",\n\t\t\t\t\"Prohibits setting state to 1 on dynamic resources.\",\n\t\t\t\t\"'state' must not have the value 1.\",\n\t\t\t},\n\t\t},\n\t\t// Test scenario 4: violates the second policy.\n\t\t{\n\t\t\tWantErrors: []string{\n\t\t\t\t\"[mandatory] validate-resource-test-policy v0.0.1 dynamic-no-state-with-value-2 (pulumi-nodejs:dynamic:Resource: b)\",\n\t\t\t\t\"Prohibits setting state to 2 on dynamic resources.\",\n\t\t\t\t\"'state' must not have the value 2.\",\n\t\t\t},\n\t\t},\n\t\t// Test scenario 5: violates the first validation function of the third policy.\n\t\t{\n\t\t\tWantErrors: []string{\n\t\t\t\t\"[mandatory] validate-resource-test-policy v0.0.1 dynamic-no-state-with-value-3-or-4 (pulumi-nodejs:dynamic:Resource: c)\",\n\t\t\t\t\"Prohibits setting state to 3 or 4 on dynamic resources.\",\n\t\t\t\t\"'state' must not have the value 3.\",\n\t\t\t},\n\t\t},\n\t\t// Test scenario 6: violates the second validation function of the third policy.\n\t\t{\n\t\t\tWantErrors: []string{\n\t\t\t\t\"[mandatory] validate-resource-test-policy v0.0.1 dynamic-no-state-with-value-3-or-4 (pulumi-nodejs:dynamic:Resource: d)\",\n\t\t\t\t\"Prohibits setting state to 3 or 4 on dynamic resources.\",\n\t\t\t\t\"'state' must not have the value 4.\",\n\t\t\t},\n\t\t},\n\t\t// Test scenario 7: violates the fourth policy.\n\t\t{\n\t\t\tWantErrors: []string{\n\t\t\t\t\"[mandatory] validate-resource-test-policy v0.0.1 randomuuid-no-keepers (random:index/randomUuid:RandomUuid: r1)\",\n\t\t\t\t\"Prohibits creating a RandomUuid without any 'keepers'.\",\n\t\t\t\t\"RandomUuid must not have an empty 'keepers'.\",\n\t\t\t},\n\t\t},\n\t\t// Test scenario 8: no violations.\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 9: violates the fifth policy.\n\t\t{\n\t\t\tWantErrors: []string{\n\t\t\t\t\"[mandatory] validate-resource-test-policy v0.0.1 dynamic-no-state-with-value-5 (pulumi-nodejs:dynamic:Resource: e)\",\n\t\t\t\t\"Prohibits setting state to 5 on dynamic resources.\",\n\t\t\t\t\"'state' must not have the value 5.\",\n\t\t\t},\n\t\t},\n\t\t// Test scenario 10: no violations.\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t\t// Test scenario 11: no violations.\n\t\t// Test the ability to send large gRPC messages (>4mb).\n\t\t// Issue: https://github.com/pulumi/pulumi/issues/4155\n\t\t{\n\t\t\tWantErrors: nil,\n\t\t},\n\t})\n}", "func (s *selection) validate() error {\n\tif s.hasAntiAffinityLabel() && s.hasPreferAntiAffinityLabel() {\n\t\treturn errors.New(\"invalid selection: both antiAffinityLabel and preferAntiAffinityLabel policies can not be together\")\n\t}\n\treturn nil\n}", "func checkResource(config interface{}, resource *unstructured.Unstructured) (bool, error) {\n\n\t// we are checking if config is a subset of resource with default pattern\n\tpath, err := validateResourceWithPattern(resource.Object, config)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"config not a subset of resource. failed at path %s: %v\", path, err)\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func (o *KubeOptions) Validate() error {\n\n\treturn nil\n}", "func (o *KubeOptions) Validate() error {\n\n\treturn nil\n}", "func (sel *AccessSelector) Validate() error {\n\tif err := validation.Validate(&sel.ViewSelector); err != nil {\n\t\treturn errors.Wrap(err, \"validate ViewSelector\")\n\t}\n\t{\n\t\tfields := &sel.FieldSelector\n\t\tif err := validation.ValidateStruct(\n\t\t\tfields,\n\t\t\tvalidation.Field(&fields.Time, validation.Required),\n\t\t\tvalidation.Field(&fields.CodeRecordID, validation.Required),\n\t\t); err != nil {\n\t\t\treturn errors.Wrap(err, \"validate FieldSelector\")\n\t\t}\n\t}\n\treturn nil\n}", "func (t BatchJobReplicateResourceType) Validate() error {\n\tswitch t {\n\tcase BatchJobReplicateResourceMinIO:\n\tdefault:\n\t\treturn errInvalidArgument\n\t}\n\treturn nil\n}", "func (m LabelSelectorOperator) ContextValidate(ctx context.Context, formats strfmt.Registry) error {\n\treturn nil\n}", "func (s *OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func CheckRequest(quotas []corev1.ResourceQuota, a admission.Attributes, evaluator quota.Evaluator,\n\tlimited []resourcequotaapi.LimitedResource) ([]corev1.ResourceQuota, error) {\n\tif !evaluator.Handles(a) {\n\t\treturn quotas, nil\n\t}\n\n\t// if we have limited resources enabled for this resource, always calculate usage\n\tinputObject := a.GetObject()\n\n\t// Check if object matches AdmissionConfiguration matchScopes\n\tlimitedScopes, err := getMatchedLimitedScopes(evaluator, inputObject, limited)\n\tif err != nil {\n\t\treturn quotas, nil\n\t}\n\n\t// determine the set of resource names that must exist in a covering quota\n\tlimitedResourceNames := []corev1.ResourceName{}\n\tlimitedResources := filterLimitedResourcesByGroupResource(limited, a.GetResource().GroupResource())\n\tif len(limitedResources) > 0 {\n\t\tdeltaUsage, err := evaluator.Usage(inputObject)\n\t\tif err != nil {\n\t\t\treturn quotas, err\n\t\t}\n\t\tlimitedResourceNames = limitedByDefault(deltaUsage, limitedResources)\n\t}\n\tlimitedResourceNamesSet := quota.ToSet(limitedResourceNames)\n\n\t// find the set of quotas that are pertinent to this request\n\t// reject if we match the quota, but usage is not calculated yet\n\t// reject if the input object does not satisfy quota constraints\n\t// if there are no pertinent quotas, we can just return\n\tinterestingQuotaIndexes := []int{}\n\t// track the cumulative set of resources that were required across all quotas\n\t// this is needed to know if we have satisfied any constraints where consumption\n\t// was limited by default.\n\trestrictedResourcesSet := sets.String{}\n\trestrictedScopes := []corev1.ScopedResourceSelectorRequirement{}\n\tfor i := range quotas {\n\t\tresourceQuota := quotas[i]\n\t\tscopeSelectors := getScopeSelectorsFromQuota(resourceQuota)\n\t\tlocalRestrictedScopes, err := evaluator.MatchingScopes(inputObject, scopeSelectors)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error matching scopes of quota %s, err: %v\", resourceQuota.Name, err)\n\t\t}\n\t\trestrictedScopes = append(restrictedScopes, localRestrictedScopes...)\n\n\t\tmatch, err := evaluator.Matches(&resourceQuota, inputObject)\n\t\tif err != nil {\n\t\t\tklog.ErrorS(err, \"Error occurred while matching resource quota against input object\",\n\t\t\t\t\"resourceQuota\", resourceQuota)\n\t\t\treturn quotas, err\n\t\t}\n\t\tif !match {\n\t\t\tcontinue\n\t\t}\n\n\t\thardResources := quota.ResourceNames(resourceQuota.Status.Hard)\n\t\trestrictedResources := evaluator.MatchingResources(hardResources)\n\t\tif err := evaluator.Constraints(restrictedResources, inputObject); err != nil {\n\t\t\treturn nil, admission.NewForbidden(a, fmt.Errorf(\"failed quota: %s: %v\", resourceQuota.Name, err))\n\t\t}\n\t\tif !hasUsageStats(&resourceQuota, restrictedResources) {\n\t\t\treturn nil, admission.NewForbidden(a, fmt.Errorf(\"status unknown for quota: %s, resources: %s\", resourceQuota.Name, prettyPrintResourceNames(restrictedResources)))\n\t\t}\n\t\tinterestingQuotaIndexes = append(interestingQuotaIndexes, i)\n\t\tlocalRestrictedResourcesSet := quota.ToSet(restrictedResources)\n\t\trestrictedResourcesSet.Insert(localRestrictedResourcesSet.List()...)\n\t}\n\n\t// Usage of some resources cannot be counted in isolation. For example, when\n\t// the resource represents a number of unique references to external\n\t// resource. In such a case an evaluator needs to process other objects in\n\t// the same namespace which needs to be known.\n\tnamespace := a.GetNamespace()\n\tif accessor, err := meta.Accessor(inputObject); namespace != \"\" && err == nil {\n\t\tif accessor.GetNamespace() == \"\" {\n\t\t\taccessor.SetNamespace(namespace)\n\t\t}\n\t}\n\t// there is at least one quota that definitely matches our object\n\t// as a result, we need to measure the usage of this object for quota\n\t// on updates, we need to subtract the previous measured usage\n\t// if usage shows no change, just return since it has no impact on quota\n\tdeltaUsage, err := evaluator.Usage(inputObject)\n\tif err != nil {\n\t\treturn quotas, err\n\t}\n\n\t// ensure that usage for input object is never negative (this would mean a resource made a negative resource requirement)\n\tif negativeUsage := quota.IsNegative(deltaUsage); len(negativeUsage) > 0 {\n\t\treturn nil, admission.NewForbidden(a, fmt.Errorf(\"quota usage is negative for resource(s): %s\", prettyPrintResourceNames(negativeUsage)))\n\t}\n\n\tif admission.Update == a.GetOperation() {\n\t\tprevItem := a.GetOldObject()\n\t\tif prevItem == nil {\n\t\t\treturn nil, admission.NewForbidden(a, fmt.Errorf(\"unable to get previous usage since prior version of object was not found\"))\n\t\t}\n\n\t\t// if we can definitively determine that this is not a case of \"create on update\",\n\t\t// then charge based on the delta. Otherwise, bill the maximum\n\t\tmetadata, err := meta.Accessor(prevItem)\n\t\tif err == nil && len(metadata.GetResourceVersion()) > 0 {\n\t\t\tprevUsage, innerErr := evaluator.Usage(prevItem)\n\t\t\tif innerErr != nil {\n\t\t\t\treturn quotas, innerErr\n\t\t\t}\n\t\t\tif feature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t\t\t// allow negative usage for pods as pod resources can increase or decrease\n\t\t\t\tif a.GetResource().GroupResource() == corev1.Resource(\"pods\") {\n\t\t\t\t\tdeltaUsage = quota.Subtract(deltaUsage, prevUsage)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdeltaUsage = quota.SubtractWithNonNegativeResult(deltaUsage, prevUsage)\n\t\t\t}\n\t\t}\n\t}\n\n\t// ignore items in deltaUsage with zero usage\n\tdeltaUsage = quota.RemoveZeros(deltaUsage)\n\t// if there is no remaining non-zero usage, short-circuit and return\n\tif len(deltaUsage) == 0 {\n\t\treturn quotas, nil\n\t}\n\n\t// verify that for every resource that had limited by default consumption\n\t// enabled that there was a corresponding quota that covered its use.\n\t// if not, we reject the request.\n\thasNoCoveringQuota := limitedResourceNamesSet.Difference(restrictedResourcesSet)\n\tif len(hasNoCoveringQuota) > 0 {\n\t\treturn quotas, admission.NewForbidden(a, fmt.Errorf(\"insufficient quota to consume: %v\", strings.Join(hasNoCoveringQuota.List(), \",\")))\n\t}\n\n\t// verify that for every scope that had limited access enabled\n\t// that there was a corresponding quota that covered it.\n\t// if not, we reject the request.\n\tscopesHasNoCoveringQuota, err := evaluator.UncoveredQuotaScopes(limitedScopes, restrictedScopes)\n\tif err != nil {\n\t\treturn quotas, err\n\t}\n\tif len(scopesHasNoCoveringQuota) > 0 {\n\t\treturn quotas, fmt.Errorf(\"insufficient quota to match these scopes: %v\", scopesHasNoCoveringQuota)\n\t}\n\n\tif len(interestingQuotaIndexes) == 0 {\n\t\treturn quotas, nil\n\t}\n\n\toutQuotas, err := copyQuotas(quotas)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, index := range interestingQuotaIndexes {\n\t\tresourceQuota := outQuotas[index]\n\n\t\thardResources := quota.ResourceNames(resourceQuota.Status.Hard)\n\t\trequestedUsage := quota.Mask(deltaUsage, hardResources)\n\t\tnewUsage := quota.Add(resourceQuota.Status.Used, requestedUsage)\n\t\tmaskedNewUsage := quota.Mask(newUsage, quota.ResourceNames(requestedUsage))\n\n\t\tif allowed, exceeded := quota.LessThanOrEqual(maskedNewUsage, resourceQuota.Status.Hard); !allowed {\n\t\t\tfailedRequestedUsage := quota.Mask(requestedUsage, exceeded)\n\t\t\tfailedUsed := quota.Mask(resourceQuota.Status.Used, exceeded)\n\t\t\tfailedHard := quota.Mask(resourceQuota.Status.Hard, exceeded)\n\t\t\treturn nil, admission.NewForbidden(a,\n\t\t\t\tfmt.Errorf(\"exceeded quota: %s, requested: %s, used: %s, limited: %s\",\n\t\t\t\t\tresourceQuota.Name,\n\t\t\t\t\tprettyPrint(failedRequestedUsage),\n\t\t\t\t\tprettyPrint(failedUsed),\n\t\t\t\t\tprettyPrint(failedHard)))\n\t\t}\n\n\t\t// update to the new usage number\n\t\toutQuotas[index].Status.Used = newUsage\n\t}\n\n\treturn outQuotas, nil\n}", "func (rs *PodAutoscalerSpec) Validate(ctx context.Context) *apis.FieldError {\n\tif equality.Semantic.DeepEqual(rs, &PodAutoscalerSpec{}) {\n\t\treturn apis.ErrMissingField(apis.CurrentField)\n\t}\n\terrs := serving.ValidateNamespacedObjectReference(&rs.ScaleTargetRef).ViaField(\"scaleTargetRef\")\n\terrs = errs.Also(rs.ContainerConcurrency.Validate(ctx).\n\t\tViaField(\"containerConcurrency\"))\n\treturn errs.Also(validateSKSFields(ctx, rs))\n}", "func ValidatePodSpecNodeSelector(nodeSelector map[string]string, fldPath *field.Path) field.ErrorList {\n\treturn unversionedvalidation.ValidateLabels(nodeSelector, fldPath)\n}", "func ValidateSplunkCustomResource(cr *v1alpha1.SplunkEnterprise) error {\n\t// cluster sanity checks\n\tif cr.Spec.Topology.SearchHeads > 0 && cr.Spec.Topology.Indexers <= 0 {\n\t\treturn errors.New(\"You must specify how many indexers the cluster should have\")\n\t}\n\tif cr.Spec.Topology.SearchHeads <= 0 && cr.Spec.Topology.Indexers > 0 {\n\t\treturn errors.New(\"You must specify how many search heads the cluster should have\")\n\t}\n\tif cr.Spec.Topology.Indexers > 0 && cr.Spec.Topology.SearchHeads > 0 && cr.Spec.LicenseURL == \"\" {\n\t\treturn errors.New(\"You must provide a license to create a cluster\")\n\t}\n\n\t// default to using a single standalone instance\n\tif cr.Spec.Topology.SearchHeads <= 0 && cr.Spec.Topology.Indexers <= 0 {\n\t\tif cr.Spec.Topology.Standalones <= 0 {\n\t\t\tcr.Spec.Topology.Standalones = 1\n\t\t}\n\t}\n\n\t// default to a single spark worker\n\tif cr.Spec.EnableDFS && cr.Spec.Topology.SparkWorkers <= 0 {\n\t\tcr.Spec.Topology.SparkWorkers = 1\n\t}\n\n\t// ImagePullPolicy\n\tif cr.Spec.ImagePullPolicy == \"\" {\n\t\tcr.Spec.ImagePullPolicy = os.Getenv(\"IMAGE_PULL_POLICY\")\n\t}\n\tswitch cr.Spec.ImagePullPolicy {\n\tcase \"\":\n\t\tcr.Spec.ImagePullPolicy = \"IfNotPresent\"\n\t\tbreak\n\tcase \"Always\":\n\t\tbreak\n\tcase \"IfNotPresent\":\n\t\tbreak\n\tdefault:\n\t\treturn fmt.Errorf(\"ImagePullPolicy must be one of \\\"Always\\\" or \\\"IfNotPresent\\\"; value=\\\"%s\\\"\",\n\t\t\tcr.Spec.ImagePullPolicy)\n\t}\n\n\t// SchedulerName\n\tif cr.Spec.SchedulerName == \"\" {\n\t\tcr.Spec.SchedulerName = \"default-scheduler\"\n\t}\n\n\treturn nil\n}", "func IsResourceNamespaced(kind string) bool {\n\tswitch kind {\n\tcase \"Namespace\",\n\t\t\"Node\",\n\t\t\"PersistentVolume\",\n\t\t\"PodSecurityPolicy\",\n\t\t\"CertificateSigningRequest\",\n\t\t\"ClusterRoleBinding\",\n\t\t\"ClusterRole\",\n\t\t\"VolumeAttachment\",\n\t\t\"StorageClass\",\n\t\t\"CSIDriver\",\n\t\t\"CSINode\",\n\t\t\"ValidatingWebhookConfiguration\",\n\t\t\"MutatingWebhookConfiguration\",\n\t\t\"CustomResourceDefinition\",\n\t\t\"PriorityClass\",\n\t\t\"RuntimeClass\":\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\n}", "func (r deleteReq) Validate() error {\n\tif len(r.ServiceAccountID) == 0 {\n\t\treturn fmt.Errorf(\"the service account ID cannot be empty\")\n\t}\n\treturn nil\n}", "func resourceVolterraK8SPodSecurityPolicyCreate(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*APIClient)\n\n\tcreateMeta := &ves_io_schema.ObjectCreateMetaType{}\n\tcreateSpec := &ves_io_schema_k8s_pod_security_policy.CreateSpecType{}\n\tcreateReq := &ves_io_schema_k8s_pod_security_policy.CreateRequest{\n\t\tMetadata: createMeta,\n\t\tSpec: createSpec,\n\t}\n\n\tif v, ok := d.GetOk(\"annotations\"); ok && !isIntfNil(v) {\n\n\t\tms := map[string]string{}\n\n\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\tval := v.(string)\n\t\t\tms[k] = val\n\t\t}\n\t\tcreateMeta.Annotations = ms\n\t}\n\n\tif v, ok := d.GetOk(\"description\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Description =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"disable\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Disable =\n\t\t\tv.(bool)\n\t}\n\n\tif v, ok := d.GetOk(\"labels\"); ok && !isIntfNil(v) {\n\n\t\tms := map[string]string{}\n\n\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\tval := v.(string)\n\t\t\tms[k] = val\n\t\t}\n\t\tcreateMeta.Labels = ms\n\t}\n\n\tif v, ok := d.GetOk(\"name\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Name =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"namespace\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Namespace =\n\t\t\tv.(string)\n\t}\n\n\t//config_method_choice\n\n\tconfigMethodChoiceTypeFound := false\n\n\tif v, ok := d.GetOk(\"psp_spec\"); ok && !configMethodChoiceTypeFound {\n\n\t\tconfigMethodChoiceTypeFound = true\n\t\tconfigMethodChoiceInt := &ves_io_schema_k8s_pod_security_policy.CreateSpecType_PspSpec{}\n\t\tconfigMethodChoiceInt.PspSpec = &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType{}\n\t\tcreateSpec.ConfigMethodChoice = configMethodChoiceInt\n\n\t\tsl := v.(*schema.Set).List()\n\t\tfor _, set := range sl {\n\t\t\tcs := set.(map[string]interface{})\n\n\t\t\tif v, ok := cs[\"allow_privilege_escalation\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowPrivilegeEscalation = v.(bool)\n\n\t\t\t}\n\n\t\t\tallowedCapabilitiesChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"allowed_capabilities\"]; ok && !isIntfNil(v) && !allowedCapabilitiesChoiceTypeFound {\n\n\t\t\t\tallowedCapabilitiesChoiceTypeFound = true\n\t\t\t\tallowedCapabilitiesChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_AllowedCapabilities{}\n\t\t\t\tallowedCapabilitiesChoiceInt.AllowedCapabilities = &ves_io_schema_k8s_pod_security_policy.CapabilityListType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedCapabilitiesChoice = allowedCapabilitiesChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"capabilities\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tallowedCapabilitiesChoiceInt.AllowedCapabilities.Capabilities = ls\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"no_allowed_capabilities\"]; ok && !isIntfNil(v) && !allowedCapabilitiesChoiceTypeFound {\n\n\t\t\t\tallowedCapabilitiesChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tallowedCapabilitiesChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoAllowedCapabilities{}\n\t\t\t\t\tallowedCapabilitiesChoiceInt.NoAllowedCapabilities = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedCapabilitiesChoice = allowedCapabilitiesChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"allowed_csi_drivers\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedCsiDrivers = ls\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"allowed_flex_volumes\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedFlexVolumes = ls\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"allowed_host_paths\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tallowedHostPaths := make([]*ves_io_schema_k8s_pod_security_policy.HostPathType, len(sl))\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedHostPaths = allowedHostPaths\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\tallowedHostPaths[i] = &ves_io_schema_k8s_pod_security_policy.HostPathType{}\n\t\t\t\t\tallowedHostPathsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\tif w, ok := allowedHostPathsMapStrToI[\"path_prefix\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\tallowedHostPaths[i].PathPrefix = w.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif w, ok := allowedHostPathsMapStrToI[\"read_only\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\tallowedHostPaths[i].ReadOnly = w.(bool)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"allowed_proc_mounts\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedProcMounts = ls\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"allowed_unsafe_sysctls\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.AllowedUnsafeSysctls = ls\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"default_allow_privilege_escalation\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.DefaultAllowPrivilegeEscalation = v.(bool)\n\n\t\t\t}\n\n\t\t\tdefaultCapabilitiesChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"default_capabilities\"]; ok && !isIntfNil(v) && !defaultCapabilitiesChoiceTypeFound {\n\n\t\t\t\tdefaultCapabilitiesChoiceTypeFound = true\n\t\t\t\tdefaultCapabilitiesChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_DefaultCapabilities{}\n\t\t\t\tdefaultCapabilitiesChoiceInt.DefaultCapabilities = &ves_io_schema_k8s_pod_security_policy.CapabilityListType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.DefaultCapabilitiesChoice = defaultCapabilitiesChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"capabilities\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefaultCapabilitiesChoiceInt.DefaultCapabilities.Capabilities = ls\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"no_default_capabilities\"]; ok && !isIntfNil(v) && !defaultCapabilitiesChoiceTypeFound {\n\n\t\t\t\tdefaultCapabilitiesChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tdefaultCapabilitiesChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoDefaultCapabilities{}\n\t\t\t\t\tdefaultCapabilitiesChoiceInt.NoDefaultCapabilities = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.DefaultCapabilitiesChoice = defaultCapabilitiesChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tdropCapabilitiesChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"drop_capabilities\"]; ok && !isIntfNil(v) && !dropCapabilitiesChoiceTypeFound {\n\n\t\t\t\tdropCapabilitiesChoiceTypeFound = true\n\t\t\t\tdropCapabilitiesChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_DropCapabilities{}\n\t\t\t\tdropCapabilitiesChoiceInt.DropCapabilities = &ves_io_schema_k8s_pod_security_policy.CapabilityListType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.DropCapabilitiesChoice = dropCapabilitiesChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"capabilities\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdropCapabilitiesChoiceInt.DropCapabilities.Capabilities = ls\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"no_drop_capabilities\"]; ok && !isIntfNil(v) && !dropCapabilitiesChoiceTypeFound {\n\n\t\t\t\tdropCapabilitiesChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tdropCapabilitiesChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoDropCapabilities{}\n\t\t\t\t\tdropCapabilitiesChoiceInt.NoDropCapabilities = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.DropCapabilitiesChoice = dropCapabilitiesChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"forbidden_sysctls\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.ForbiddenSysctls = ls\n\n\t\t\t}\n\n\t\t\tfsGroupChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"fs_group_strategy_options\"]; ok && !isIntfNil(v) && !fsGroupChoiceTypeFound {\n\n\t\t\t\tfsGroupChoiceTypeFound = true\n\t\t\t\tfsGroupChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_FsGroupStrategyOptions{}\n\t\t\t\tfsGroupChoiceInt.FsGroupStrategyOptions = &ves_io_schema_k8s_pod_security_policy.IDStrategyOptionsType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.FsGroupChoice = fsGroupChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"id_ranges\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tidRanges := make([]*ves_io_schema_k8s_pod_security_policy.IDRangeType, len(sl))\n\t\t\t\t\t\tfsGroupChoiceInt.FsGroupStrategyOptions.IdRanges = idRanges\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tidRanges[i] = &ves_io_schema_k8s_pod_security_policy.IDRangeType{}\n\t\t\t\t\t\t\tidRangesMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"max_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MaxId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"min_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MinId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"rule\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tfsGroupChoiceInt.FsGroupStrategyOptions.Rule = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"no_fs_groups\"]; ok && !isIntfNil(v) && !fsGroupChoiceTypeFound {\n\n\t\t\t\tfsGroupChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tfsGroupChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoFsGroups{}\n\t\t\t\t\tfsGroupChoiceInt.NoFsGroups = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.FsGroupChoice = fsGroupChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tgroupChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"no_run_as_group\"]; ok && !isIntfNil(v) && !groupChoiceTypeFound {\n\n\t\t\t\tgroupChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tgroupChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoRunAsGroup{}\n\t\t\t\t\tgroupChoiceInt.NoRunAsGroup = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.GroupChoice = groupChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"run_as_group\"]; ok && !isIntfNil(v) && !groupChoiceTypeFound {\n\n\t\t\t\tgroupChoiceTypeFound = true\n\t\t\t\tgroupChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_RunAsGroup{}\n\t\t\t\tgroupChoiceInt.RunAsGroup = &ves_io_schema_k8s_pod_security_policy.IDStrategyOptionsType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.GroupChoice = groupChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"id_ranges\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tidRanges := make([]*ves_io_schema_k8s_pod_security_policy.IDRangeType, len(sl))\n\t\t\t\t\t\tgroupChoiceInt.RunAsGroup.IdRanges = idRanges\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tidRanges[i] = &ves_io_schema_k8s_pod_security_policy.IDRangeType{}\n\t\t\t\t\t\t\tidRangesMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"max_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MaxId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"min_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MinId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"rule\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tgroupChoiceInt.RunAsGroup.Rule = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"host_ipc\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.HostIpc = v.(bool)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"host_network\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.HostNetwork = v.(bool)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"host_pid\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.HostPid = v.(bool)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"host_port_ranges\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.HostPortRanges = v.(string)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"privileged\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.Privileged = v.(bool)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"read_only_root_filesystem\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tconfigMethodChoiceInt.PspSpec.ReadOnlyRootFilesystem = v.(bool)\n\n\t\t\t}\n\n\t\t\truntimeClassChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"no_runtime_class\"]; ok && !isIntfNil(v) && !runtimeClassChoiceTypeFound {\n\n\t\t\t\truntimeClassChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\truntimeClassChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoRuntimeClass{}\n\t\t\t\t\truntimeClassChoiceInt.NoRuntimeClass = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.RuntimeClassChoice = runtimeClassChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"runtime_class\"]; ok && !isIntfNil(v) && !runtimeClassChoiceTypeFound {\n\n\t\t\t\truntimeClassChoiceTypeFound = true\n\t\t\t\truntimeClassChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_RuntimeClass{}\n\t\t\t\truntimeClassChoiceInt.RuntimeClass = &ves_io_schema_k8s_pod_security_policy.RuntimeClassStrategyOptions{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.RuntimeClassChoice = runtimeClassChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"allowed_runtime_class_names\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t\t\t}\n\t\t\t\t\t\truntimeClassChoiceInt.RuntimeClass.AllowedRuntimeClassNames = ls\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"default_runtime_class_name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\truntimeClassChoiceInt.RuntimeClass.DefaultRuntimeClassName = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tseLinuxChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"no_se_linux_options\"]; ok && !isIntfNil(v) && !seLinuxChoiceTypeFound {\n\n\t\t\t\tseLinuxChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tseLinuxChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoSeLinuxOptions{}\n\t\t\t\t\tseLinuxChoiceInt.NoSeLinuxOptions = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.SeLinuxChoice = seLinuxChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"se_linux_options\"]; ok && !isIntfNil(v) && !seLinuxChoiceTypeFound {\n\n\t\t\t\tseLinuxChoiceTypeFound = true\n\t\t\t\tseLinuxChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_SeLinuxOptions{}\n\t\t\t\tseLinuxChoiceInt.SeLinuxOptions = &ves_io_schema_k8s_pod_security_policy.SELinuxStrategyOptions{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.SeLinuxChoice = seLinuxChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"level\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tseLinuxChoiceInt.SeLinuxOptions.Level = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"role\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tseLinuxChoiceInt.SeLinuxOptions.Role = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"rule\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tseLinuxChoiceInt.SeLinuxOptions.Rule = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"type\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tseLinuxChoiceInt.SeLinuxOptions.Type = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"user\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tseLinuxChoiceInt.SeLinuxOptions.User = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tsupplementalGroupChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"no_supplemental_groups\"]; ok && !isIntfNil(v) && !supplementalGroupChoiceTypeFound {\n\n\t\t\t\tsupplementalGroupChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tsupplementalGroupChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoSupplementalGroups{}\n\t\t\t\t\tsupplementalGroupChoiceInt.NoSupplementalGroups = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.SupplementalGroupChoice = supplementalGroupChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"supplemental_groups\"]; ok && !isIntfNil(v) && !supplementalGroupChoiceTypeFound {\n\n\t\t\t\tsupplementalGroupChoiceTypeFound = true\n\t\t\t\tsupplementalGroupChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_SupplementalGroups{}\n\t\t\t\tsupplementalGroupChoiceInt.SupplementalGroups = &ves_io_schema_k8s_pod_security_policy.IDStrategyOptionsType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.SupplementalGroupChoice = supplementalGroupChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"id_ranges\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tidRanges := make([]*ves_io_schema_k8s_pod_security_policy.IDRangeType, len(sl))\n\t\t\t\t\t\tsupplementalGroupChoiceInt.SupplementalGroups.IdRanges = idRanges\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tidRanges[i] = &ves_io_schema_k8s_pod_security_policy.IDRangeType{}\n\t\t\t\t\t\t\tidRangesMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"max_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MaxId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"min_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MinId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"rule\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsupplementalGroupChoiceInt.SupplementalGroups.Rule = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tuserChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"no_run_as_user\"]; ok && !isIntfNil(v) && !userChoiceTypeFound {\n\n\t\t\t\tuserChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tuserChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_NoRunAsUser{}\n\t\t\t\t\tuserChoiceInt.NoRunAsUser = &ves_io_schema.Empty{}\n\t\t\t\t\tconfigMethodChoiceInt.PspSpec.UserChoice = userChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"run_as_user\"]; ok && !isIntfNil(v) && !userChoiceTypeFound {\n\n\t\t\t\tuserChoiceTypeFound = true\n\t\t\t\tuserChoiceInt := &ves_io_schema_k8s_pod_security_policy.PodSecurityPolicySpecType_RunAsUser{}\n\t\t\t\tuserChoiceInt.RunAsUser = &ves_io_schema_k8s_pod_security_policy.IDStrategyOptionsType{}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.UserChoice = userChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"id_ranges\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.([]interface{})\n\t\t\t\t\t\tidRanges := make([]*ves_io_schema_k8s_pod_security_policy.IDRangeType, len(sl))\n\t\t\t\t\t\tuserChoiceInt.RunAsUser.IdRanges = idRanges\n\t\t\t\t\t\tfor i, set := range sl {\n\t\t\t\t\t\t\tidRanges[i] = &ves_io_schema_k8s_pod_security_policy.IDRangeType{}\n\t\t\t\t\t\t\tidRangesMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"max_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MaxId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif w, ok := idRangesMapStrToI[\"min_id\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\tidRanges[i].MinId = uint32(w.(int))\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"rule\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tuserChoiceInt.RunAsUser.Rule = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"volumes\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tls := make([]string, len(v.([]interface{})))\n\t\t\t\tfor i, v := range v.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tconfigMethodChoiceInt.PspSpec.Volumes = ls\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"yaml\"); ok && !configMethodChoiceTypeFound {\n\n\t\tconfigMethodChoiceTypeFound = true\n\t\tconfigMethodChoiceInt := &ves_io_schema_k8s_pod_security_policy.CreateSpecType_Yaml{}\n\n\t\tcreateSpec.ConfigMethodChoice = configMethodChoiceInt\n\n\t\tconfigMethodChoiceInt.Yaml = v.(string)\n\n\t}\n\n\tlog.Printf(\"[DEBUG] Creating Volterra K8SPodSecurityPolicy object with struct: %+v\", createReq)\n\n\tcreateK8SPodSecurityPolicyResp, err := client.CreateObject(context.Background(), ves_io_schema_k8s_pod_security_policy.ObjectType, createReq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating K8SPodSecurityPolicy: %s\", err)\n\t}\n\td.SetId(createK8SPodSecurityPolicyResp.GetObjSystemMetadata().GetUid())\n\n\treturn resourceVolterraK8SPodSecurityPolicyRead(d, meta)\n}", "func (p *plugin) Validate(req json.RawMessage) error {\n\tlog.Debugln(\"validate\", string(req))\n\n\tparsed := SpecPropertiesFormat{}\n\terr := json.Unmarshal([]byte(req), &parsed)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif parsed.Type == \"\" {\n\t\treturn fmt.Errorf(\"no-resource-type:%s\", string(req))\n\t}\n\n\tif len(parsed.Value) == 0 {\n\t\treturn fmt.Errorf(\"no-value:%s\", string(req))\n\t}\n\treturn nil\n}", "func validateK8STrigger(trigger *v1alpha1.StandardK8STrigger) error {\n\tif trigger == nil {\n\t\treturn errors.New(\"k8s trigger for can't be nil\")\n\t}\n\tif trigger.Source == nil {\n\t\treturn errors.New(\"k8s trigger for does not contain an absolute action\")\n\t}\n\tif trigger.GroupVersionResource.Size() == 0 {\n\t\treturn errors.New(\"must provide group, version and resource for the resource\")\n\t}\n\tswitch trigger.Operation {\n\tcase \"\", v1alpha1.Create, v1alpha1.Patch, v1alpha1.Update:\n\tdefault:\n\t\treturn errors.Errorf(\"unknown operation type %s\", string(trigger.Operation))\n\t}\n\tif trigger.Parameters != nil {\n\t\tfor i, parameter := range trigger.Parameters {\n\t\t\tif err := validateTriggerParameter(&parameter); err != nil {\n\t\t\t\treturn errors.Errorf(\"resource parameter index: %d. err: %+v\", i, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (v *validator) Validate(ctx context.Context, seed *kubermaticv1.Seed, op admissionv1.Operation) error {\n\t// We need locking to make the validation concurrency-safe\n\t// TODO: this is acceptable as request rate is low, but is it required?\n\tv.lock.Lock()\n\tdefer v.lock.Unlock()\n\n\tseeds := kubermaticv1.SeedList{}\n\terr := v.client.List(ctx, &seeds)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get seeds: %v\", err)\n\t}\n\tseedsMap := map[string]*kubermaticv1.Seed{}\n\tfor i, s := range seeds.Items {\n\t\tseedsMap[s.Name] = &seeds.Items[i]\n\t}\n\tif op == admissionv1.Delete {\n\t\t// when a namespace is deleted, a DELETE call for all seeds in the namespace\n\t\t// is issued; this request has no .Request.Name set, so this check will make\n\t\t// sure that we exit cleanly and allow deleting namespaces without seeds\n\t\tif _, exists := seedsMap[seed.Name]; !exists && op == admissionv1.Delete {\n\t\t\treturn nil\n\t\t}\n\t\t// in case of delete request the seed is empty\n\t\tseed = seedsMap[seed.Name]\n\t}\n\n\tclient, err := v.seedClientGetter(seed)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get client for seed %q: %v\", seed.Name, err)\n\t}\n\n\treturn v.validate(ctx, seed, client, seedsMap, op == admissionv1.Delete)\n}", "func (s *OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors_Selector_Config) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors_Selector_Config\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *CheckRightOnResourcesV4Request) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateResourceCrns(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateRight(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (t *OpenconfigInterfaces_Interfaces_Interface_Subinterfaces_Subinterface_Ipv4) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_Subinterfaces_Subinterface_Ipv4\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (w *WhoCan) validate(action Action) error {\n\tif action.NonResourceURL != \"\" && action.SubResource != \"\" {\n\t\treturn fmt.Errorf(\"--subresource cannot be used with NONRESOURCEURL\")\n\t}\n\n\terr := w.namespaceValidator.Validate(action.Namespace)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"validating namespace: %v\", err)\n\t}\n\n\treturn nil\n}", "func validateK3sControlPlaneTemplateResourceSpec(s K3sControlPlaneTemplateResourceSpec, pathPrefix *field.Path) field.ErrorList {\n\treturn validateRolloutStrategy(s.RolloutStrategy, nil, pathPrefix.Child(\"rolloutStrategy\"))\n}", "func CfnRegistryPolicy_IsCfnResource(construct constructs.IConstruct) *bool {\n\t_init_.Initialize()\n\n\tvar returns *bool\n\n\t_jsii_.StaticInvoke(\n\t\t\"monocdk.aws_ecr.CfnRegistryPolicy\",\n\t\t\"isCfnResource\",\n\t\t[]interface{}{construct},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func (o *deleteSvcOpts) Validate() error {\n\treturn nil\n}", "func (s *OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors_Selector_State) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Selectors_Selector_State\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (sc selectCriterion) Validate() error {\n\tif sc.name == \"\" {\n\t\treturn fmt.Errorf(\"name is empty\")\n\t}\n\tif i := strings.IndexAny(sc.name, InvalidCriterionRunes); i == 0 {\n\t\treturn fmt.Errorf(\"name starts with invalid character '%v'\", sc.name[i])\n\t}\n\tif sc.name == SelectAll {\n\t\tif sc.tagged {\n\t\t\treturn fmt.Errorf(\"cannot use '.' with special name 'v'\", SelectAll)\n\t\t}\n\t\tif sc.negated {\n\t\t\treturn fmt.Errorf(\"cannot use '!' with special name 'v'\", SelectAll)\n\t\t}\n\t}\n\treturn nil\n}", "func validateK8sTriggerPolicy(policy *v1alpha1.K8SResourcePolicy) error {\n\tif policy == nil {\n\t\treturn nil\n\t}\n\tif policy.Labels == nil {\n\t\treturn errors.New(\"resource labels are not specified\")\n\t}\n\tif &policy.Backoff == nil {\n\t\treturn errors.New(\"backoff is not specified\")\n\t}\n\treturn nil\n}", "func (s *OpenconfigInterfaces_Interfaces_Interface_Subinterfaces_Subinterface_Ipv4) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_Subinterfaces_Subinterface_Ipv4\"], s, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *Qos_Qos_Qos_ConnectivityService) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"Qos_Qos_Qos_ConnectivityService\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func TestDiscoveryResourceGate(t *testing.T) {\n\tresources := map[string][]metav1.APIResource{\n\t\t\"allLegacy\": {\n\t\t\t{Name: \"clusterpolicies\", Kind: \"ClusterPolicies\"},\n\t\t\t{Name: \"clusterpolicybindings\", Kind: \"ClusterPolicyBindings\"},\n\t\t\t{Name: \"policies\", Kind: \"Policies\"},\n\t\t\t{Name: \"policybindings\", Kind: \"PolicyBindings\"},\n\t\t\t{Name: \"foo\", Kind: \"Foo\"},\n\t\t},\n\t\t\"partialLegacy\": {\n\t\t\t{Name: \"clusterpolicies\", Kind: \"ClusterPolicies\"},\n\t\t\t{Name: \"clusterpolicybindings\", Kind: \"ClusterPolicyBindings\"},\n\t\t\t{Name: \"foo\", Kind: \"Foo\"},\n\t\t},\n\t\t\"noLegacy\": {\n\t\t\t{Name: \"foo\", Kind: \"Foo\"},\n\t\t\t{Name: \"bar\", Kind: \"Bar\"},\n\t\t},\n\t}\n\n\tlegacyTests := map[string]struct {\n\t\texistingResources *metav1.APIResourceList\n\t\texpectErrStr string\n\t}{\n\t\t\"scheme-legacy-all-supported\": {\n\t\t\texistingResources: &metav1.APIResourceList{\n\t\t\t\tGroupVersion: authorization.LegacySchemeGroupVersion.String(),\n\t\t\t\tAPIResources: resources[\"allLegacy\"],\n\t\t\t},\n\t\t\texpectErrStr: \"\",\n\t\t},\n\t\t\"scheme-legacy-some-supported\": {\n\t\t\texistingResources: &metav1.APIResourceList{\n\t\t\t\tGroupVersion: authorization.LegacySchemeGroupVersion.String(),\n\t\t\t\tAPIResources: resources[\"partialLegacy\"],\n\t\t\t},\n\t\t\texpectErrStr: \"the server does not support legacy policy resources\",\n\t\t},\n\t\t\"scheme-legacy-none-supported\": {\n\t\t\texistingResources: &metav1.APIResourceList{\n\t\t\t\tGroupVersion: authorization.LegacySchemeGroupVersion.String(),\n\t\t\t\tAPIResources: resources[\"noLegacy\"],\n\t\t\t},\n\t\t\texpectErrStr: \"the server does not support legacy policy resources\",\n\t\t},\n\t\t\"scheme-all-supported\": {\n\t\t\texistingResources: &metav1.APIResourceList{\n\t\t\t\tGroupVersion: authorization.SchemeGroupVersion.String(),\n\t\t\t\tAPIResources: resources[\"allLegacy\"],\n\t\t\t},\n\t\t\texpectErrStr: \"\",\n\t\t},\n\t\t\"scheme-some-supported\": {\n\t\t\texistingResources: &metav1.APIResourceList{\n\t\t\t\tGroupVersion: authorization.SchemeGroupVersion.String(),\n\t\t\t\tAPIResources: resources[\"partialLegacy\"],\n\t\t\t},\n\t\t\texpectErrStr: \"the server does not support legacy policy resources\",\n\t\t},\n\t\t\"scheme-none-supported\": {\n\t\t\texistingResources: &metav1.APIResourceList{\n\t\t\t\tGroupVersion: authorization.SchemeGroupVersion.String(),\n\t\t\t\tAPIResources: resources[\"noLegacy\"],\n\t\t\t},\n\t\t\texpectErrStr: \"the server does not support legacy policy resources\",\n\t\t},\n\t}\n\n\tdiscoveryTests := map[string]struct {\n\t\texistingResources *metav1.APIResourceList\n\t\tinputGVR []schema.GroupVersionResource\n\t\texpectedGVR []schema.GroupVersionResource\n\t\texpectedAll bool\n\t}{\n\t\t\"discovery-subset\": {\n\t\t\texistingResources: &metav1.APIResourceList{\n\t\t\t\tGroupVersion: \"v1\",\n\t\t\t\tAPIResources: resources[\"noLegacy\"],\n\t\t\t},\n\t\t\tinputGVR: []schema.GroupVersionResource{\n\t\t\t\t{\n\t\t\t\t\tGroup: \"\",\n\t\t\t\t\tVersion: \"v1\",\n\t\t\t\t\tResource: \"foo\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tGroup: \"\",\n\t\t\t\t\tVersion: \"v1\",\n\t\t\t\t\tResource: \"bar\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tGroup: \"\",\n\t\t\t\t\tVersion: \"v1\",\n\t\t\t\t\tResource: \"noexist\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedGVR: []schema.GroupVersionResource{\n\t\t\t\t{\n\t\t\t\t\tGroup: \"\",\n\t\t\t\t\tVersion: \"v1\",\n\t\t\t\t\tResource: \"foo\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tGroup: \"\",\n\t\t\t\t\tVersion: \"v1\",\n\t\t\t\t\tResource: \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"discovery-none\": {\n\t\t\texistingResources: &metav1.APIResourceList{\n\t\t\t\tGroupVersion: \"v1\",\n\t\t\t\tAPIResources: resources[\"noLegacy\"],\n\t\t\t},\n\t\t\tinputGVR: []schema.GroupVersionResource{\n\t\t\t\t{\n\t\t\t\t\tGroup: \"\",\n\t\t\t\t\tVersion: \"v1\",\n\t\t\t\t\tResource: \"noexist\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedGVR: []schema.GroupVersionResource{},\n\t\t},\n\t\t\"discovery-all\": {\n\t\t\texistingResources: &metav1.APIResourceList{\n\t\t\t\tGroupVersion: \"v1\",\n\t\t\t\tAPIResources: resources[\"noLegacy\"],\n\t\t\t},\n\t\t\tinputGVR: []schema.GroupVersionResource{\n\t\t\t\t{\n\t\t\t\t\tGroup: \"\",\n\t\t\t\t\tVersion: \"v1\",\n\t\t\t\t\tResource: \"foo\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tGroup: \"\",\n\t\t\t\t\tVersion: \"v1\",\n\t\t\t\t\tResource: \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedGVR: []schema.GroupVersionResource{\n\t\t\t\t{\n\t\t\t\t\tGroup: \"\",\n\t\t\t\t\tVersion: \"v1\",\n\t\t\t\t\tResource: \"foo\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tGroup: \"\",\n\t\t\t\t\tVersion: \"v1\",\n\t\t\t\t\tResource: \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedAll: true,\n\t\t},\n\t}\n\n\tfor tcName, tc := range discoveryTests {\n\t\tfunc() {\n\t\t\tserver := testServer(t, tc.existingResources)\n\t\t\tdefer server.Close()\n\t\t\tclient := discovery.NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})\n\n\t\t\tgot, all, err := DiscoverGroupVersionResources(client, tc.inputGVR...)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"myerr %s\", err.Error())\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(got, tc.expectedGVR) {\n\t\t\t\tt.Fatalf(\"%s got %v, expected %v\", tcName, got, tc.expectedGVR)\n\t\t\t}\n\t\t\tif tc.expectedAll && !all {\n\t\t\t\tt.Fatalf(\"%s expected all\", tcName)\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor tcName, tc := range legacyTests {\n\t\tfunc() {\n\t\t\tserver := testServer(t, tc.existingResources)\n\t\t\tdefer server.Close()\n\t\t\tclient := discovery.NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})\n\n\t\t\terr := LegacyPolicyResourceGate(client)\n\t\t\tif err != nil {\n\t\t\t\tif len(tc.expectErrStr) == 0 {\n\t\t\t\t\tt.Fatalf(\"%s unexpected err %s\\n\", tcName, err.Error())\n\t\t\t\t}\n\t\t\t\tif tc.expectErrStr != err.Error() {\n\t\t\t\t\tt.Fatalf(\"%s expected err %s, got %s\", tcName, tc.expectErrStr, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err == nil && len(tc.expectErrStr) != 0 {\n\t\t\t\tt.Fatalf(\"%s expected err %s, got none\\n\", tcName, tc.expectErrStr)\n\t\t\t}\n\t\t}()\n\t}\n}", "func TbCustomImageReqStructLevelValidation(sl validator.StructLevel) {\n\n\tu := sl.Current().Interface().(TbCustomImageReq)\n\n\terr := common.CheckString(u.Name)\n\tif err != nil {\n\t\t// ReportError(field interface{}, fieldName, structFieldName, tag, param string)\n\t\tsl.ReportError(u.Name, \"name\", \"Name\", err.Error(), \"\")\n\t}\n}", "func (setting *MongodbDatabaseCollectionThroughputSetting) validateResourceReferences() (admission.Warnings, error) {\n\trefs, err := reflecthelpers.FindResourceReferences(&setting.Spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn genruntime.ValidateResourceReferences(refs)\n}", "func resourceVolterraNetworkPolicyRule() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceVolterraNetworkPolicyRuleCreate,\n\t\tRead: resourceVolterraNetworkPolicyRuleRead,\n\t\tUpdate: resourceVolterraNetworkPolicyRuleUpdate,\n\t\tDelete: resourceVolterraNetworkPolicyRuleDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\"annotations\": {\n\t\t\t\tType: schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"description\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"disable\": {\n\t\t\t\tType: schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"labels\": {\n\t\t\t\tType: schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"namespace\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"action\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"advanced_action\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"action\": {\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"label_matcher\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"keys\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"ports\": {\n\n\t\t\t\tType: schema.TypeList,\n\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"protocol\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"ip_prefix_set\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"ref\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\t\t\t\"kind\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\"namespace\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\"tenant\": {\n\t\t\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"prefix\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"ipv6_prefix\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"prefix\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"prefix_selector\": {\n\n\t\t\t\tType: schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\n\t\t\t\t\t\t\"expressions\": {\n\n\t\t\t\t\t\t\tType: schema.TypeList,\n\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (o TopImagesOptions) Validate(cmd *cobra.Command) error {\n\treturn nil\n}", "func (m *SearchResources) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateResource(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func NamespaceForResourceIsReady(resource common.ComponentResource) (bool, error) {\n\t// create a stub namespace resource to pass to the NamespaceIsReady method\n\tnamespace := &Resource{\n\t\tReconciler: resource.GetReconciler(),\n\t}\n\n\t// insert the inherited fields\n\tnamespace.Name = resource.GetNamespace()\n\tnamespace.Group = \"\"\n\tnamespace.Version = \"v1\"\n\tnamespace.Kind = NamespaceKind\n\n\treturn NamespaceIsReady(namespace)\n}", "func (t Topic) Validate() error {\n\treturn validateResource(string(t), \"topics\")\n}", "func (opts Options) validate() error {\n\t// AzureDNSClient is only not nil for the tests.\n\tif opts.AzureAuthentication == nil && opts.AzureDNSClient == nil {\n\t\treturn errAzureAuthenticationNil\n\t}\n\n\tif opts.KubeClient == nil {\n\t\treturn errKubeClientNil\n\t}\n\n\tif len(opts.DomainNameRoot) <= 0 {\n\t\treturn errDomainNameRootEmpty\n\t}\n\n\tif len(opts.ResourceGroupName) <= 0 {\n\t\treturn errResourceGroupNameEmpty\n\t}\n\n\tif len(opts.ResourceName) <= 0 {\n\t\treturn errResourceNameEmpty\n\t}\n\n\tif len(opts.Region) <= 0 {\n\t\treturn errRegionEmpty\n\t}\n\n\treturn nil\n}", "func (r *Resource) Valid() bool {\n\tif r.Spec == nil {\n\t\tfmt.Println(\"no resource spec\")\n\t\treturn false\n\t}\n\n\treturn r.Spec.Valid()\n}", "func validateSelectRead(media []*medium) (a cmdArgs, err error) {\n\tif len(media) > 1 {\n\t\terr = tooManyInputs\n\t\treturn\n\t}\n\n\tif len(media) == 0 {\n\t\ta.in, err = processEtcdArgs(defaultEtcdUrls, defaultEtcdPrefix, \"\")\n\t\treturn\n\t}\n\n\tswitch media[0].typ {\n\tcase inlineIds, patchPrepend, patchPrependFile, patchAppend, patchAppendFile:\n\t\terr = invalidInputType\n\t\treturn\n\t}\n\n\ta.in = media[0]\n\treturn\n}", "func ValidateControllerRegistrationSpecUpdate(new, old *core.ControllerRegistrationSpec, deletionTimestampSet bool, fldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif deletionTimestampSet && !apiequality.Semantic.DeepEqual(new, old) {\n\t\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(new, old, fldPath)...)\n\t\treturn allErrs\n\t}\n\n\tkindTypeToPrimary := make(map[string]*bool, len(old.Resources))\n\tfor _, resource := range old.Resources {\n\t\tkindTypeToPrimary[resource.Kind+resource.Type] = resource.Primary\n\t}\n\tfor i, resource := range new.Resources {\n\t\tif primary, ok := kindTypeToPrimary[resource.Kind+resource.Type]; ok {\n\t\t\tallErrs = append(allErrs, apivalidation.ValidateImmutableField(resource.Primary, primary, fldPath.Child(\"resources\").Index(i).Child(\"primary\"))...)\n\t\t}\n\t}\n\n\treturn allErrs\n}", "func NewResourceCondition(ref *common.ResourceRef) ResourceConditionInterface {\n\tkvg := ref.SprintKindVersionGroup()\n\trc, found := supportedResourceConditions[kvg]\n\tif found == false {\n\t\trc = nil\n\t}\n\treturn rc\n}", "func TestUpdate_Unit_EmptyLabelSelector(t *testing.T) {\n\n\tvar dr Router\n\tdr = &MockedResources{}\n\n\tvar vs Router\n\tvs = &MockedResources{}\n\n\tshift := router.Shift{}\n\n\tvar op Operator\n\top = &Istiops{\n\t\tDrRouter: dr,\n\t\tVsRouter: vs,\n\t}\n\n\terr := op.Update(shift)\n\tassert.EqualError(t, err, \"label-selector must exists in need to find resources\")\n}", "func (m *CreateNamespaceQuotaReq) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif l := utf8.RuneCountInString(m.GetNamespace()); l < 2 || l > 100 {\n\t\treturn CreateNamespaceQuotaReqValidationError{\n\t\t\tfield: \"Namespace\",\n\t\t\treason: \"value length must be between 2 and 100 runes, inclusive\",\n\t\t}\n\t}\n\n\tif utf8.RuneCountInString(m.GetFederationClusterID()) > 100 {\n\t\treturn CreateNamespaceQuotaReqValidationError{\n\t\t\tfield: \"FederationClusterID\",\n\t\t\treason: \"value length must be at most 100 runes\",\n\t\t}\n\t}\n\n\tif utf8.RuneCountInString(m.GetClusterID()) > 100 {\n\t\treturn CreateNamespaceQuotaReqValidationError{\n\t\t\tfield: \"ClusterID\",\n\t\t\treason: \"value length must be at most 100 runes\",\n\t\t}\n\t}\n\n\tif utf8.RuneCountInString(m.GetRegion()) > 100 {\n\t\treturn CreateNamespaceQuotaReqValidationError{\n\t\t\tfield: \"Region\",\n\t\t\treason: \"value length must be at most 100 runes\",\n\t\t}\n\t}\n\n\t// no validation rules for ResourceQuota\n\n\treturn nil\n}", "func (t *OpenconfigQos_Qos_Classifiers_Classifier_Terms_Term_Conditions) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Classifiers_Classifier_Terms_Term_Conditions\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (client *Client) CheckCloudResourceAuthorizedWithOptions(request *CheckCloudResourceAuthorizedRequest, runtime *util.RuntimeOptions) (_result *CheckCloudResourceAuthorizedResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.InstanceId)) {\n\t\tquery[\"InstanceId\"] = request.InstanceId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerAccount)) {\n\t\tquery[\"OwnerAccount\"] = request.OwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerId)) {\n\t\tquery[\"OwnerId\"] = request.OwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerAccount)) {\n\t\tquery[\"ResourceOwnerAccount\"] = request.ResourceOwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerId)) {\n\t\tquery[\"ResourceOwnerId\"] = request.ResourceOwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.RoleArn)) {\n\t\tquery[\"RoleArn\"] = request.RoleArn\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SecurityToken)) {\n\t\tquery[\"SecurityToken\"] = request.SecurityToken\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"CheckCloudResourceAuthorized\"),\n\t\tVersion: tea.String(\"2015-01-01\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &CheckCloudResourceAuthorizedResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (s *PostgresSpec) ObserveSelectors(rsrc interface{}) []ResourceSelector {\n\tr := rsrc.(*AirflowBase)\n\tif s.Operator {\n\t\treturn nil\n\t}\n\tselector := selectorLabels(r, ValueAirflowComponentPostgres)\n\tsecretSelector := selectorLabels(r, ValueAirflowComponentPostgres)\n\trsrcSelectos := []ResourceSelector{\n\t\t{&resources.StatefulSet{}, selector},\n\t\t{&resources.Service{}, selector},\n\t\t{&resources.Secret{}, secretSelector},\n\t\t{&resources.PodDisruptionBudget{}, selector},\n\t}\n\t//if s.VolumeClaimTemplate != nil {\n\t//\trsrcSelectos = append(rsrcSelectos, ResourceSelector{s.VolumeClaimTemplate, nil})\n\t//}\n\treturn rsrcSelectos\n}" ]
[ "0.59584147", "0.5700171", "0.5696888", "0.56482863", "0.55733466", "0.5490589", "0.5441203", "0.5355841", "0.5320605", "0.5286241", "0.528479", "0.51627755", "0.5150385", "0.514723", "0.5142086", "0.51359487", "0.50891954", "0.50874746", "0.5085249", "0.49886724", "0.49864337", "0.49799454", "0.49588868", "0.4947418", "0.48951918", "0.489457", "0.48921522", "0.48917222", "0.4879877", "0.48758942", "0.48561984", "0.4837104", "0.48315364", "0.48307315", "0.48282707", "0.48198515", "0.48125488", "0.47837245", "0.47707272", "0.47650874", "0.47620618", "0.47580746", "0.4736916", "0.47324926", "0.47316223", "0.47189975", "0.47154793", "0.47030818", "0.4686685", "0.46838415", "0.46750504", "0.4670461", "0.4654456", "0.46542817", "0.46418408", "0.46418408", "0.46404904", "0.46302986", "0.46260333", "0.46227896", "0.4620711", "0.46157253", "0.45900446", "0.4580738", "0.457716", "0.45765427", "0.4571648", "0.45658255", "0.4564042", "0.45610094", "0.45604318", "0.4557306", "0.4555927", "0.45549107", "0.45511654", "0.45501846", "0.4548094", "0.45387068", "0.45358163", "0.45349956", "0.4531337", "0.45298812", "0.4529672", "0.45296577", "0.4528455", "0.45202333", "0.45105314", "0.44924912", "0.44765055", "0.4474568", "0.44696963", "0.44657195", "0.4465683", "0.44607705", "0.44569254", "0.44544676", "0.44533348", "0.4447023", "0.4443836", "0.44431514" ]
0.71744615
0
NewClient returns an instance of REST API client. If a nil httpClient is provided, http.DefaultClient will be used.
func NewClient(httpClient *http.Client, baseURL string) (*Client, error) { if httpClient == nil { httpClient = http.DefaultClient } base, err := url.Parse(baseURL) if err != nil { return nil, errors.New("Could not parse base URL") } c := &Client{client: httpClient, baseURL: base} return c, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\treturn &Client{\n\t\thttpClient: httpClient,\n\t}\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\treturn &Client{httpClient: httpClient}\n}", "func NewClient(httpClient *http.Client) *Client {\n\tvar c *http.Client\n\n\tif httpClient == nil {\n\t\tc = http.DefaultClient\n\t} else {\n\t\tc = httpClient\n\t}\n\n\treturn &Client{\n\t\tclient: c,\n\t}\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\tc := Client{\n\t\tBaseURL: baseURL,\n\t\tclient: httpClient,\n\t\tUserAgent: userAgent,\n\t}\n\treturn &c\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\tcloned := *http.DefaultClient\n\t\thttpClient = &cloned\n\t}\n\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\n\tc := &Client{\n\t\tclient: httpClient,\n\t\tBaseURL: baseURL,\n\t}\n\n\tc.common.client = c\n\tc.Question = (*QuestionService)(&c.common)\n\tc.Token = (*TokenService)(&c.common)\n\n\treturn c\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\tc := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent}\n\tc.Post = &PostServiceClient{client: c}\n\tc.User = &UserServiceClient{client: c}\n\treturn c\n}", "func NewClient(username, password string, httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\n\treturn &Client{\n\t\tclient: httpClient,\n\t\tusername: username,\n\t\tpassword: password,\n\t\tUserAgent: defaultUserAgent,\n\t\tBaseURL: baseURL,\n\t}\n}", "func NewClient(baseURL string, httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\tif baseURL == \"\" {\n\t\tbaseURL = \"https://httpbin.org\"\n\t}\n\n\treturn &Client{\n\t\tbaseURL: baseURL,\n\t\thttpClient: httpClient,\n\t}\n}", "func NewClient(baseURL *url.URL, token string, httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tc := &Client{client: httpClient, BaseURL: baseURL, token: token}\n\tc.Dashboards = NewDashboardsService(c)\n\tc.Datasources = NewDatasourcesService(c)\n\n\treturn c\n}", "func New(httpClient HTTPClient) *Client {\n\tif httpClient == nil {\n\t\tpanic(\"http.Client cannot == nil\")\n\t}\n\n\treturn &Client{client: httpClient}\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\n\tc := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent}\n\tc.Items = &ItemsService{client: c}\n\tc.Users = &UsersService{client: c}\n\tc.AuthenticatedUser = &AuthenticatedUserService{client: c}\n\tc.Tags = &TagsService{client: c}\n\treturn c\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\tbaseURL, _ := url.Parse(baseURL)\n\n\tc := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent}\n\tc.common.client = c\n\tc.RRSet = (*RRSetService)(&c.common)\n\tc.RData = (*RDataService)(&c.common)\n\n\treturn c\n}", "func New(url string, httpClient *http.Client, customHeaders http.Header) *Client {\n\tif httpClient == nil {\n\t\thttpClient = &http.Client{\n\t\t\tTimeout: defaultHTTPTimeout,\n\t\t}\n\t}\n\n\treturn &Client{\n\t\turl: url,\n\t\thttpClient: httpClient,\n\t\tcustomHeaders: customHeaders,\n\t}\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\tbaseURL, err := url.Parse(baseURL)\n\tc := &Client{client: httpClient, BaseURL: baseURL, err: err}\n\tc.common.client = c\n\tc.Teams = (*TeamsService)(&c.common)\n\tc.Invitations = (*InvitationsService)(&c.common)\n\treturn c\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = &http.Client{}\n\t}\n\tbaseURL, _ := url.Parse(baseURL)\n\tc := &Client{\n\t\tclient: httpClient,\n\t\tBaseURL: baseURL,\n\t}\n\tc.common.client = c\n\tc.Tags = (*TagsService)(&c.common)\n\tc.Manifests = (*ManifestsService)(&c.common)\n\treturn c\n}", "func NewClient(baseURL string, httpClient *http.Client) (*Client, error) {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tbaseEndpoint, err := url.Parse(baseURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !strings.HasSuffix(baseEndpoint.Path, \"/\") {\n\t\tbaseEndpoint.Path += \"/\"\n\t}\n\n\tc := &Client{\n\t\tclient: httpClient,\n\t\tBaseURL: baseEndpoint,\n\t}\n\tc.common.client = c\n\tc.Boards = (*BoardsService)(&c.common)\n\tc.Epics = (*EpicsService)(&c.common)\n\tc.Issues = (*IssuesService)(&c.common)\n\tc.Sprints = (*SprintsService)(&c.common)\n\tc.Backlog = (*BacklogService)(&c.common)\n\n\treturn c, nil\n}", "func NewClient(httpClient *http.Client, baseURL string) (*Client, error) {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tparsedBaseURL, err := url.Parse(baseURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := &Client{\n\t\tclient: httpClient,\n\t\tbaseURL: parsedBaseURL,\n\t}\n\tc.Authentication = &AuthenticationService{client: c}\n\tc.User = &UserService{client: c}\n\tc.Project = &ProjectService{client: c}\n\tc.Report = &ReportService{client: c}\n\treturn c, nil\n}", "func NewClient(apiKey string, httpClient HTTPClient) *Client {\n\treturn &Client{\n\t\tapiKey: apiKey,\n\t\tclient: httpClient,\n\t\tLanguage: \"en-us\", // change after creating a new client\n\t}\n}", "func NewClient(httpClient *http.Client, apiID, apiKey string) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tclient := &Client{}\n\n\tclient.SetHTTPClient(httpClient)\n\tclient.SetAPIID(apiID)\n\tclient.SetAPIKey(apiKey)\n\tclient.SetBaseURL(BaseURL)\n\tclient.SetDebug(false)\n\tclient.SetUserAgent(userAgent)\n\tclient.SetMediaType(mediaType)\n\tclient.SetCharset(charset)\n\n\treturn client\n}", "func NewClient(httpClient *http.Client) (*Client, error) {\n\tc := &Client{\n\t\thttpClient: httpClient,\n\t}\n\tu, err := url.Parse(APIEndpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.endpoint = u\n\treturn c, nil\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = &http.Client{}\n\t}\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\n\tc := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent}\n\tc.common.client = c\n\tc.Datasets = (*DatasetsService)(&c.common)\n\tc.Streams = (*StreamsService)(&c.common)\n\tc.Users = (*UsersService)(&c.common)\n\tc.Groups = (*GroupsService)(&c.common)\n\tc.Pages = (*PagesService)(&c.common)\n\tc.Logs = (*ActivityLogsService)(&c.common)\n\tc.Accounts = (*AccountsService)(&c.common)\n\n\treturn c\n}", "func NewClient(httpClient *http.Client) (*Client, error) {\n\tif httpClient == nil {\n\t\thttpClient = &http.Client{}\n\t}\n\tb, err := url.Parse(baseURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := &Client{client: httpClient, BaseURL: b}\n\tc.PriceHistory = &PriceHistoryService{client: c}\n\tc.Account = &AccountsService{client: c}\n\tc.MarketHours = &MarketHoursService{client: c}\n\tc.Quotes = &QuotesService{client: c}\n\tc.Instrument = &InstrumentService{client: c}\n\tc.Chains = &ChainsService{client: c}\n\tc.Mover = &MoverService{client: c}\n\tc.TransactionHistory = &TransactionHistoryService{client: c}\n\tc.User = &UserService{client: c}\n\tc.Watchlist = &WatchlistService{client: c}\n\n\treturn c, nil\n}", "func NewClient(config *config.Config, httpClient *http.Client) *Client {\n\treturn &Client{\n\t\tGetter: NewGetter(config, httpClient),\n\t}\n}", "func NewClient(httpClient *http.Client, endpoint, apiVersion string, tlsConfig *tls.Config) (*Client, error) {\n\tif endpoint == \"\" {\n\t\treturn nil, errors.New(\"endpoint missing for httpClient configuration\")\n\t}\n\tif apiVersion == \"\" {\n\t\tapiVersion = DefaultAPIVersion\n\t}\n\n\tif tlsConfig != nil {\n\t\ttlsConfig.Renegotiation = tls.RenegotiateFreelyAsClient\n\t\ttlsConfig.BuildNameToCertificate()\n\t\thttpClient.Transport = &http.Transport{TLSClientConfig: tlsConfig}\n\t}\n\n\treturn &Client{\n\t\tendpoint: endpoint,\n\t\tapiVersion: apiVersion,\n\t\thttpClient: httpClient,\n\t}, nil\n}", "func NewClient(creds Authenticator, apiBaseURL string, httpClient httpClient) *Client {\n\tif apiBaseURL == \"\" {\n\t\tapiBaseURL = fmt.Sprintf(\"https://%s.api.dragonchain.com\", creds.GetDragonchainID())\n\t}\n\tif httpClient == nil {\n\t\thttpClient = &http.Client{}\n\t}\n\tclient := &Client{\n\t\tcreds: creds,\n\t\tapiBaseURL: apiBaseURL,\n\t\thttpClient: httpClient,\n\t}\n\n\treturn client\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\n\tc := &Client{\n\t\tclient: httpClient,\n\t\tBaseURL: baseURL,\n\t}\n\n\tc.Draws = &drawsService{\n\t\tclient: c,\n\t\tEndpoint: defaultDrawsEndpoint,\n\t}\n\treturn c\n}", "func NewClient(httpClient *http.Client, c ClientConfig) Client {\n\treturn Client{\n\t\thttpClient: *httpClient,\n\t\tconfig: c,\n\t}\n}", "func NewClient(service, apiID, apiKey string, client *http.Client) *Client {\n\tc := &Client{\n\t\tservice: service,\n\t\tapiID: apiID,\n\t\tapiKey: apiKey,\n\t\tclient: client,\n\t}\n\tif c.client == nil {\n\t\tc.client = http.DefaultClient\n\t}\n\treturn c\n}", "func NewClient(token Token, httpClient *http.Client) *Client {\n\treturn newClient(defaultBaseURL, defaultDomain, token, httpClient)\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\tc := &Client{client: httpClient}\n\tc.common.client = c\n\tc.Search = (*SearchService)(&c.common)\n\tc.PlaceSuggest = (*PlaceSuggestService)(&c.common)\n\tc.SpaceDetail = (*SpaceDetailService)(&c.common)\n\tc.Reviews = (*ReviewsService)(&c.common)\n\n\treturn c\n}", "func NewClient(httpClient *http.Client, username string, password string, atlantisURL string) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\treturn &Client{\n\t\tHTTPClient: httpClient,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tBaseURL: BaseURL,\n\t\tAtlantisURL: atlantisURL,\n\t}\n}", "func NewClient(accessToken string, version string, httpClient *http.Client) *Client {\n\tclient := &Client{\n\t\tAccessToken: accessToken,\n\t\tsling: sling.New().Client(httpClient).Base(baseURL).\n\t\t\tSet(\"Content-Type\", contentTypeHeader(version)).\n\t\t\tSet(\"Authorization\", authorizationHeader(accessToken)),\n\t}\n\n\tclient.rl = rate.New(10, time.Second*1)\n\n\treturn client\n}", "func NewClient(st, usrname, passwd string, httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tstore = st\n\tusername = usrname\n\tpassword = passwd\n\n\tc := &Client{client: httpClient, UserAgent: userAgent}\n\tc.Config = &ConfigService{client: c}\n\tc.Products = &ProductService{client: c}\n\tc.NewProducts = &NewProductService{client: c}\n\tc.Taxes = &TaxService{client: c}\n\tc.Users = &UserService{client: c}\n\tc.Outlets = &OutletService{client: c}\n\tc.Registers = &RegisterService{client: c}\n\tc.Suppliers = &SupplierService{client: c}\n\tc.Customers = &CustomerService{client: c}\n\n\treturn c\n}", "func NewClient(baseURL string, apiKey string) Client {\n\treturn &httpClient{\n\t\tapiKey: apiKey,\n\t\tbaseURL: baseURL,\n\t\tinst: &http.Client{},\n\t}\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tclient := &Client{\n\t\tClient: *httpClient,\n\t\tUserAgent: \"Akamai-Open-Edgegrid-golang/\" + libraryVersion +\n\t\t\t\" golang/\" + strings.TrimPrefix(runtime.Version(), \"go\"),\n\t}\n\n\treturn client\n}", "func NewClient() *http.Client {\n\treturn &http.Client{}\n}", "func NewClient(httpClient *http.Client, opts ...Option) (*Client, error) {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\tc := &Client{\n\t\tclient: httpClient,\n\t\tbaseURL: baseURL,\n\t\tUserAgent: userAgent,\n\t}\n\n\tfor _, opt := range opts {\n\t\tif err := opt(&c.opts); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tc.common.client = c\n\tc.common.opts = c.opts\n\n\n\treturn c, nil\n}", "func NewClient(httpClient *http.Client, URL string, Token string, Source string, SourceType string, Index string) (*Client) {\n\t// Create a new client\n\tif httpClient == nil {\n\t\ttr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} // turn off certificate checking\n\t\thttpClient = &http.Client{Timeout: time.Second * 20, Transport: tr}\n\t}\n\n\tc := &Client{HTTPClient: httpClient, URL: URL, Token: Token, Source: Source, SourceType: SourceType, Index: Index}\n\n\treturn c\n}", "func NewClient(token string, client *http.Client) *Client {\n\tif client == nil {\n\t\thttpClient = &http.Client{Timeout: time.Second * 10}\n\t} else {\n\t\thttpClient = client\n\t}\n\treturn &Client{token}\n}", "func NewClient(client *http.Client) *Client {\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\t// Set a custom default transport instead of the default transport.\n\tif client.Transport == nil {\n\t\tclient.Transport = DefaultTransport\n\t}\n\n\treturn &Client{client}\n}", "func NewClient(httpClient *http.Client, address, token string, logger Logger) *Client {\n\treturn &Client{httpClient, address, token, logger}\n}", "func newClient(httpClient *http.Client) (c *Client) {\n\tc = &Client{httpClient: httpClient}\n\tc.service.client = c\n\tc.Auth = (*AuthService)(&c.service)\n\tc.Providers = (*ProvidersService)(&c.service)\n\tc.Projects = (*ProjectsService)(&c.service)\n\tc.Releases = (*ReleasesService)(&c.service)\n\tc.SlackChannels = (*SlackChannelsService)(&c.service)\n\tc.TelegramChats = (*TelegramChatsService)(&c.service)\n\tc.DiscordChannels = (*DiscordChannelsService)(&c.service)\n\tc.HangoutsChatWebhooks = (*HangoutsChatWebhooksService)(&c.service)\n\tc.MicrosoftTeamsWebhooks = (*MicrosoftTeamsWebhooksService)(&c.service)\n\tc.MattermostWebhooks = (*MattermostWebhooksService)(&c.service)\n\tc.RocketchatWebhooks = (*RocketchatWebhooksService)(&c.service)\n\tc.MatrixRooms = (*MatrixRoomsService)(&c.service)\n\tc.Webhooks = (*WebhooksService)(&c.service)\n\tc.Tags = (*TagsService)(&c.service)\n\treturn c\n}", "func NewClient(baseClient *httpclient.Client) *Client {\n\treturn &Client{\n\t\thttp: baseClient,\n\t}\n}", "func NewClient(httpClient *http.Client) *Client {\n\tu, _ := url.Parse(BaseURL)\n\treturn &Client{\n\t\tBaseURL: u,\n\t\tHTTPClient: httpClient,\n\t}\n}", "func NewClient(httpClient *http.Client, apikey string) *Service {\n\treturn &Service{\n\t\tsling: sling.New().Client(httpClient).Base(baseURL).Set(\"Authorization\", apikey),\n\t}\n}", "func newHTTPClient() *http.Client {\n\tclient := &http.Client{\n\t\tTimeout: defaultTimeout,\n\t}\n\treturn client\n}", "func NewClient(accessToken string, version string, httpClient *http.Client) *Client {\n\ttype Params struct {\n\t\tAccessToken string `url:\"access_token,omitempty\"`\n\t\tLocale string `url:\"locale,omitempty\"`\n\t}\n\n\tparams := &Params{AccessToken: accessToken, Locale: \"*\"}\n\n\tclient := &Client{\n\t\tAccessToken: accessToken,\n\t\tsling: sling.New().Client(httpClient).Base(baseURL).\n\t\t\tSet(\"Content-Type\", contentTypeHeader(version)).\n\t\t\tQueryStruct(params),\n\t}\n\n\tclient.rl = rate.New(10, time.Second*1)\n\n\treturn client\n}", "func (c *Client) httpClient() *http.Client { return http.DefaultClient }", "func NewClient(apiKey string) *Client {\n\treturn &Client{&http.Client{}, defaultURL, apiKey}\n}", "func NewClient(conf *Config, httpClient *http.Client) *Client {\n\ts := sling.New().Client(conf.HttpClient).Base(conf.BaseURL).SetBasicAuth(conf.Username, conf.Password)\n\treturn &Client{\n\t\tEnvironmentsService: NewEnvironmentsService(s),\n\t\tHostsService: NewHostsService(s),\n\t}\n}", "func NewClient() *Client {\n\n\treturn &Client{\n\t\thttpClient: http.DefaultClient,\n\t}\n}", "func NewClient(baseURL string, defaultHeaders map[string]string) *Client {\n\turl, _ := url.Parse(baseURL)\n\tif defaultHeaders == nil {\n\t\tdefaultHeaders = make(map[string]string)\n\t}\n\treturn &Client{httpClient: &http.Client{}, baseURL: url, defaultHeaders: defaultHeaders}\n}", "func NewHTTPClient(retries int) HTTPClient {\n\tif retries <= 0 {\n\t\tpanic(\"retries should be greater than 0\")\n\t}\n\treturn &httpClient{\n\t\tretries: retries,\n\t}\n}", "func NewClient(meta *metadata.Client, acc string) *http.Client {\n\treturn &http.Client{\n\t\tTransport: newRoundTripper(meta, acc),\n\t}\n}", "func NewClient(addr, password string, httpClient *http.Client) (*Client, error) {\n\tif httpClient == nil {\n\t\thttpClient = &http.Client{}\n\t}\n\n\tif httpClient.Jar == nil {\n\t\tjar, err := cookiejar.New(&cookiejar.Options{\n\t\t\tPublicSuffixList: publicsuffix.List,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thttpClient.Jar = jar\n\t}\n\n\tu, err := url.Parse(\"http://\" + addr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tclient := &Client{\n\t\tbaseURL: u,\n\t\tpassword: password,\n\t\tc: httpClient,\n\t}\n\n\treturn client, nil\n}", "func NewHttpClient() *http.Client {\n\tclient := &http.Client{\n\t\tTransport: constants.DefaultTransport,\n\t\tTimeout: constants.ClientTimeout,\n\t}\n\treturn client\n}", "func NewClient(httpClient *http.Client) (*Client, error) {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tc := &Client{}\n\n\tbaseURL, _ := url.Parse(DefaultBaseURL)\n\tvsspsBaseURL, _ := url.Parse(DefaultVsspsBaseURL)\n\tvsaexBaseURL, _ := url.Parse(DefaultVsaexBaseURL)\n\n\tc.client = httpClient\n\tc.BaseURL = *baseURL\n\tc.VsspsBaseURL = *vsspsBaseURL\n\tc.VsaexBaseURL = *vsaexBaseURL\n\tc.UserAgent = userAgent\n\n\tc.Boards = &BoardsService{client: c}\n\tc.BuildDefinitions = &BuildDefinitionsService{client: c}\n\tc.Builds = &BuildsService{client: c}\n\tc.DeliveryPlans = &DeliveryPlansService{client: c}\n\tc.Favourites = &FavouritesService{client: c}\n\tc.Git = &GitService{client: c}\n\tc.Iterations = &IterationsService{client: c}\n\tc.PolicyEvaluations = &PolicyEvaluationsService{client: c}\n\tc.PullRequests = &PullRequestsService{client: c}\n\tc.Teams = &TeamsService{client: c}\n\tc.Tests = &TestsService{client: c}\n\tc.Users = &UsersService{client: c}\n\tc.UserEntitlements = &UserEntitlementsService{client: c}\n\tc.WorkItems = &WorkItemsService{client: c}\n\n\treturn c, nil\n}", "func NewClient(h *http.Client) *Client {\n\treturn &Client{httpClient: *h}\n}", "func NewClient(options *ClientOptions, customHTTPClient *http.Client,\r\n\tcustomEnvironment string) (c *Client) {\r\n\r\n\t// Create a client\r\n\tc = new(Client)\r\n\r\n\t// Set options (either default or user modified)\r\n\tif options == nil {\r\n\t\toptions = DefaultClientOptions()\r\n\t}\r\n\r\n\t// Set the options\r\n\tc.Options = options\r\n\r\n\t// Set the environment\r\n\tvar found bool\r\n\tif c.Environment, found = environments[customEnvironment]; !found {\r\n\t\tc.Environment = environments[EnvironmentProduction]\r\n\t}\r\n\r\n\t// Is there a custom HTTP client to use?\r\n\tif customHTTPClient != nil {\r\n\t\tc.httpClient = customHTTPClient\r\n\t\treturn\r\n\t}\r\n\r\n\t// dial is the net dialer for clientDefaultTransport\r\n\tdial := &net.Dialer{KeepAlive: options.DialerKeepAlive, Timeout: options.DialerTimeout}\r\n\r\n\t// clientDefaultTransport is the default transport struct for the HTTP client\r\n\tclientDefaultTransport := &http.Transport{\r\n\t\tDialContext: dial.DialContext,\r\n\t\tExpectContinueTimeout: options.TransportExpectContinueTimeout,\r\n\t\tIdleConnTimeout: options.TransportIdleTimeout,\r\n\t\tMaxIdleConns: options.TransportMaxIdleConnections,\r\n\t\tProxy: http.ProxyFromEnvironment,\r\n\t\tTLSHandshakeTimeout: options.TransportTLSHandshakeTimeout,\r\n\t}\r\n\r\n\t// Determine the strategy for the http client\r\n\tif options.RequestRetryCount <= 0 {\r\n\r\n\t\t// no retry enabled\r\n\t\tc.httpClient = httpclient.NewClient(\r\n\t\t\thttpclient.WithHTTPTimeout(options.RequestTimeout),\r\n\t\t\thttpclient.WithHTTPClient(&http.Client{\r\n\t\t\t\tTransport: clientDefaultTransport,\r\n\t\t\t\tTimeout: options.RequestTimeout,\r\n\t\t\t}),\r\n\t\t)\r\n\t\treturn\r\n\t}\r\n\r\n\t// Retry enabled - create exponential back-off\r\n\tc.httpClient = httpclient.NewClient(\r\n\t\thttpclient.WithHTTPTimeout(options.RequestTimeout),\r\n\t\thttpclient.WithRetrier(heimdall.NewRetrier(\r\n\t\t\theimdall.NewExponentialBackoff(\r\n\t\t\t\toptions.BackOffInitialTimeout,\r\n\t\t\t\toptions.BackOffMaxTimeout,\r\n\t\t\t\toptions.BackOffExponentFactor,\r\n\t\t\t\toptions.BackOffMaximumJitterInterval,\r\n\t\t\t))),\r\n\t\thttpclient.WithRetryCount(options.RequestRetryCount),\r\n\t\thttpclient.WithHTTPClient(&http.Client{\r\n\t\t\tTransport: clientDefaultTransport,\r\n\t\t\tTimeout: options.RequestTimeout,\r\n\t\t}),\r\n\t)\r\n\r\n\treturn\r\n}", "func NewClient(url string) *Client {\n\treturn &Client{&http.Client{}, url}\n}", "func NewHTTPClient() *HTTPClient {\n\treturn &HTTPClient{\n\t\tClient: http.DefaultClient,\n\t\tCacheDir: viper.GetString(\"http_cache_dir\"),\n\t}\n}", "func NewClient(c *http.Client) *Client {\n\tapi := &Client{\n\t\tc: c,\n\t\terrorHandler: defaultErrorHandler,\n\t\theaders: make(map[string]string),\n\t}\n\treturn api\n}", "func NewClient(apiURL string, logger lager.Logger) Client {\n\treturn &client{\n\t\trequestGenerator: rata.NewRequestGenerator(apiURL, api.Routes),\n\t\tgivenHTTPClient: &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDisableKeepAlives: false,\n\t\t\t\tResponseHeaderTimeout: 20 * time.Second,\n\t\t\t\tMaxIdleConns: 200,\n\t\t\t},\n\t\t},\n\t\tlogger: logger,\n\t}\n}", "func NewHttpClient(url string) *HTTPClient {\n\treturn &HTTPClient{\n\t\tclient: &http.Client{},\n\t\turl: url,\n\t}\n}", "func NewHTTPClient(apiEndpoint string, pageSize int64, setAuth func(r *http.Request)) *APIClient {\n\treturn &APIClient{\n\t\tconn: connector.NewHTTPConnector(apiEndpoint, pageSize, setAuth),\n\t}\n}", "func NewClient(apiTokenID string, apiSecret string, logger *log.Logger) (*Client, error) {\n\tif len(apiTokenID) == 0 {\n\t\treturn nil, fmt.Errorf(\"apiTokenID is not set\")\n\t}\n\n\tif len(apiSecret) == 0 {\n\t\treturn nil, fmt.Errorf(\"apiSecret is not set\")\n\t}\n\n\tpublicUrl, err := url.ParseRequestURI(baseUrl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprivateUrl, err := url.ParseRequestURI(privateBaseUrl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar discardLogger = log.New(ioutil.Discard, \"\", log.LstdFlags)\n\tif logger == nil {\n\t\tlogger = discardLogger\n\t}\n\n\tclient := &http.Client{Timeout: time.Duration(10) * time.Second}\n\treturn &Client{URL: publicUrl, PrivateURL: privateUrl, ApiTokenID: apiTokenID, ApiSecret: apiSecret, HTTPClient: client, Logger: logger}, nil\n\n}", "func NewClient(c *http.Client, baseURL *url.URL) *client {\n\treturn &client{\n\t\tbaseURL: baseURL,\n\t\tclient: c,\n\t}\n}", "func New() (client *Client) {\n\thttpClient := &http.Client{}\n\treturn &Client{\n\t\thttpClient: httpClient,\n\t\tTimeout: 0,\n\t\tDisableKeepAlives: true,\n\t\tIdleConnectionTimeout: 0,\n\t\ttransport: &http.Transport{},\n\t\tMaxRetriesOnError: 1,\n\t}\n}", "func New(address, apiKey string, httpClient *http.Client) *Client {\n\tclient := Client{\n\t\tAddress: strings.TrimRight(address, \"/\"),\n\t\tAPIKey: apiKey,\n\t\thttpClient: httpClient,\n\t}\n\n\treturn &client\n}", "func NewHTTPClient(slog slog.Logger, filer sio.Filer) (clt Client, err error) {\n\thttpClt := &HTTPClient{logger: slog}\n\thttpClt.client = httpClt\n\thttpClt.filer = filer\n\treturn httpClt.client, nil\n}", "func NewClient(ctx context.Context, config *ClientConfig, httpClient auth.HTTPClient) Client {\n\tif httpClient != nil {\n\t\treturn &serviceManagerClient{Context: ctx, Config: config, HTTPClient: httpClient}\n\t}\n\tccConfig := &clientcredentials.Config{\n\t\tClientID: config.ClientID,\n\t\tClientSecret: config.ClientSecret,\n\t\tTokenURL: config.TokenURL + tokenURLSuffix,\n\t\tAuthStyle: oauth2.AuthStyleInParams,\n\t}\n\n\tauthClient := auth.NewAuthClient(ccConfig, config.SSLDisabled)\n\treturn &serviceManagerClient{Context: ctx, Config: config, HTTPClient: authClient}\n}", "func NewClient(cfg clients.Config, hc *http.Client) (Client, error) {\n\treturn clients.NewClient(cfg, hc)\n}", "func NewClient(cfg clients.Config, hc *http.Client) (Client, error) {\n\treturn clients.NewClient(cfg, hc)\n}", "func NewHTTPClient() *HTTPClient {\n\treturn &HTTPClient{\n\t\tfasthttpClient: fasthttp.Client{},\n\t}\n}", "func NewClient() *Client {\n\tclient := &Client{\n\t\turl: baseURL,\n\t\thttpClient: &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tMaxConnsPerHost: maxConnsPerHost,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn client\n}", "func NewClient(url string) *Client {\n\treturn &Client{\n\t\thttpClient: &http.Client{Timeout: time.Minute},\n\t\turl: url,\n\t\tminVersion: minVersion,\n\t}\n}", "func NewHttpClient() *Client {\n\treturn &Client{\n\t\tclient: &http.Client{Timeout: 20 * time.Second},\n\t}\n}", "func NewClient() *Client {\n\treturn &Client{\n\t\tClient: http.DefaultClient,\n\t}\n}", "func NewClient() *http.Client {\n\treturn &http.Client{\n\t\tTimeout: 10 * time.Second,\n\t}\n}", "func NewHTTPClient(url string, backend Backend) (*HTTPClient, error) {\n b := backend\n if b == nil {\n b = newDefaultBackend()\n }\n return &HTTPClient{url: url, backend: b}, nil\n}", "func NewClient(opts ...ClientOps) ClientInterface {\n\n\t// Create a client with defaults\n\tc := &Client{\n\t\toptions: &ClientOptions{\n\t\t\thttpOptions: DefaultHTTPOptions(),\n\t\t\tsearchOptions: DefaultSearchOptions(),\n\t\t\tuserAgent: defaultUserAgent,\n\t\t},\n\t}\n\n\t// Overwrite defaults with any set by user\n\tfor _, opt := range opts {\n\t\topt(c.options)\n\t}\n\n\t// Set a default http client if one does not exist\n\tif c.options.httpClient == nil {\n\t\tc.options.httpClient = createDefaultHTTPClient(c)\n\t}\n\n\treturn c\n}", "func NewClient(client *api.HTTPClient) *Client {\n\treturn &Client{\n\t\tclient,\n\t}\n}", "func NewClient() *Client {\n baseURL, _ := url.Parse(defaultBaseURL)\n return &Client{client: http.DefaultClient, BaseURL: baseURL, UserAgent: userAgent}\n}", "func NewClient(endpoint string, options ...Option) *Client {\n\tc := &Client{endpoint: endpoint}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\tif c.httpClient == nil {\n\t\tc.httpClient = http.DefaultClient\n\t}\n\n\treturn c\n}", "func NewClient(baseURL, apiKey string) *Client {\n\treturn &Client{baseURL: baseURL, apiKey: apiKey, httpClient: http.Client{}}\n}", "func NewClient(url string) *Client {\n\ttr := http.DefaultTransport\n\thttp := &http.Client{Transport: tr}\n\tclient := &Client{http: http, url: url}\n\treturn client\n}", "func NewRESTClient(httpClient *http.Client, cfg Config) *RESTClient {\n\tif httpClient == nil {\n\t\t// This is a no bueno and for demonstrative purposes only!\n\t\t// tr := &http.Transport{\n\t\t// \tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t// }\n\t\thttpClient = http.DefaultClient\n\t}\n\tif cfg.Addr == \"\" {\n\t\tcfg.Addr = \"https://icanhazdadjoke.com/\"\n\t}\n\tc := &RESTClient{\n\t\tClient: httpClient,\n\t\tConfig: cfg,\n\t}\n\treturn c\n}", "func NewClient(apiVersion ApiVersion, tenantId string) Client {\n\treturn Client{\n\t\tEndpoint: environments.AadGraphGlobal.Endpoint,\n\t\tApiVersion: apiVersion,\n\t\tTenantId: tenantId,\n\t\thttpClient: http.DefaultClient,\n\t}\n}", "func NewClient() Client {\n\treturn &client{\n\t\thclient: http.DefaultClient,\n\t}\n}", "func NewHTTPClient(timeout time.Duration) *http.Client {\n\treturn &http.Client{\n\t\tTimeout: timeout,\n\t}\n}", "func NewClient(endpoint string) *Client {\n\tc := &Client{\n\t\tendpoint: endpoint,\n\t}\n\n\tif c.httpClient == nil {\n\t\tc.httpClient = http.DefaultClient\n\t}\n\treturn c\n}", "func NewClient(opts ...ClientOption) *Client {\n\ttr := http.DefaultTransport\n\tfor _, opt := range opts {\n\t\ttr = opt(tr)\n\t}\n\n\th := &http.Client{Transport: tr}\n\tclient := &Client{http: h}\n\n\treturn client\n}", "func NewHTTPClient() *http.Client {\n\n\ttr := &http.Transport{\n\t\t//TLSClientConfig: &tls.Config{\n\t\t//\tInsecureSkipVerify: conf.InsecureSkipVerify,\n\t\t//},\n\t\tMaxIdleConnsPerHost: DefaultMaxIdleConnsPerHost,\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout: DefaultTimeout,\n\t\t\tKeepAlive: DefaultKeepAlive,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: DefaultTimeout,\n\t}\n\n\treturn &http.Client{\n\t\tTimeout: DefaultTimeout,\n\t\tTransport: tr,\n\t}\n}", "func NewClient(c *http.Client, api, key, secret string) *Client {\n\treturn &Client{\n\t\tclient: c,\n\t\tapi: api,\n\t\tapiKey: key,\n\t\tsecret: secret,\n\t}\n}", "func NewClient(apiURL, apiName, apiKey string) *Client {\n\treturn &Client{\n\t\tapiName: apiName,\n\t\tapiKey: apiKey,\n\t\tapiURL: apiURL,\n\t\tclient: &http.Client{},\n\t}\n}", "func NewClient() *http.Client {\n\treturn &http.Client{\n\t\tTransport: roundTripper,\n\t\tTimeout: TCPConnectionTimeout,\n\t}\n}", "func NewHTTPClient(uri string) HTTPClient {\n\treturn HTTPClient{\n\t\tBackendURI: uri,\n\t\tclient: &http.Client{},\n\t}\n}", "func NewClient() *Client {\n\treturn &Client{\n\t\tHTTPClient: http.DefaultClient,\n\t\tBaseURL: BaseURL,\n\t}\n}", "func NewClient(httpClient *http.Client, token string) Client {\n\turl, err := url.Parse(graphqlURL)\n\tif err != nil {\n\t\t// Beacause graphqlURL is constant, but parse error occured\n\t\tpanic(err)\n\t}\n\n\tapiClient, err := api.NewClient(httpClient, url, token)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &clientImp{apiClient: apiClient}\n}", "func NewClient(serverAddress string, cli *http.Client) *Client {\n\tif cli == nil {\n\t\tcli = http.DefaultClient\n\t}\n\treturn &Client{\"http://\" + serverAddress + \"/api/v1/\", cli}\n}" ]
[ "0.8190736", "0.819041", "0.8155558", "0.8001566", "0.7915223", "0.7910204", "0.78870803", "0.7877559", "0.78694683", "0.78224707", "0.7799551", "0.77663815", "0.7759795", "0.7755385", "0.77519286", "0.7749985", "0.77259535", "0.7722583", "0.7718366", "0.7712413", "0.77112836", "0.76657665", "0.76625204", "0.7595268", "0.7589454", "0.75343627", "0.75229216", "0.74600303", "0.7446982", "0.7444614", "0.74390334", "0.7435446", "0.7424914", "0.7422119", "0.73626053", "0.7353459", "0.73456264", "0.7334972", "0.73081917", "0.72972846", "0.72827464", "0.72767913", "0.72725344", "0.7271735", "0.727033", "0.72467977", "0.7243654", "0.7214498", "0.7213255", "0.7210005", "0.7209543", "0.7198928", "0.71966857", "0.7196588", "0.7196036", "0.7188783", "0.7174373", "0.7168706", "0.7164066", "0.71449643", "0.7138655", "0.713051", "0.71220946", "0.711643", "0.7107468", "0.7095074", "0.7092415", "0.70739174", "0.7070608", "0.7062855", "0.7061255", "0.7059426", "0.7059426", "0.70555127", "0.70483226", "0.70179343", "0.70165163", "0.70146155", "0.69858474", "0.69844186", "0.6983234", "0.6981856", "0.6976982", "0.69719964", "0.69681317", "0.6959527", "0.6955972", "0.69536936", "0.69536835", "0.69459957", "0.6942849", "0.69422686", "0.6941578", "0.69358194", "0.692585", "0.6925194", "0.69146883", "0.6906941", "0.6899362", "0.6897632" ]
0.7719205
18
NewDir creates a new Interface that converts the return value of a Directory's Readdir method into 9P Stat structures.
func NewDir(dir Directory, abspath string, pool *qidpool.Pool) Interface { return &dirReader{ Directory: dir, pool: pool, path: abspath, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newDir(name string, attr plugin.EntryAttributes, impl Interface, path string) *dir {\n\tvd := &dir{\n\t\tEntryBase: plugin.NewEntry(name),\n\t}\n\tvd.impl = impl\n\tvd.path = path\n\tvd.SetAttributes(attr)\n\treturn vd\n}", "func newDirectory(root string, maxDepth int) *Directory {\n\td, err := os.Lstat(root);\n\tif err != nil || !isPkgDir(d) {\n\t\treturn nil\n\t}\n\treturn newDirTree(root, d.Name, 0, maxDepth);\n}", "func newDirFileInfo(name string) os.FileInfo {\n\treturn &bindataFileInfo{\n\t\tname: name,\n\t\tsize: 0,\n\t\tmode: os.FileMode(2147484068), // equal os.FileMode(0644)|os.ModeDir\n\t\tmodTime: time.Time{}}\n}", "func NewDirTracker(dir string, newEntry func(string) (DirectoryTrackerInterface, error)) *DirTracker {\n\tnumOutsanding := NumTrackerOutstanding // FIXME expose this\n\tvar dt DirTracker\n\tdt.dm = make(map[string]DirectoryTrackerInterface)\n\tdt.newEntry = newEntry\n\tdt.tokenChan = makeTokenChan(numOutsanding)\n\tdt.wg = new(sync.WaitGroup)\n\tdt.errChan = make(chan error)\n\tdt.wg.Add(1)\n\tgo dt.populateDircount(dir)\n\tgo func() {\n\t\terr := filepath.WalkDir(dir, dt.directoryWalker)\n\t\tif err != nil {\n\t\t\tdt.errChan <- err\n\t\t}\n\t\tfor _, val := range dt.dm {\n\t\t\tval.Close()\n\t\t}\n\t\tdt.wg.Wait()\n\t\tdt.finished.Set()\n\t\tclose(dt.errChan)\n\t\tclose(dt.tokenChan)\n\t}()\n\n\treturn &dt\n}", "func (f *Fs) newDir(dir fs.Directory) fs.Directory {\n\treturn dir // We're using the same dir\n}", "func NewDir(dir string) http.Handler {\n\treturn New(Config{Dir: dir})\n}", "func New(cacheFile string, typeFilter string) (*Directory, error) {\n\txmlData := []byte{}\n\tif _, err := os.Stat(cacheFile); err == nil {\n\t\txmlData, _ = ioutil.ReadFile(cacheFile)\n\t}\n\n\tif len(xmlData) == 0 {\n\t\treq, _ := http.NewRequest(\"GET\", \"http://dir.xiph.org/yp.xml\", nil)\n\t\tres, err := http.DefaultClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer res.Body.Close()\n\t\txmlData, err = ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\ttmp := Directory{}\n\terr := xml.Unmarshal(xmlData, &tmp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tentries := []Entry{}\n\tif typeFilter == \"\" {\n\t\tentries = tmp.Entries\n\t} else {\n\t\tfor _, e := range tmp.Entries {\n\t\t\tif e.ServerType != typeFilter {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tentries = append(entries, e)\n\t\t}\n\t}\n\n\treturn &Directory{\n\t\tcacheFile: cacheFile,\n\t\tEntries: entries,\n\t}, nil\n}", "func NewDirectory() *Directory {\n\treturn &Directory{\n\t\tentry: entry{\n\t\t\tname: \"<root>\",\n\t\t\tmode: 0o777 | os.ModeDir, //nolint:gomnd\n\t\t\tmodTime: DefaultModTime,\n\t\t},\n\t}\n}", "func newDirectory(dns, prefix string) *directory {\n\treturn &directory{prefix: prefix, dns: dns}\n}", "func Directory(dir string, permissions os.FileMode, opts *bolt.Options) store.Factory {\n\treturn &directory{\n\t\tdir: dir,\n\t\tpermissions: permissions,\n\t\topts: opts,\n\t}\n}", "func NewDirectory(ctx context.Context, name string, node ipld.Node, parent parent, dserv ipld.DAGService) (*Directory, error) {\n\tdb, err := uio.NewDirectoryFromNode(dserv, node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Directory{\n\t\tinode: inode{\n\t\t\tname: name,\n\t\t\tparent: parent,\n\t\t\tdagService: dserv,\n\t\t},\n\t\tctx: ctx,\n\t\tunixfsDir: db,\n\t\tentriesCache: make(map[string]FSNode),\n\t\tmodTime: time.Now(),\n\t}, nil\n}", "func NewSearchDir() *SearchDir {\n newObj := SearchDir {\n DoneChan: make(chan bool),\n ErrChan: make(chan string),\n FileChan: make(chan string),\n }\n\n return &newObj\n}", "func (l *CPIO9PFID) Readdir(offset uint64, count uint32) (p9.Dirents, error) {\n\tqid, _, err := l.info()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlist, err := l.readdir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif offset > uint64(len(list)) {\n\t\treturn nil, io.EOF\n\t}\n\tverbose(\"cpio:readdir list %v\", list)\n\tvar dirents p9.Dirents\n\tdirents = append(dirents, p9.Dirent{\n\t\tQID: qid,\n\t\tType: qid.Type,\n\t\tName: \".\",\n\t\tOffset: l.path,\n\t})\n\tverbose(\"cpio:add path %d '.'\", l.path)\n\t//log.Printf(\"cpio:readdir %q returns %d entries start at offset %d\", l.path, len(fi), offset)\n\tfor _, i := range list[offset:] {\n\t\tentry := CPIO9PFID{path: i, fs: l.fs}\n\t\tqid, _, err := entry.info()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tr, err := entry.rec()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tverbose(\"cpio:add path %d %q\", i, filepath.Base(r.Info.Name))\n\t\tdirents = append(dirents, p9.Dirent{\n\t\t\tQID: qid,\n\t\t\tType: qid.Type,\n\t\t\tName: filepath.Base(r.Info.Name),\n\t\t\tOffset: i,\n\t\t})\n\t}\n\n\tverbose(\"cpio:readdir:return %v, nil\", dirents)\n\treturn dirents, nil\n}", "func (fn *randomTypeTest) Readdir(ctx context.Context) (DirStream, syscall.Errno) {\n\tvar entries []fuse.DirEntry\n\n\tfor i := 0; i < 100; i++ {\n\t\tentries = append(entries, fuse.DirEntry{\n\t\t\tName: fmt.Sprintf(\"%d\", i),\n\t\t\tMode: fuse.S_IFDIR,\n\t\t})\n\t}\n\treturn NewListDirStream(entries), syscall.F_OK\n}", "func NewDirectoryIndex(rdr io.Reader) (DirIndex, error) {\n\tvar index DirIndex\n\terr := binary.Read(rdr, binary.LittleEndian, &index.DirIndexInit)\n\tif err != nil {\n\t\treturn index, err\n\t}\n\ttmp := make([]byte, index.NameSize+1, index.NameSize+1)\n\terr = binary.Read(rdr, binary.LittleEndian, &tmp)\n\tif err != nil {\n\t\treturn index, err\n\t}\n\tindex.Name = string(tmp)\n\treturn index, nil\n}", "func NewDirectory()(*Directory) {\n m := &Directory{\n Entity: *NewEntity(),\n }\n return m\n}", "func (w *wrapper) Readdir(path string,\n\tfill func(name string, stat *fuse.Stat_t, ofst int64) bool,\n\tofst int64,\n\tfh uint64) int {\n\tif dfs, ok := w.underlying.(billy.Dir); ok {\n\t\tentries, err := dfs.ReadDir(path)\n\t\tif err != nil {\n\t\t\treturn convertError(err)\n\t\t}\n\t\t// TODO(sjors): This sort.Strings is a workaround for an issue\n\t\t// reproducible in at least two implementations of FUSE on macOS.\n\t\t// Perhaps there is an issue in macFUSE somewhere. See e.g.\n\t\t// https://github.com/billziss-gh/cgofuse/issues/57\n\t\tsort.Slice(entries, func(i, j int) bool {\n\t\t\treturn entries[i].Name() < entries[j].Name()\n\t\t})\n\t\tfor _, e := range entries {\n\t\t\tst := new(fuse.Stat_t)\n\t\t\tfileInfoToStat(e, st)\n\t\t\tfill(e.Name(), st, 0)\n\t\t}\n\t\treturn 0\n\t}\n\treturn -fuse.ENOSYS\n}", "func newDirHandle(d *Dir) *DirHandle {\n\treturn &DirHandle{\n\t\td: d,\n\t}\n}", "func (*FileSystemBase) Readdir(path string,\n\tfill func(name string, stat *Stat_t, ofst int64) bool,\n\tofst int64,\n\tfh uint64) int {\n\treturn -ENOSYS\n}", "func Dir(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"dir\", Attributes: attrs, Children: children}\n}", "func (iio *IO) Readdir(inode *ext.Inode) ([]*DirectoryEntry, error) {\r\n\r\n\trdr, err := iio.InodeReader(inode)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tdirent := new(Dirent)\r\n\tlist := make([]*DirectoryEntry, 0)\r\n\r\n\tfor {\r\n\t\terr = binary.Read(rdr, binary.LittleEndian, dirent)\r\n\t\tif err == io.EOF {\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\r\n\t\tl := int(dirent.Size)\r\n\t\tbuf := new(bytes.Buffer)\r\n\t\t_, err = io.CopyN(buf, rdr, int64(l-8))\r\n\t\tif err == io.EOF {\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\r\n\t\tname := cstring(buf.Bytes()[:dirent.NameLen])\r\n\r\n\t\tif name == \"\" || dirent.Inode == 0 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\tlist = append(list, &DirectoryEntry{\r\n\t\t\tName: name,\r\n\t\t\tType: dirent.Type,\r\n\t\t\tInode: int(dirent.Inode),\r\n\t\t})\r\n\t}\r\n\r\n\treturn list, nil\r\n\r\n}", "func newTestFileSystemWithDir(name string) (*DirNode, *FileSystem, error) {\n\tdir := testDir(name)\n\tfs := newTestFileSystem(dir)\n\tsp := modules.RandomSiaPath()\n\tif err := fs.NewSiaDir(sp, modules.DefaultDirPerm); err != nil {\n\t\tpanic(err) // Reflect behavior of newTestFileSystemWithFile.\n\t}\n\tsd, err := fs.OpenSiaDir(sp)\n\treturn sd, fs, err\n}", "func (dTreeOp DirTreeOp) New() DirTreeOp {\n newDTreeOp := DirTreeOp{}\n newDTreeOp.ErrReturns = make([]error, 0, 100)\n return newDTreeOp\n}", "func NewDirectoryLite(file RAS,segsize int) *Directory{\n\td := new(Directory)\n\td.File = file\n\td.Buf = &dskimg.FixedIO{make([]byte,segsize),0}\n\td.Segsz = segsize\n\treturn d\n}", "func NewDirectory(root string) Directory {\n\treturn Directory{root: root, m: &sync.RWMutex{}}\n}", "func Dir(useLocal bool, name string) http.FileSystem {\n\tif useLocal {\n\t\treturn _escDirectory{fs: _escLocal, name: name}\n\t}\n\treturn _escDirectory{fs: _escStatic, name: name}\n}", "func Dir(useLocal bool, name string) http.FileSystem {\n\tif useLocal {\n\t\treturn _escDirectory{fs: _escLocal, name: name}\n\t}\n\treturn _escDirectory{fs: _escStatic, name: name}\n}", "func Dir(useLocal bool, name string) http.FileSystem {\n\tif useLocal {\n\t\treturn _escDirectory{fs: _escLocal, name: name}\n\t}\n\treturn _escDirectory{fs: _escStatic, name: name}\n}", "func Dir(useLocal bool, name string) http.FileSystem {\n\tif useLocal {\n\t\treturn _escDirectory{fs: _escLocal, name: name}\n\t}\n\treturn _escDirectory{fs: _escStatic, name: name}\n}", "func Dir(useLocal bool, name string) http.FileSystem {\n\tif useLocal {\n\t\treturn _escDirectory{fs: _escLocal, name: name}\n\t}\n\treturn _escDirectory{fs: _escStatic, name: name}\n}", "func (fsys *FS) Readdir(dirPath string,\n\tfill func(name string, stat *fuse.Stat_t, ofst int64) bool,\n\tofst int64,\n\tfh uint64) (errc int) {\n\titemsRead := -1\n\tdefer fs.Trace(dirPath, \"ofst=%d, fh=0x%X\", ofst, fh)(\"items=%d, errc=%d\", &itemsRead, &errc)\n\n\tnode, errc := fsys.openDirs.Get(fh)\n\tif errc != 0 {\n\t\treturn errc\n\t}\n\n\tdir, ok := node.(*mountlib.Dir)\n\tif !ok {\n\t\treturn -fuse.ENOTDIR\n\t}\n\n\titems, err := dir.ReadDirAll()\n\tif err != nil {\n\t\treturn translateError(err)\n\t}\n\n\t// Optionally, create a struct stat that describes the file as\n\t// for getattr (but FUSE only looks at st_ino and the\n\t// file-type bits of st_mode).\n\t//\n\t// FIXME If you call host.SetCapReaddirPlus() then WinFsp will\n\t// use the full stat information - a Useful optimization on\n\t// Windows.\n\t//\n\t// NB we are using the first mode for readdir: The readdir\n\t// implementation ignores the offset parameter, and passes\n\t// zero to the filler function's offset. The filler function\n\t// will not return '1' (unless an error happens), so the whole\n\t// directory is read in a single readdir operation.\n\tfill(\".\", nil, 0)\n\tfill(\"..\", nil, 0)\n\tfor _, item := range items {\n\t\tname := path.Base(item.Obj.Remote())\n\t\tfill(name, nil, 0)\n\t}\n\titemsRead = len(items)\n\treturn 0\n}", "func (fs FS) NewStat() (Stat, error) {\n\treturn fs.Stat()\n}", "func newDir(t *testing.T) (string, func()) {\n\tdir, err := os.MkdirTemp(\"\", \"lxd-db-node-test-\")\n\trequire.NoError(t, err)\n\n\tcleanup := func() {\n\t\trequire.NoError(t, os.RemoveAll(dir))\n\t}\n\n\treturn dir, cleanup\n}", "func Dir(index, root string, listDirectory bool) http.FileSystem {\n\tfs := http.Dir(root)\n\tif listDirectory {\n\t\treturn fs\n\t}\n\treturn &onlyFilesFS{fs, index}\n}", "func NewDirReader(dir string, mode DirMode) (*DirReader, error) {\n\tf, err := os.OpenFile(dir, os.O_RDONLY, os.ModePerm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tinfo, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !info.IsDir() {\n\t\treturn nil, ErrNotDirectory\n\t}\n\n\tr := &DirReader{\n\t\tdirs: make([]FileInfo, 1, 8),\n\t\tmode: mode,\n\t}\n\tr.dirs[0] = FileInfo{dir, info}\n\treturn r, nil\n}", "func newTestDir(rootDir string) (*SiaDir, error) {\n\trootPath, err := newSiaDirTestDir(rootDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\twal, _ := newTestWAL()\n\treturn New(modules.RandomSiaPath().SiaDirSysPath(rootPath), rootPath, modules.DefaultDirPerm, wal)\n}", "func NewDirInode(\n\tid fuseops.InodeID,\n\tname Name,\n\tattrs fuseops.InodeAttributes,\n\timplicitDirs bool,\n\ttypeCacheTTL time.Duration,\n\tbucket gcsx.SyncerBucket,\n\tmtimeClock timeutil.Clock,\n\tcacheClock timeutil.Clock) (d DirInode) {\n\n\tif !name.IsDir() {\n\t\tpanic(fmt.Sprintf(\"Unexpected name: %s\", name))\n\t}\n\n\t// Set up the struct.\n\tconst typeCacheCapacity = 1 << 16\n\ttyped := &dirInode{\n\t\tbucket: bucket,\n\t\tmtimeClock: mtimeClock,\n\t\tcacheClock: cacheClock,\n\t\tid: id,\n\t\timplicitDirs: implicitDirs,\n\t\tname: name,\n\t\tattrs: attrs,\n\t\tcache: newTypeCache(typeCacheCapacity/2, typeCacheTTL),\n\t}\n\n\ttyped.lc.Init(id)\n\n\t// Set up invariant checking.\n\ttyped.mu = syncutil.NewInvariantMutex(typed.checkInvariants)\n\n\td = typed\n\treturn\n}", "func (ReadOnlyDirectory) VirtualMkdir(name path.Component, requested AttributesMask, out *Attributes) (Directory, ChangeInfo, Status) {\n\treturn nil, ChangeInfo{}, StatusErrROFS\n}", "func (m *wasiSnapshotPreview1Impl) fdReaddir(pfd wasiFd, pbuf pointer, pbufLen wasiSize, pcookie wasiDircookie) (rv wasiSize, err wasiErrno) {\n\tf, err := m.files.acquireFile(pfd, wasiRightsFdReaddir)\n\tif err != wasiErrnoSuccess {\n\t\treturn 0, err\n\t}\n\n\tentries, err := func() ([]os.DirEntry, wasiErrno) {\n\t\tdefer m.files.releaseFile(pfd, f)\n\n\t\tdir, ok := f.f.(Directory)\n\t\tif !ok {\n\t\t\treturn nil, wasiErrnoNotdir\n\t\t}\n\n\t\tif f.entries == nil {\n\t\t\tentries, ferr := dir.ReadDir(0)\n\t\t\tif ferr != nil {\n\t\t\t\treturn nil, fileErrno(ferr)\n\t\t\t}\n\t\t\tf.entries = entries\n\t\t}\n\t\tentries := f.entries\n\t\tswitch {\n\t\tcase pcookie > uint64(len(entries)):\n\t\t\treturn nil, wasiErrnoInval\n\t\tcase pcookie == uint64(len(entries)):\n\t\t\tf.entries = nil\n\t\t\treturn nil, wasiErrnoSuccess\n\t\tdefault:\n\t\t\treturn entries[int(pcookie):], wasiErrnoSuccess\n\t\t}\n\t}()\n\tif err != wasiErrnoSuccess {\n\t\treturn 0, err\n\t}\n\n\tdest := m.slice(pbuf, pbufLen)\n\n\tvar dirent wasiDirent\n\tdirentSize, _ := dirent.layout()\n\n\twritten := wasiSize(0)\n\tbuf := exec.NewMemory(1, 1)\n\tfor i, entry := range entries[int(pcookie):] {\n\t\tname := entry.Name()\n\t\tbytes := buf.Bytes()\n\t\tentrySize := direntSize + uint32(len(name))\n\t\tif entrySize > uint32(len(bytes)) {\n\t\t\treturn written, wasiErrnoNobufs\n\t\t}\n\n\t\tinfo, ferr := entry.Info()\n\t\tif ferr != nil {\n\t\t\treturn written, fileErrno(ferr)\n\t\t}\n\t\tstat := fileStat(info)\n\n\t\tdirent.dIno = stat.Inode\n\t\tdirent.dNamlen = wasiDirnamlen(len(name))\n\t\tdirent.dNext = pcookie + uint64(i)\n\t\tdirent.dType = filetype(stat.Mode)\n\n\t\tdirent.store(&buf, 0, 0)\n\t\tcopy(bytes[int(direntSize):], name)\n\n\t\tn := copy(dest, bytes[:int(entrySize)])\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\t\twritten += wasiSize(n)\n\t\tdest = dest[n:]\n\t}\n\treturn written, wasiErrnoSuccess\n}", "func newFileInfoGroup(dir string) (*fileInfoGroup, error) {\n\tfsi, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor k := len(fsi) - 1; k >= 0; k-- {\n\t\t// remove directories, and files without the correct extension\n\t\tif fsi[k].IsDir() || !strings.HasSuffix(fsi[k].Name(), \".gz\") {\n\t\t\tfsi = append(fsi[:k], fsi[k+1:]...)\n\t\t}\n\t}\n\n\treturn &fileInfoGroup{dir: dir, fsi: fsi}, nil\n}", "func (dr *DirReader) Readdir(n int) (entries []DirectoryEntry, err error) {\n\tsts, err := dr.StaticSet()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"schema/filereader: can't get StaticSet: %v\\n\", err)\n\t}\n\tup := dr.current + n\n\tif n <= 0 {\n\t\tdr.current = 0\n\t\tup = len(sts)\n\t} else {\n\t\tif n > (len(sts) - dr.current) {\n\t\t\terr = io.EOF\n\t\t\tup = len(sts)\n\t\t}\n\t}\n\tfor _, entryBref := range sts[dr.current:up] {\n\t\tentry, err := NewDirectoryEntryFromBlobRef(dr.fetcher, entryBref)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"schema/filereader: can't create dirEntry: %v\\n\", err)\n\t\t}\n\t\tentries = append(entries, entry)\n\t}\n\treturn entries, err\n}", "func NewDirectory(name string, parent *Directory) *Directory {\n\treturn &Directory{\n\t\tname: name,\n\t\tparent: parent,\n\t\tready: make(chan struct{}),\n\t}\n}", "func makeDirDriver(path string) volume.Driver {\n\tdrv := new(DirDriver)\n\tdrv.volumesPath = path\n\tdrv.volumes = make(map[string]*dirVol)\n\n\treturn drv\n}", "func newConfigDirectory(baseDirectory string) *configDirectory {\n\treturn &configDirectory{nil, baseDirectory, make([]string, 0)}\n}", "func NewVDir(moddedPath, realPath, abs string, root bool) *VDir {\n\tvf := VFile{\n\t\tBaseDir: abs,\n\t\tDir: moddedPath,\n\t\tShadowDir: realPath,\n\t\tFileName: filepath.Base(moddedPath),\n\t\tMod: time.Now(),\n\t}\n\n\treturn &VDir{\n\t\tVFile: &vf,\n\t\tFiles: NewFileCollector(),\n\t\tSubs: NewDeferDirCollector(),\n\t\troot: root,\n\t}\n}", "func (h *Header) Directory(r io.ReadSeeker) (Directory, error) {\n\tif _, err := r.Seek(int64(h.FatOffset), io.SeekStart); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to seek to directory: %w\", err)\n\t}\n\n\tout := make(Directory, 0, h.NumFiles)\n\tfor i := int32(0); i < h.NumFiles; i++ {\n\t\tentry, err := getEntry(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read directory entry: %w\", err)\n\t\t}\n\t\tout = append(out, entry)\n\t}\n\n\treturn out, nil\n}", "func NewDirectory(name, id string, children []Resource) *Directory {\n\treturn &Directory{\n\t\tname: name,\n\t\tid: id,\n\t\tchildren: children,\n\t}\n}", "func FileReaddir(f *os.File, n int) ([]os.FileInfo, error)", "func (*File) ReadDir(args rpc.Args, result *[]FileInfo) error {\n\tpath, ok := args.Args.(string)\n\tif !ok {\n\t\treturn errors.New(\"args should is a string\")\n\t}\n\tr := make([]FileInfo, 0)\n\tif path == \"/\" || path == \"\\\\\" {\n\t\tfor k,v := range share.GetDirs() {\n\t\t\tf, err := os.Stat(filepath.Join(v, k))\n\t\t\tif err != nil {\n\t\t\t\tif err == os.ErrNotExist {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tt := FileInfo{\n\t\t\t\tName: f.Name(),\n\t\t\t\tIsDir: f.IsDir(),\n\t\t\t\tSize:f.Size(),\n\t\t\t\tMTime:f.ModTime(),\n\t\t\t}\n\t\t\tr = append(r, t)\n\t\t}\n\t\t*result = r\n\t\treturn nil\n\t}\n\n\tf, err := os.Open(share.GetAbs(path))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tfileInfo, err := f.Readdir(-1)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, st := range fileInfo {\n\t\tif st.Name() == \".git\" {\n\t\t\tcontinue\n\t\t}\n\t\tt := FileInfo{\n\t\t\tName: st.Name(),\n\t\t\tSize: st.Size(),\n\t\t\tMode: st.Mode(),\n\t\t\tMTime: st.ModTime(),\n\t\t\tIsDir: st.IsDir(),\n\t\t}\n\t\tr = append(r, t)\n\t}\n\t*result = r\n\treturn nil\n}", "func (vd *VDir) Readdir(count int) ([]os.FileInfo, error) {\n\tvar total = count\n\tvar files []os.FileInfo\n\n\tvd.EachFile(func(v *VFile, _ string, stop func()) {\n\t\tif total <= 0 {\n\t\t\tstop()\n\t\t\treturn\n\t\t}\n\n\t\tfiles = append(files, v)\n\t\ttotal--\n\t})\n\n\treturn files, nil\n}", "func Dir(useLocal bool, name string) http.FileSystem {\n\tif useLocal {\n\t\treturn _escDir{fs: _escLocal, name: name}\n\t}\n\treturn _escDir{fs: _escStatic, name: name}\n}", "func Dir(useLocal bool, name string) http.FileSystem {\n\tif useLocal {\n\t\treturn _escDir{fs: _escLocal, name: name}\n\t}\n\treturn _escDir{fs: _escStatic, name: name}\n}", "func Dir(useLocal bool, name string) http.FileSystem {\n\tif useLocal {\n\t\treturn _escDir{fs: _escLocal, name: name}\n\t}\n\treturn _escDir{fs: _escStatic, name: name}\n}", "func New(dir string, maxSizeBytes int64) cache.Cache {\n\t// Create the directory structure.\n\thexLetters := []byte(\"0123456789abcdef\")\n\tfor _, c1 := range hexLetters {\n\t\tfor _, c2 := range hexLetters {\n\t\t\tsubDir := string(c1) + string(c2)\n\t\t\terr := os.MkdirAll(filepath.Join(dir, cache.CAS.String(), subDir), os.FileMode(0744))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\terr = os.MkdirAll(filepath.Join(dir, cache.AC.String(), subDir), os.FileMode(0744))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// The eviction callback deletes the file from disk.\n\tonEvict := func(key Key, value SizedItem) {\n\t\t// Only remove committed items (as temporary files have a different filename)\n\t\tif value.(*lruItem).committed {\n\t\t\terr := os.Remove(filepath.Join(dir, key.(string)))\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tcache := &diskCache{\n\t\tdir: filepath.Clean(dir),\n\t\tmux: &sync.RWMutex{},\n\t\tlru: NewSizedLRU(maxSizeBytes, onEvict),\n\t}\n\n\terr := cache.migrateDirectories()\n\tif err != nil {\n\t\tlog.Fatalf(\"Attempting to migrate the old directory structure to the new structure failed \"+\n\t\t\t\"with error: %v\", err)\n\t}\n\terr = cache.loadExistingFiles()\n\tif err != nil {\n\t\tlog.Fatalf(\"Loading of existing cache entries failed due to error: %v\", err)\n\t}\n\n\treturn cache\n}", "func New() *FS {\n\treturn &FS{\n\t\tdir: &dir{\n\t\t\tchildren: make(map[string]childI),\n\t\t},\n\t}\n}", "func (d *dir) Readdir(count int) (fis []os.FileInfo, err error) {\n\td.fs.log.CDebugf(d.fs.ctx, \"ReadDir %s\", count)\n\tdefer func() {\n\t\td.fs.deferLog.CDebugf(d.fs.ctx, \"ReadDir done: %+v\", err)\n\t\terr = translateErr(err)\n\t}()\n\n\treturn d.fs.readDir(d.node)\n}", "func TestReaddirTypeFixup(t *testing.T) {\n\troot := &randomTypeTest{}\n\n\tmntDir, _ := testMount(t, root, nil)\n\n\tf, err := os.Open(mntDir)\n\tif err != nil {\n\t\tt.Fatalf(\"open: %v\", err)\n\t}\n\tdefer f.Close()\n\n\t// (Ab)use loopbackDirStream to call and parse getdents(2) on mntDir.\n\t// This makes the kernel call READDIRPLUS, which ultimately calls\n\t// randomTypeTest.Readdir() and randomTypeTest.Lookup() above.\n\tds, errno := NewLoopbackDirStream(mntDir)\n\tif errno != 0 {\n\t\tt.Fatalf(\"readdir: %v\", err)\n\t}\n\tdefer ds.Close()\n\n\tfor ds.HasNext() {\n\t\te, err := ds.Next()\n\t\tif err != 0 {\n\t\t\tt.Errorf(\"Next: %d\", err)\n\t\t}\n\t\tgotIsDir := (e.Mode & syscall.S_IFDIR) != 0\n\t\twantIsdir := (crc32.ChecksumIEEE([]byte(e.Name)) % 2) == 1\n\t\tif gotIsDir != wantIsdir {\n\t\t\tt.Errorf(\"%q: isdir %v, want %v\", e.Name, gotIsDir, wantIsdir)\n\t\t}\n\t}\n}", "func ParseDir(T *Tree) []*Node {\n var ret []*Node\n return append(ret, &Node{\n Name: \".\",\n Format: \"root\",\n Children: T.Children,\n Id: \"\",\n\n Num_children: len(T.Children),\n })\n}", "func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) {\n\toriglen := len(buf)\n\tcount = 0\n\tfor max != 0 && len(buf) > 0 {\n\t\treclen, ok := direntReclen(buf)\n\t\tif !ok || reclen > uint64(len(buf)) {\n\t\t\treturn origlen, count, names\n\t\t}\n\t\trec := buf[:reclen]\n\t\tbuf = buf[reclen:]\n\t\tino, ok := direntIno(rec)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tif ino == 0 { // File absent in directory.\n\t\t\tcontinue\n\t\t}\n\t\tconst namoff = uint64(unsafe.Offsetof(Dirent{}.Name))\n\t\tnamlen, ok := direntNamlen(rec)\n\t\tif !ok || namoff+namlen > uint64(len(rec)) {\n\t\t\tbreak\n\t\t}\n\t\tname := rec[namoff : namoff+namlen]\n\t\tfor i, c := range name {\n\t\t\tif c == 0 {\n\t\t\t\tname = name[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// Check for useless names before allocating a string.\n\t\tif string(name) == \".\" || string(name) == \"..\" {\n\t\t\tcontinue\n\t\t}\n\t\tmax--\n\t\tcount++\n\t\tnames = append(names, string(name))\n\t}\n\treturn origlen - len(buf), count, names\n}", "func (v *VFile) Readdir(count int) ([]os.FileInfo, error) {\n\treturn nil, nil\n}", "func (file *Remote) Readdir() ([]DirEntry, error) {\n\treturn ReadDir(bufio.NewReaderSize(file, file.maxBufSize()))\n}", "func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {\n\t// this disables directory listing\n\treturn nil, nil\n}", "func Scan(startDir string, inspector Inspector) (*DirScan, error) {\n\t// Are we scanning a directory?\n\tstat, err := os.Stat(startDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !stat.Mode().IsDir() {\n\t\treturn nil, errors.New(startDir + \" is not a directory\")\n\t}\n\n\t// Setup default if not specified\n\tif inspector == nil {\n\t\tinspector = DefaultInspector{}\n\t}\n\n\t// Track results of directory scan\n\td := DirScan{Name: startDir}\n\n\t// Closure to walk directory\n\twalkFn := 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\t// Do we want to traverse this directory?\n\t\tif info.IsDir() {\n\t\t\terr := inspector.acceptDir(path, info)\n\n\t\t\tif err != nil {\n\t\t\t\tinfof(\"Ignoring directory %s\", path)\n\t\t\t\td.IgnoredDirCount++\n\t\t\t} else if path != startDir { // Don't count the initial directory\n\t\t\t\td.DirCount++\n\t\t\t}\n\n\t\t\treturn err\n\t\t}\n\n\t\tif inspector.acceptFile(path, info) {\n\t\t\t// Found a file to process\n\t\t\td.FileCount++\n\n\t\t\tif d.FileCount % 500 == 0 {\n\t\t\t\tdebugf(\"Found %d files\", d.FileCount)\n\t\t\t}\n\n\t\t\t// Will need file path relative to the starting directory\n\t\t\trelPath, err := filepath.Rel(startDir, path)\n\t\t\tif err != nil {\n\t\t\t\tinfof(\"Unable to calculate relative path for file %s\", path)\n\t\t\t}\n\n\t\t\t// Perform optional further processing of file\n\t\t\tfile := inspector.process(&File{Name: relPath, AbsolutePath: path, Size: info.Size(), Metadata: make(map[string]string)})\n\n\t\t\t// Update directory scan results\n\t\t\td.Files = append(d.Files, file)\n\t\t} else {\n\t\t\tdebugf(\"Ignoring file %s\", path)\n\t\t\td.IgnoredFileCount++\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tinfof(\"Scanning %s\", startDir)\n\n\tstart := time.Now()\n\terr = filepath.Walk(startDir, walkFn)\n\telapsed := time.Since(start)\n\n\tinfof(\"Found %d files in %s (ignored %d directories, %d files)\", d.FileCount, elapsed, d.IgnoredDirCount, d.IgnoredFileCount)\n\n\treturn &d, err\n}", "func (cl *Client) Readdir(fh *FileHandle) (nodes []fs.DirEntry, err error) {\n\tvar (\n\t\tlogp = \"Readdir\"\n\t\treq = cl.generatePacket()\n\t\tpayload = req.fxpReaddir(fh)\n\t)\n\n\tres, err := cl.send(payload)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: %w\", logp, err)\n\t}\n\tif res.kind == packetKindFxpStatus {\n\t\treturn nil, handleStatusCode(res.code, res.message)\n\t}\n\tif res.kind != packetKindFxpName {\n\t\treturn nil, errUnexpectedResponse(packetKindFxpName, res.kind)\n\t}\n\tfor _, node := range res.nodes {\n\t\tnodes = append(nodes, node)\n\t}\n\tres.nodes = nil\n\treturn nodes, nil\n}", "func NewExtendedDirectory(rdr io.Reader) (ExtDir, error) {\n\tvar inode ExtDir\n\terr := binary.Read(rdr, binary.LittleEndian, &inode.ExtDirInit)\n\tif err != nil {\n\t\treturn inode, err\n\t}\n\tfor i := uint16(0); i < inode.IndexCount; i++ {\n\t\tvar tmp DirIndex\n\t\ttmp, err = NewDirectoryIndex(rdr)\n\t\tif err != nil {\n\t\t\treturn inode, err\n\t\t}\n\t\tinode.Indexes = append(inode.Indexes, tmp)\n\t}\n\treturn inode, err\n}", "func New(siaPath modules.SiaPath, rootDir string, wal *writeaheadlog.WAL) (*SiaDir, error) {\n\t// Create path to directory and ensure path contains all metadata\n\tupdates, err := createDirMetadataAll(siaPath, rootDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create metadata for directory\n\tmd, update, err := createDirMetadata(siaPath, rootDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create SiaDir\n\tsd := &SiaDir{\n\t\tmetadata: md,\n\t\tdeps: modules.ProdDependencies,\n\t\tsiaPath: siaPath,\n\t\trootDir: rootDir,\n\t\twal: wal,\n\t}\n\n\treturn sd, managedCreateAndApplyTransaction(wal, append(updates, update)...)\n}", "func directory(name upspin.PathName) *upspin.DirEntry {\n\treturn &upspin.DirEntry{\n\t\tName: name,\n\t\tSignedName: name,\n\t\tAttr: upspin.AttrDirectory,\n\t\tTime: upspin.Now(),\n\t}\n}", "func (d *Dir) Dir(path string) *Dir {\n\tnpath := d.Path + path\n\n\tif err := os.MkdirAll(npath, 0700); err != nil {\n\t\treturn &Dir{Error: err}\n\t}\n\n\treturn &Dir{Path: path}\n}", "func (info *DirInfo) InitDir(root string, filter Filter) error {\n\n\t*info = DirInfo{\n\t\t_focus: 0,\n\t\t_fileCnt: 0,\n\t\t_fileArr: nil,\n\t}\n\tif !strings.HasSuffix(root, \"/\") {\n\t\troot += \"/\"\n\t}\n\n\tinfo._filter = filter\n\terr := filepath.Walk(root, info.handleWalk)\n\tif err != nil {\n\n\t\tfmt.Println(\"there's an error in dict reset : \" + err.Error())\n\t}\n\n\treturn err\n}", "func NewLister() Lister {\n\treturn _lister{\n\t\tioUtil: iioutil.New(),\n\t\tdotYmlUnmarshaller: dotyml.NewUnmarshaller(),\n\t}\n}", "func (n *Node) Readdir(ctx context.Context) (stream fs.DirStream, errno syscall.Errno) {\n\trn := n.rootNode()\n\t// Should we present a virtual gocryptfs.diriv?\n\tvar virtualFiles []fuse.DirEntry\n\tif !rn.args.PlaintextNames && !rn.args.DeterministicNames {\n\t\tvirtualFiles = append(virtualFiles, fuse.DirEntry{Mode: virtualFileMode, Name: nametransform.DirIVFilename})\n\t}\n\n\t// This directory is a mountpoint. Present it as empty.\n\tif rn.args.OneFileSystem && n.isOtherFilesystem {\n\t\treturn fs.NewListDirStream(virtualFiles), 0\n\t}\n\n\td, errno := n.prepareAtSyscall(\"\")\n\tif errno != 0 {\n\t\treturn\n\t}\n\tdefer syscall.Close(d.dirfd)\n\n\t// Read plaintext directory\n\tvar entries []fuse.DirEntry\n\tfd, err := syscallcompat.Openat(d.dirfd, d.pName, syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW, 0)\n\tif err != nil {\n\t\treturn nil, fs.ToErrno(err)\n\t}\n\tdefer syscall.Close(fd)\n\tentries, err = syscallcompat.Getdents(fd)\n\tif err != nil {\n\t\treturn nil, fs.ToErrno(err)\n\t}\n\n\t// Filter out excluded entries\n\tentries = rn.excludeDirEntries(d, entries)\n\n\tif rn.args.PlaintextNames {\n\t\treturn n.readdirPlaintextnames(entries)\n\t}\n\n\tdirIV := rn.deriveDirIV(d.cPath)\n\t// Encrypt names\n\tfor i := range entries {\n\t\tvar cName string\n\t\t// \".gocryptfs.reverse.conf\" in the root directory is mapped to \"gocryptfs.conf\"\n\t\tif n.isRoot() && entries[i].Name == configfile.ConfReverseName &&\n\t\t\t!rn.args.ConfigCustom {\n\t\t\tcName = configfile.ConfDefaultName\n\t\t} else {\n\t\t\tcName, err = rn.nameTransform.EncryptName(entries[i].Name, dirIV)\n\t\t\tif err != nil {\n\t\t\t\tentries[i].Name = \"___GOCRYPTFS_INVALID_NAME___\"\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(cName) > unix.NAME_MAX || len(cName) > rn.nameTransform.GetLongNameMax() {\n\t\t\t\tcName = rn.nameTransform.HashLongName(cName)\n\t\t\t\tdotNameFile := fuse.DirEntry{\n\t\t\t\t\tMode: virtualFileMode,\n\t\t\t\t\tName: cName + nametransform.LongNameSuffix,\n\t\t\t\t}\n\t\t\t\tvirtualFiles = append(virtualFiles, dotNameFile)\n\t\t\t}\n\t\t}\n\t\tentries[i].Name = cName\n\t}\n\n\t// Add virtual files\n\tentries = append(entries, virtualFiles...)\n\treturn fs.NewListDirStream(entries), 0\n}", "func (d *Directory) Directory(name string, modTime time.Time) *Directory {\n\treturn &Directory{\n\t\tw: d.w,\n\t\tname: name,\n\t\tmodTime: modTime,\n\t\tparent: d,\n\t}\n}", "func newFileSystem(basedir string, mkdir osMkdirAll) (*FS, error) {\n\tif err := mkdir(basedir, 0700); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &FS{basedir: basedir}, nil\n}", "func newSiaDirTestDir(testDir string) (string, error) {\n\trootPath := filepath.Join(os.TempDir(), \"siadirs\", testDir)\n\tif err := os.RemoveAll(rootPath); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn rootPath, os.MkdirAll(rootPath, persist.DefaultDiskPermissionsTest)\n}", "func (i *Instance) ReturnStateForDir(directory string) *Instance {\n\tif i.Error != nil {\n\t\treturn i\n\t}\n\ti.ReturnState(directory)\n\treturn i\n}", "func (s *memStat) IsDir() bool { return false }", "func (fod fileOrDir) Readdir(count int) (fis []os.FileInfo, err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\terr = translateErr(err)\n\t\t}\n\t}()\n\tif fod.dir == nil {\n\t\treturn nil, libkbfs.NotDirError{}\n\t}\n\treturn fod.dir.Readdir(count)\n}", "func NewFileInfo(name string, size int64, mode os.FileMode, modTime, accessTime time.Time) *FileInfo {\n\treturn &FileInfo{\n\t\tname: filepath.Base(name),\n\t\tsize: size,\n\t\tmode: mode & (os.ModePerm | os.ModeDir),\n\t\tmodTime: modTime,\n\t\taccessTime: accessTime,\n\t}\n}", "func New(fs fs.FS, path string) (*GitDir, error) {\n\td := &GitDir{}\n\td.fs = fs\n\td.path = path\n\td.packDir = d.fs.Join(d.path, \"objects\", \"pack\")\n\n\tif _, err := fs.Stat(path); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, ErrNotFound\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn d, nil\n}", "func (D Disk) NewIter() DiskIterator {\n\tvar I diskIterator\n\n\tfi, _ := D.filePnt.Stat()\n\n\tI.actualOfset = fi.Size() - 16\n\tI.filePointer = D.filePnt\n\tI.recordInx = D.recNun - 1\n\n\treturn &I\n}", "func (c *StorageClient) Dir() *DirectoryClient {\n\treturn &DirectoryClient{c.Client}\n}", "func (f *fs) OpenDir(name string, context *fuse.Context) ([]fuse.DirEntry, fuse.Status) {\n\tlog.Printf(\"OpenDir '%s'\\n\", name)\n\tvar entries []fuse.DirEntry\n\n\tif name == \"\" {\n\t\tmounts, err := f.client.Sys().ListMounts()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn entries, fuse.OK\n\t\t}\n\t\tif len(mounts) == 0 {\n\t\t\treturn entries, fuse.OK\n\t\t}\n\n\t\tentries = make([]fuse.DirEntry, 0, len(mounts))\n\t\tfor name, _ := range mounts {\n\t\t\tentries = append(entries, fuse.DirEntry{\n\t\t\t\tMode: unix.S_IFDIR,\n\t\t\t\tName: strings.TrimSuffix(name, \"/\"),\n\t\t\t})\n\t\t}\n\t}\n\treturn entries, fuse.OK\n}", "func (ff *File) Readdir(n int) ([]os.FileInfo, error) {\n\tif n > 0 {\n\t\treturn nil, &os.PathError{\n\t\t\tOp: \"readdir\",\n\t\t\tPath: ff.Name(),\n\t\t\tErr: errors.New(\"Sliced call to Readdir not supported\"),\n\t\t}\n\t}\n\tff.fs.RLock()\n\tdefer ff.fs.RUnlock()\n\tret := make([]os.FileInfo, len(ff.entries))\n\ti := 0\n\tfor _, entry := range ff.entries {\n\t\tret[i] = entry\n\t\ti++\n\t}\n\treturn ret, nil\n}", "func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {\n\tdirectoryID, err := f.dirCache.FindDir(ctx, dir, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar iErr error\n\t_, err = f.listAll(ctx, directoryID,\n\t\tfunc(info *api.File) bool {\n\t\t\tremote := path.Join(dir, info.Name)\n\t\t\to, err := f.newObjectWithInfo(ctx, remote, info)\n\t\t\tif err != nil {\n\t\t\t\tiErr = err\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tentries = append(entries, o)\n\t\t\treturn false\n\t\t},\n\t\tfunc(info *api.Collection) bool {\n\t\t\tremote := path.Join(dir, info.Name)\n\t\t\tid := info.Ref\n\t\t\t// cache the directory ID for later lookups\n\t\t\tf.dirCache.Put(remote, id)\n\t\t\td := fs.NewDir(remote, info.TimeCreated).SetID(id)\n\t\t\tentries = append(entries, d)\n\t\t\treturn false\n\t\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif iErr != nil {\n\t\treturn nil, iErr\n\t}\n\treturn entries, nil\n}", "func (cli *FakeDatabaseClient) ReadDir(ctx context.Context, in *dbdpb.ReadDirRequest, opts ...grpc.CallOption) (*dbdpb.ReadDirResponse, error) {\n\tpanic(\"implement me\")\n}", "func New(paths ...string) (*Scanner, error) {\n\tfor _, p := range paths {\n\t\tfi, err := os.Stat(p)\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn nil, err\n\t\tcase !fi.IsDir():\n\t\t\treturn nil, fmt.Errorf(\"path is not directory: %s\", p)\n\t\t}\n\t}\n\n\treturn &Scanner{paths: paths}, nil\n}", "func (fs *helloFS) ReadDir(ctx context.Context, op *fuseops.ReadDirOp) error {\n\t// Find the info for this inode.\n\tinfo, ok := gInodeInfo[op.Inode]\n\tif !ok {\n\t\treturn fuse.ENOENT\n\t}\n\n\tklog.Infof(fmt.Sprintf(\"[ReadDirOp]Inode: %+v, InodeInfo: %+v\", op.Inode, info))\n\n\tif !info.dir {\n\t\treturn fuse.EIO\n\t}\n\n\tentries := info.children\n\t// Grab the range of interest.\n\tif op.Offset > fuseops.DirOffset(len(entries)) {\n\t\treturn fuse.EIO\n\t}\n\n\tentries = entries[op.Offset:]\n\t// Resume at the specified offset into the array.\n\tfor _, e := range entries {\n\t\tn := fuseutil.WriteDirent(op.Dst[op.BytesRead:], e)\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\top.BytesRead += n\n\t}\n\n\treturn nil\n}", "func (inode *Inode_t) CreateDirEntry(disk * Disk_t, name string, mode int16) (int16,Inode_t){\n\t//create Inode\n\taddress ,newInode := CreateInode(disk,mode)\n\t//create dir_entry w/ Inode and name\n\tcharArr := [10]byte{}\n\tcopy(charArr[:],name)\n\tdir_entry := DirEntry_t{Inode_P:address, Name:charArr}\n\n\t//convert dir_entry to []byte\n\tbuff := &bytes.Buffer{}\n\n\tbinary.Write(buff, binary.LittleEndian, dir_entry)\n\n\t//write dir_entry to given inode\n\tinode.WriteInodeData(disk,buff.Bytes())\n\n\treturn address, newInode\n\n}", "func (m *GraphBaseServiceClient) Directory()(*ib14d748b564c787931c10f1c7ba6856eeddea29a5b9e5c5c27eb1224ff65e5c4.DirectoryRequestBuilder) {\n return ib14d748b564c787931c10f1c7ba6856eeddea29a5b9e5c5c27eb1224ff65e5c4.NewDirectoryRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (m *GraphBaseServiceClient) Directory()(*ib14d748b564c787931c10f1c7ba6856eeddea29a5b9e5c5c27eb1224ff65e5c4.DirectoryRequestBuilder) {\n return ib14d748b564c787931c10f1c7ba6856eeddea29a5b9e5c5c27eb1224ff65e5c4.NewDirectoryRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func TestDirInfo(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\trt, err := newRenterTester(t.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer rt.Close()\n\n\t// Create directory\n\terr = rt.renter.CreateDir(\"foo/\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Check that DirInfo returns the same information as stored in the metadata\n\tfooDirInfo, err := rt.renter.DirInfo(\"foo\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\trootDirInfo, err := rt.renter.DirInfo(\"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfooEntry, err := rt.renter.staticDirSet.Open(\"foo\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\trootEntry, err := rt.renter.staticDirSet.Open(\"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = compareDirectoryInfoAndMetadata(fooDirInfo, fooEntry)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = compareDirectoryInfoAndMetadata(rootDirInfo, rootEntry)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (file *Remote) Stat(p string) (DirEntry, error) {\n\tif p != \"\" {\n\t\tfile, err := file.walk(p)\n\t\tif err != nil {\n\t\t\treturn DirEntry{}, err\n\t\t}\n\t\tdefer file.Close()\n\n\t\treturn file.Stat(\"\")\n\t}\n\n\trsp, err := file.client.Send(&Tstat{\n\t\tFID: file.fid,\n\t})\n\tif err != nil {\n\t\treturn DirEntry{}, err\n\t}\n\tstat := rsp.(*Rstat)\n\n\treturn stat.Stat.DirEntry(), nil\n}", "func (w *wrapper) Mkdir(path string, mode uint32) int {\n\tif dfs, ok := w.underlying.(billy.Dir); ok {\n\t\treturn convertError(dfs.MkdirAll(path, os.FileMode(mode)))\n\t}\n\treturn -fuse.ENOSYS\n}", "func (d *Dir) Mkdir(ctx context.Context, req *fuse.MkdirRequest) (fs.Node, error) {\n\t// fmt.Println(\"doing Mkdir for dir \" + req.Name)\n\t// req contains an os.FileMode but I think it isn't really relevant in this implementation\n\tvar isDir int8 = 1\n\tinode := createInode(isDir)\n\tnewInodeNum := d.inodeStream.next()\n\tinode.init(d.inodeNum, newInodeNum)\n\terr := putInode(inode, newInodeNum)\n\td.addFile(req.Name, newInodeNum)\n\tnewDir := &Dir{\n\t\tinodeNum: newInodeNum,\n\t\tinode: inode,\n\t\tinodeStream: d.inodeStream,\n\t}\n\t// should newDir be returned if err != nil?\n\treturn newDir, err\n}", "func (n *Node) Mkdir(ctx context.Context, name string, mode uint32, out *fuse.EntryOut) (*fs.Inode, syscall.Errno) {\n\tdirfd, cName, errno := n.prepareAtSyscall(name)\n\tif errno != 0 {\n\t\treturn nil, errno\n\t}\n\tdefer syscall.Close(dirfd)\n\n\trn := n.rootNode()\n\tvar context *fuse.Context\n\tif rn.args.PreserveOwner {\n\t\tcontext = toFuseCtx(ctx)\n\t}\n\n\tvar st syscall.Stat_t\n\tif rn.args.PlaintextNames {\n\t\terr := syscallcompat.MkdiratUser(dirfd, cName, mode, context)\n\t\tif err != nil {\n\t\t\treturn nil, fs.ToErrno(err)\n\t\t}\n\t\tvar ust unix.Stat_t\n\t\terr = syscallcompat.Fstatat(dirfd, cName, &ust, unix.AT_SYMLINK_NOFOLLOW)\n\t\tif err != nil {\n\t\t\treturn nil, fs.ToErrno(err)\n\t\t}\n\t\tst = syscallcompat.Unix2syscall(ust)\n\n\t\t// Create child node & return\n\t\tch := n.newChild(ctx, &st, out)\n\t\treturn ch, 0\n\n\t}\n\n\t// We need write and execute permissions to create gocryptfs.diriv.\n\t// Also, we need read permissions to open the directory (to avoid\n\t// race-conditions between getting and setting the mode).\n\torigMode := mode\n\tmode = mode | 0700\n\n\t// Handle long file name\n\tif nametransform.IsLongContent(cName) {\n\t\t// Create \".name\"\n\t\terr := rn.nameTransform.WriteLongNameAt(dirfd, cName, name)\n\t\tif err != nil {\n\t\t\treturn nil, fs.ToErrno(err)\n\t\t}\n\t\t// Create directory & rollback .name file on error\n\t\terr = rn.mkdirWithIv(dirfd, cName, mode, context)\n\t\tif err != nil {\n\t\t\tnametransform.DeleteLongNameAt(dirfd, cName)\n\t\t\treturn nil, fs.ToErrno(err)\n\t\t}\n\t} else {\n\t\terr := rn.mkdirWithIv(dirfd, cName, mode, context)\n\t\tif err != nil {\n\t\t\treturn nil, fs.ToErrno(err)\n\t\t}\n\t}\n\n\t// Fill `st`\n\tfd, err := syscallcompat.Openat(dirfd, cName,\n\t\tsyscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW, 0)\n\tif err != nil {\n\t\ttlog.Warn.Printf(\"Mkdir %q: Openat failed: %v\", cName, err)\n\t\treturn nil, fs.ToErrno(err)\n\t}\n\tdefer syscall.Close(fd)\n\n\terr = syscall.Fstat(fd, &st)\n\tif err != nil {\n\t\ttlog.Warn.Printf(\"Mkdir %q: Fstat failed: %v\", cName, err)\n\t\treturn nil, fs.ToErrno(err)\n\t}\n\n\t// Fix permissions\n\tif origMode != mode {\n\t\t// Preserve SGID bit if it was set due to inheritance.\n\t\torigMode = uint32(st.Mode&^0777) | origMode\n\t\terr = syscall.Fchmod(fd, origMode)\n\t\tif err != nil {\n\t\t\ttlog.Warn.Printf(\"Mkdir %q: Fchmod %#o -> %#o failed: %v\", cName, mode, origMode, err)\n\t\t}\n\n\t}\n\n\t// Create child node & return\n\tch := n.newChild(ctx, &st, out)\n\treturn ch, 0\n}", "func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {\n\tvar iErr error\n\t_, err = f.listAll(ctx, dir, false, false, defaultDepth, func(remote string, isDir bool, info *api.Prop) bool {\n\t\tif isDir {\n\t\t\td := fs.NewDir(remote, time.Time(info.Modified))\n\t\t\t// .SetID(info.ID)\n\t\t\t// FIXME more info from dir? can set size, items?\n\t\t\tentries = append(entries, d)\n\t\t} else {\n\t\t\to, err := f.newObjectWithInfo(ctx, remote, info)\n\t\t\tif err != nil {\n\t\t\t\tiErr = err\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tentries = append(entries, o)\n\t\t}\n\t\treturn false\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif iErr != nil {\n\t\treturn nil, iErr\n\t}\n\treturn entries, nil\n}", "func NewDirCollector() DirCollector {\n\treturn make(DirCollector)\n}", "func createDirectories(e *finalizeFileInfo) []*finalizeFileInfo {\n\tvar (\n\t\tdirs = make([]*finalizeFileInfo, 0)\n\t\tentries = make([]*directoryEntryRaw, 0)\n\t)\n\t// go through each entry, and create a directory structure for it\n\t// we will cycle through each directory, creating an entry for it\n\t// and its children. A second pass will split into headers\n\tfor _, child := range e.children {\n\t\tblockPos := child.inodeLocation\n\t\tvar iType inodeType\n\t\tswitch child.fileType {\n\t\tcase fileRegular:\n\t\t\tiType = inodeBasicFile\n\t\tcase fileSymlink:\n\t\t\tiType = inodeBasicSymlink\n\t\tcase fileDirectory:\n\t\t\tiType = inodeBasicDirectory\n\t\tcase fileBlock:\n\t\t\tiType = inodeBasicBlock\n\t\tcase fileChar:\n\t\t\tiType = inodeBasicChar\n\t\tcase fileFifo:\n\t\t\tiType = inodeBasicFifo\n\t\tcase fileSocket:\n\t\t\tiType = inodeBasicSocket\n\t\t}\n\t\tentry := &directoryEntryRaw{\n\t\t\tname: child.Name(),\n\t\t\tisSubdirectory: child.IsDir(),\n\t\t\tstartBlock: blockPos.block,\n\t\t\toffset: blockPos.offset,\n\t\t\tinodeType: iType,\n\t\t\tinodeNumber: child.inode.index(),\n\t\t\t// we do not yet know the inodeNumber, which is an offset from the one in the header\n\t\t\t// it will be filled in later\n\t\t}\n\t\t// set the inode type. It doesn't use extended, just the basic ones.\n\t\tentries = append(entries, entry)\n\t}\n\te.directory = &directory{\n\t\tentries: entries,\n\t}\n\tdirs = append(dirs, e)\n\t// do children in a separate loop, so that we get all of the children lined up\n\tfor _, child := range e.children {\n\t\tif child.IsDir() {\n\t\t\tdirs = append(dirs, createDirectories(child)...)\n\t\t}\n\t}\n\treturn dirs\n}", "func scanDir(dir string) error {\n\n\tvar files []string\n\tvar m = make(map[string]int)\n\tm[\"directories\"] = 0\n\tm[\"others\"] = 0\n\tm[\"symlinks\"] = 0\n\n\tfmt.Printf(\"Path: %s\\n\", dir)\n\n filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n files = append(files, path)\n return nil\n\t})\n\t\n for _, file := range files {\n state, err := os.Lstat(file)\n\t\tif(err != nil){\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t\tif state.Mode() & os.ModeSymlink != 0{\n\t\t\tm[\"symlinks\"] = m[\"symlinks\"] + 1\n\t\t}\n\n\t\tswitch mode := state.Mode(); {\n\n\t\tcase mode.IsDir():\n\t\t\tm[\"directories\"] = m[\"directories\"] + 1\n\n\t\tcase mode.IsRegular():\n\t\t\tm[\"others\"] = m[\"others\"] + 1\n\n\t\t}\n\t}\t\n\n\tfor key, value := range m{\n\t\tfmt.Println(key, \":\", value);\n\t}\n\n\treturn nil\n}", "func readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno) {\n\tr0, _, _ := syscall_syscall(libc_readdir_r_trampoline_addr, uintptr(dir), uintptr(unsafe.Pointer(entry)), uintptr(unsafe.Pointer(result)))\n\tres = Errno(r0)\n\treturn\n}" ]
[ "0.70143336", "0.6318057", "0.6316557", "0.59013355", "0.5891918", "0.57855", "0.5736885", "0.5731109", "0.571727", "0.5715768", "0.5702267", "0.56806433", "0.5642527", "0.5584259", "0.55786663", "0.5512318", "0.5490894", "0.5477301", "0.5384469", "0.53448236", "0.5331859", "0.5323757", "0.53136396", "0.5309082", "0.5299993", "0.52915627", "0.52915627", "0.52915627", "0.52915627", "0.52915627", "0.52840257", "0.527266", "0.52712554", "0.5269193", "0.5268107", "0.52670765", "0.5242831", "0.5213349", "0.5204714", "0.5199891", "0.51977324", "0.5194577", "0.51798755", "0.5179539", "0.5161087", "0.51111895", "0.5110861", "0.51105195", "0.50829315", "0.5057755", "0.50521", "0.50521", "0.50521", "0.50500435", "0.50489825", "0.5047467", "0.503666", "0.5033329", "0.4998964", "0.4991764", "0.49844447", "0.49662524", "0.4962518", "0.4959224", "0.4958249", "0.49560824", "0.49393356", "0.49281982", "0.49276236", "0.49179637", "0.49041024", "0.48937282", "0.4875503", "0.48721913", "0.4868011", "0.48617765", "0.48450148", "0.48361", "0.4834292", "0.48320776", "0.48250353", "0.48240235", "0.48184562", "0.48177627", "0.48052222", "0.48026016", "0.4801115", "0.47980207", "0.4797452", "0.4797452", "0.47964105", "0.47949392", "0.47943407", "0.47906324", "0.47893858", "0.4784082", "0.47837684", "0.47832724", "0.47808647", "0.47805268" ]
0.65730906
1
TestConcurrentBuildControllers tests the transition of a build from new to pending. Ensures that only a single New > Pending transition happens and that only a single pod is created during a set period of time.
func TestConcurrentBuildControllers(t *testing.T) { defer testutil.DumpEtcdOnFailure(t) // Start a master with multiple BuildControllers osClient, kClient := setupBuildControllerTest(controllerCount{BuildControllers: 5}, t) build.RunBuildControllerTest(t, osClient, kClient) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestConcurrentBuildPodControllers(t *testing.T) {\n\tdefer testutil.DumpEtcdOnFailure(t)\n\t// Start a master with multiple BuildPodControllers\n\tosClient, kClient := setupBuildControllerTest(controllerCount{BuildPodControllers: 5}, t)\n\tbuild.RunBuildPodControllerTest(t, osClient, kClient)\n}", "func TestConcurrentBuildControllers(t *testing.T) {\n\t// Start a master with multiple BuildControllers\n\tbuildClient, _, kClient, fn := setupBuildControllerTest(controllerCount{BuildControllers: 5}, t)\n\tdefer fn()\n\tbuild.RunBuildControllerTest(t, buildClient, kClient)\n}", "func TestConcurrentBuildControllersPodSync(t *testing.T) {\n\t// Start a master with multiple BuildControllers\n\tbuildClient, _, kClient, fn := setupBuildControllerTest(controllerCount{BuildControllers: 5}, t)\n\tdefer fn()\n\tbuild.RunBuildControllerPodSyncTest(t, buildClient, kClient)\n}", "func TestTriggerController(t *testing.T) {\n\tconfig, stopFn := framework.RunControlPlane(t)\n\tdefer stopFn()\n\n\tctx, cancel := context.WithTimeout(context.TODO(), time.Second*20)\n\tdefer cancel()\n\n\tfakeClock := &fakeclock.FakeClock{}\n\t// Build, instantiate and run the trigger controller.\n\tkubeClient, factory, cmCl, cmFactory := framework.NewClients(t, config)\n\n\tnamespace := \"testns\"\n\n\t// Create Namespace\n\tns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}\n\t_, err := kubeClient.CoreV1().Namespaces().Create(context.TODO(), ns, metav1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tctrl, queue, mustSync := trigger.NewController(logf.Log, cmCl, factory, cmFactory, framework.NewEventRecorder(t), fakeClock, policies.NewTriggerPolicyChain(fakeClock))\n\tc := controllerpkg.NewController(\n\t\tcontext.Background(),\n\t\t\"trigger_test\",\n\t\tmetrics.New(logf.Log),\n\t\tctrl.ProcessItem,\n\t\tmustSync,\n\t\tnil,\n\t\tqueue,\n\t)\n\tstopController := framework.StartInformersAndController(t, factory, cmFactory, c)\n\tdefer stopController()\n\n\t// Create a Certificate resource and wait for it to have the 'Issuing' condition.\n\tcert, err := cmCl.CertmanagerV1().Certificates(namespace).Create(ctx, &cmapi.Certificate{\n\t\tObjectMeta: metav1.ObjectMeta{Name: \"testcrt\", Namespace: \"testns\"},\n\t\tSpec: cmapi.CertificateSpec{\n\t\t\tSecretName: \"example\",\n\t\t\tCommonName: \"example.com\",\n\t\t\tIssuerRef: cmmeta.ObjectReference{Name: \"testissuer\"}, // doesn't need to exist\n\t\t},\n\t}, metav1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = wait.Poll(time.Millisecond*100, time.Second*5, func() (done bool, err error) {\n\t\tc, err := cmCl.CertmanagerV1().Certificates(cert.Namespace).Get(ctx, cert.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tt.Logf(\"Failed to fetch Certificate resource, retrying: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tif !apiutil.CertificateHasCondition(c, cmapi.CertificateCondition{\n\t\t\tType: cmapi.CertificateConditionIssuing,\n\t\t\tStatus: cmmeta.ConditionTrue,\n\t\t}) {\n\t\t\tt.Logf(\"Certificate does not have expected condition, got=%#v\", apiutil.GetCertificateCondition(c, cmapi.CertificateConditionIssuing))\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func validateController(ctx context.Context, c clientset.Interface, containerImage string, replicas int, containername string, testname string, validator validatorFn, ns string) {\n\tcontainerImage = trimDockerRegistry(containerImage)\n\tgetPodsTemplate := \"--template={{range.items}}{{.metadata.name}} {{end}}\"\n\n\tgetContainerStateTemplate := fmt.Sprintf(`--template={{if (exists . \"status\" \"containerStatuses\")}}{{range .status.containerStatuses}}{{if (and (eq .name \"%s\") (exists . \"state\" \"running\"))}}true{{end}}{{end}}{{end}}`, containername)\n\n\tgetImageTemplate := fmt.Sprintf(`--template={{if (exists . \"spec\" \"containers\")}}{{range .spec.containers}}{{if eq .name \"%s\"}}{{.image}}{{end}}{{end}}{{end}}`, containername)\n\n\tginkgo.By(fmt.Sprintf(\"waiting for all containers in %s pods to come up.\", testname)) //testname should be selector\nwaitLoop:\n\tfor start := time.Now(); time.Since(start) < framework.PodStartTimeout && ctx.Err() == nil; time.Sleep(5 * time.Second) {\n\t\tgetPodsOutput := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"pods\", \"-o\", \"template\", getPodsTemplate, \"-l\", testname)\n\t\tpods := strings.Fields(getPodsOutput)\n\t\tif numPods := len(pods); numPods != replicas {\n\t\t\tginkgo.By(fmt.Sprintf(\"Replicas for %s: expected=%d actual=%d\", testname, replicas, numPods))\n\t\t\tcontinue\n\t\t}\n\t\tvar runningPods []string\n\t\tfor _, podID := range pods {\n\t\t\trunning := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"pods\", podID, \"-o\", \"template\", getContainerStateTemplate)\n\t\t\tif running != \"true\" {\n\t\t\t\tframework.Logf(\"%s is created but not running\", podID)\n\t\t\t\tcontinue waitLoop\n\t\t\t}\n\n\t\t\tcurrentImage := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"pods\", podID, \"-o\", \"template\", getImageTemplate)\n\t\t\tcurrentImage = trimDockerRegistry(currentImage)\n\t\t\tif currentImage != containerImage {\n\t\t\t\tframework.Logf(\"%s is created but running wrong image; expected: %s, actual: %s\", podID, containerImage, currentImage)\n\t\t\t\tcontinue waitLoop\n\t\t\t}\n\n\t\t\t// Call the generic validator function here.\n\t\t\t// This might validate for example, that (1) getting a url works and (2) url is serving correct content.\n\t\t\tif err := validator(ctx, c, podID); err != nil {\n\t\t\t\tframework.Logf(\"%s is running right image but validator function failed: %v\", podID, err)\n\t\t\t\tcontinue waitLoop\n\t\t\t}\n\n\t\t\tframework.Logf(\"%s is verified up and running\", podID)\n\t\t\trunningPods = append(runningPods, podID)\n\t\t}\n\t\t// If we reach here, then all our checks passed.\n\t\tif len(runningPods) == replicas {\n\t\t\treturn\n\t\t}\n\t}\n\t// Reaching here means that one of more checks failed multiple times. Assuming its not a race condition, something is broken.\n\tframework.Failf(\"Timed out after %v seconds waiting for %s pods to reach valid state\", framework.PodStartTimeout.Seconds(), testname)\n}", "func TestBuildControllerNoBuildManifestsFirst(t *testing.T) {\n\tf := newTestFixture(t)\n\tdefer f.TearDown()\n\n\tmanifests := make([]model.Manifest, 10)\n\tfor i := 0; i < 10; i++ {\n\t\tsync := model.Sync{LocalPath: f.Path(), ContainerPath: \"/go\"}\n\t\tmanifests[i] = f.newManifest(fmt.Sprintf(\"built%d\", i+1), []model.Sync{sync})\n\t}\n\n\tfor _, i := range []int{3, 7, 8} {\n\t\tmanifests[i] = assembleK8sManifest(\n\t\t\tmodel.Manifest{\n\t\t\t\tName: model.ManifestName(fmt.Sprintf(\"unbuilt%d\", i+1))},\n\t\t\tmodel.K8sTarget{YAML: \"fake-yaml\"})\n\t}\n\tf.Start(manifests, true)\n\n\tvar observedBuildOrder []string\n\tfor i := 0; i < len(manifests); i++ {\n\t\tcall := f.nextCall()\n\t\tobservedBuildOrder = append(observedBuildOrder, call.k8s().Name.String())\n\t}\n\n\t// throwing a bunch of elements at it to increase confidence we maintain order between built and unbuilt\n\t// this might miss bugs since we might just get these elements back in the right order via luck\n\texpectedBuildOrder := []string{\n\t\t\"unbuilt4\",\n\t\t\"unbuilt8\",\n\t\t\"unbuilt9\",\n\t\t\"built1\",\n\t\t\"built2\",\n\t\t\"built3\",\n\t\t\"built5\",\n\t\t\"built6\",\n\t\t\"built7\",\n\t\t\"built10\",\n\t}\n\tassert.Equal(t, expectedBuildOrder, observedBuildOrder)\n}", "func TestTriggerController(t *testing.T) {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*40)\n\tdefer cancel()\n\n\tconfig, stopFn := framework.RunControlPlane(t, ctx)\n\tdefer stopFn()\n\n\tfakeClock := &fakeclock.FakeClock{}\n\t// Build, instantiate and run the trigger controller.\n\tkubeClient, factory, cmCl, cmFactory := framework.NewClients(t, config)\n\n\tnamespace := \"testns\"\n\n\t// Create Namespace\n\tns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}\n\t_, err := kubeClient.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tshouldReissue := policies.NewTriggerPolicyChain(fakeClock).Evaluate\n\tctrl, queue, mustSync := trigger.NewController(logf.Log, cmCl, factory, cmFactory, framework.NewEventRecorder(t), fakeClock, shouldReissue)\n\tc := controllerpkg.NewController(\n\t\tctx,\n\t\t\"trigger_test\",\n\t\tmetrics.New(logf.Log, clock.RealClock{}),\n\t\tctrl.ProcessItem,\n\t\tmustSync,\n\t\tnil,\n\t\tqueue,\n\t)\n\tstopController := framework.StartInformersAndController(t, factory, cmFactory, c)\n\tdefer stopController()\n\n\t// Create a Certificate resource and wait for it to have the 'Issuing' condition.\n\tcert, err := cmCl.CertmanagerV1().Certificates(namespace).Create(ctx, &cmapi.Certificate{\n\t\tObjectMeta: metav1.ObjectMeta{Name: \"testcrt\", Namespace: \"testns\"},\n\t\tSpec: cmapi.CertificateSpec{\n\t\t\tSecretName: \"example\",\n\t\t\tCommonName: \"example.com\",\n\t\t\tIssuerRef: cmmeta.ObjectReference{Name: \"testissuer\"}, // doesn't need to exist\n\t\t},\n\t}, metav1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = wait.PollImmediateUntil(time.Millisecond*100, func() (done bool, err error) {\n\t\tc, err := cmCl.CertmanagerV1().Certificates(cert.Namespace).Get(ctx, cert.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tt.Logf(\"Failed to fetch Certificate resource, retrying: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tif !apiutil.CertificateHasCondition(c, cmapi.CertificateCondition{\n\t\t\tType: cmapi.CertificateConditionIssuing,\n\t\t\tStatus: cmmeta.ConditionTrue,\n\t\t}) {\n\t\t\tt.Logf(\"Certificate does not have expected condition, got=%#v\", apiutil.GetCertificateCondition(c, cmapi.CertificateConditionIssuing))\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}, ctx.Done())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func TestNewController(t *testing.T) {\n\tmessagingClientSet, err := clientset.NewForConfig(&rest.Config{})\n\tif err != nil {\n\t\tt.Fail()\n\t}\n\n\tmessagingInformerFactory := informers.NewSharedInformerFactory(messagingClientSet, 0)\n\tnatssChannelInformer := messagingInformerFactory.Messaging().V1alpha1().NatssChannels()\n\n\tc := NewController(reconciler.Options{\n\t\tKubeClientSet: fakekubeclientset.NewSimpleClientset(),\n\t\tDynamicClientSet: nil,\n\t\tNatssClientSet: nil,\n\t\tRecorder: nil,\n\t\tStatsReporter: nil,\n\t\tConfigMapWatcher: nil,\n\t\tLogger: logtesting.TestLogger(t),\n\t\tResyncPeriod: 0,\n\t\tStopChannel: nil,\n\t}, dispatchertesting.NewDispatcherDoNothing(), natssChannelInformer)\n\tif c == nil {\n\t\tt.Errorf(\"unable to create dispatcher controller\")\n\t}\n}", "func (m *MockPodControllerFactory) Build(mgr mc_manager.AsyncManager, clusterName string) (controller1.PodController, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", mgr, clusterName)\n\tret0, _ := ret[0].(controller1.PodController)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestController(t *testing.T) {\n\tctx, _ := rtesting.SetupFakeContext(t)\n\tctx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\n\t// Create reconcilers, start controller.\n\tresults := test.NewResultsClient(t)\n\n\ttrctrl := taskrun.NewController(ctx, results)\n\tprctrl := pipelinerun.NewController(ctx, results)\n\tgo controller.StartAll(ctx, trctrl, prctrl)\n\n\t// Start informers - this notifies the controller of new events.\n\tgo taskruninformer.Get(ctx).Informer().Run(ctx.Done())\n\tgo pipelineruninformer.Get(ctx).Informer().Run(ctx.Done())\n\n\tpipeline := fakepipelineclient.Get(ctx)\n\tt.Run(\"taskrun\", func(t *testing.T) {\n\t\ttr := &v1beta1.TaskRun{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: \"tekton.dev/v1beta1\",\n\t\t\t\tKind: \"TaskRun\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"taskrun\",\n\t\t\t\tNamespace: \"ns\",\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"demo\": \"demo\",\n\t\t\t\t\t// This TaskRun belongs to a PipelineRun, so the record should\n\t\t\t\t\t// be associated with the PipelineRun result.\n\t\t\t\t\t\"tekton.dev/pipelineRun\": \"pr\",\n\t\t\t\t},\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\t\tAPIVersion: \"tekton.dev/v1beta1\",\n\t\t\t\t\tKind: \"PipelineRun\",\n\t\t\t\t\tUID: \"pr-id\",\n\t\t\t\t}},\n\t\t\t\tUID: \"tr-id\",\n\t\t\t},\n\t\t}\n\n\t\t// The following is a hack to make the fake clients play nice with\n\t\t// each other. While the controller uses the typed informer that uses\n\t\t// the fake pipeline client to receive events, the controller uses the\n\t\t// fake dynamic client to fetch and update objects during reconcile.\n\t\t// These fake clients store objects independently, so we create the\n\t\t// object in each client to make sure the data is populated in both\n\t\t// places.\n\t\tif _, err := pipeline.TektonV1beta1().TaskRuns(tr.GetNamespace()).Create(tr); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdata, err := runtime.DefaultUnstructuredConverter.ToUnstructured(tr)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ToUnstructured: %v\", err)\n\t\t}\n\t\t_, err = dynamicinject.Get(ctx).Resource(apis.KindToResource(tr.GroupVersionKind())).Namespace(tr.GetNamespace()).Create(&unstructured.Unstructured{Object: data}, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Create: %v\", err)\n\t\t}\n\n\t\twait(ctx, t, tr, \"ns/results/pr-id\")\n\t})\n\n\tt.Run(\"pipelinerun\", func(t *testing.T) {\n\t\tpr := &v1beta1.PipelineRun{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: \"tekton.dev/v1beta1\",\n\t\t\t\tKind: \"PipelineRun\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"pr\",\n\t\t\t\tNamespace: \"ns\",\n\t\t\t\tAnnotations: map[string]string{\"demo\": \"demo\"},\n\t\t\t\tUID: \"pr-id\",\n\t\t\t},\n\t\t}\n\n\t\t// Same create hack as taskrun (see above).\n\t\tif _, err := pipeline.TektonV1beta1().PipelineRuns(pr.GetNamespace()).Create(pr); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdata, err := runtime.DefaultUnstructuredConverter.ToUnstructured(pr)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ToUnstructured: %v\", err)\n\t\t}\n\t\t_, err = dynamicinject.Get(ctx).Resource(apis.KindToResource(pr.GroupVersionKind())).Namespace(pr.GetNamespace()).Create(&unstructured.Unstructured{Object: data}, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Create: %v\", err)\n\t\t}\n\n\t\twait(ctx, t, pr, \"ns/results/pr-id\")\n\t})\n}", "func TestControllerInitPrepare_Parallel(t *testing.T) {\n\t_ = testlib.IntegrationEnv(t)\n\n\tt.Run(\"with parent context that is never canceled\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\t// the nil params should never be used in this case\n\t\tbuildControllers := controllerinit.Prepare(nil, nil, buildBrokenInformer(t))\n\n\t\tstart := time.Now()\n\t\trunControllers, err := buildControllers(context.Background()) // we expect this to not block forever even with a context.Background()\n\t\tdelta := time.Since(start)\n\n\t\trequire.EqualError(t, err,\n\t\t\t\"failed to sync informers of k8s.io/client-go/informers.sharedInformerFactory: \"+\n\t\t\t\t\"[k8s.io/api/core/v1.Namespace k8s.io/api/core/v1.Node]\")\n\t\trequire.Nil(t, runControllers)\n\n\t\trequire.InDelta(t, time.Minute, delta, float64(30*time.Second))\n\t})\n\n\tt.Run(\"with parent context that is canceled early\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\t// the nil params should never be used in this case\n\t\tbuildControllers := controllerinit.Prepare(nil, nil, buildBrokenInformer(t))\n\n\t\t// we expect this to exit sooner because the parent context is shorter\n\t\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\t\tt.Cleanup(cancel)\n\n\t\tstart := time.Now()\n\t\trunControllers, err := buildControllers(ctx)\n\t\tdelta := time.Since(start)\n\n\t\trequire.EqualError(t, err,\n\t\t\t\"failed to sync informers of k8s.io/client-go/informers.sharedInformerFactory: \"+\n\t\t\t\t\"[k8s.io/api/core/v1.Namespace k8s.io/api/core/v1.Node]\")\n\t\trequire.Nil(t, runControllers)\n\n\t\trequire.InDelta(t, 10*time.Second, delta, float64(15*time.Second))\n\t})\n}", "func (b *Botanist) WaitForControllersToBeActive(ctx context.Context) error {\n\ttype controllerInfo struct {\n\t\tname string\n\t\tlabels map[string]string\n\t}\n\n\ttype checkOutput struct {\n\t\tcontrollerName string\n\t\tready bool\n\t\terr error\n\t}\n\n\tvar (\n\t\tcontrollers = []controllerInfo{}\n\t\tpollInterval = 5 * time.Second\n\t)\n\n\t// Check whether the kube-controller-manager deployment exists\n\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(b.Shoot.SeedNamespace, v1beta1constants.DeploymentNameKubeControllerManager), &appsv1.Deployment{}); err == nil {\n\t\tcontrollers = append(controllers, controllerInfo{\n\t\t\tname: v1beta1constants.DeploymentNameKubeControllerManager,\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"app\": \"kubernetes\",\n\t\t\t\t\"role\": \"controller-manager\",\n\t\t\t},\n\t\t})\n\t} else if client.IgnoreNotFound(err) != nil {\n\t\treturn err\n\t}\n\n\treturn retry.UntilTimeout(context.TODO(), pollInterval, 90*time.Second, func(ctx context.Context) (done bool, err error) {\n\t\tvar (\n\t\t\twg sync.WaitGroup\n\t\t\tout = make(chan *checkOutput)\n\t\t)\n\n\t\tfor _, controller := range controllers {\n\t\t\twg.Add(1)\n\n\t\t\tgo func(controller controllerInfo) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tpodList := &corev1.PodList{}\n\t\t\t\terr := b.K8sSeedClient.Client().List(ctx, podList,\n\t\t\t\t\tclient.InNamespace(b.Shoot.SeedNamespace),\n\t\t\t\t\tclient.MatchingLabels(controller.labels))\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check that only one replica of the controller exists.\n\t\t\t\tif len(podList.Items) != 1 {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for %s to have exactly one replica\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Check that the existing replica is not in getting deleted.\n\t\t\t\tif podList.Items[0].DeletionTimestamp != nil {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for a new replica of %s\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check if the controller is active by reading its leader election record.\n\t\t\t\tleaderElectionRecord, err := common.ReadLeaderElectionRecord(b.K8sShootClient, resourcelock.EndpointsResourceLock, metav1.NamespaceSystem, controller.name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif delta := metav1.Now().UTC().Sub(leaderElectionRecord.RenewTime.Time.UTC()); delta <= pollInterval-time.Second {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, ready: true}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tb.Logger.Infof(\"Waiting for %s to be active\", controller.name)\n\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t}(controller)\n\t\t}\n\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tclose(out)\n\t\t}()\n\n\t\tfor result := range out {\n\t\t\tif result.err != nil {\n\t\t\t\treturn retry.SevereError(fmt.Errorf(\"could not check whether controller %s is active: %+v\", result.controllerName, result.err))\n\t\t\t}\n\t\t\tif !result.ready {\n\t\t\t\treturn retry.MinorError(fmt.Errorf(\"controller %s is not active\", result.controllerName))\n\t\t\t}\n\t\t}\n\n\t\treturn retry.Ok()\n\t})\n}", "func TestController(t *testing.T) {\n\tfakeKubeClient, catalogClient, fakeBrokerCatalog, _, _, testController, _, stopCh := newTestController(t)\n\tdefer close(stopCh)\n\n\tt.Log(fakeKubeClient, catalogClient, fakeBrokerCatalog, testController, stopCh)\n\n\tfakeBrokerCatalog.RetCatalog = &brokerapi.Catalog{\n\t\tServices: []*brokerapi.Service{\n\t\t\t{\n\t\t\t\tName: \"test-service\",\n\t\t\t\tID: \"12345\",\n\t\t\t\tDescription: \"a test service\",\n\t\t\t\tPlans: []brokerapi.ServicePlan{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"test-plan\",\n\t\t\t\t\t\tFree: true,\n\t\t\t\t\t\tID: \"34567\",\n\t\t\t\t\t\tDescription: \"a test plan\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tname := \"test-name\"\n\tbroker := &v1alpha1.Broker{\n\t\tObjectMeta: v1.ObjectMeta{Name: name},\n\t\tSpec: v1alpha1.BrokerSpec{\n\t\t\tURL: \"https://example.com\",\n\t\t},\n\t}\n\tbrokerClient := catalogClient.Servicecatalog().Brokers()\n\n\tbrokerServer, err := brokerClient.Create(broker)\n\tif nil != err {\n\t\tt.Fatalf(\"error creating the broker %q (%q)\", broker, err)\n\t}\n\n\tif err := wait.PollImmediate(500*time.Millisecond, wait.ForeverTestTimeout,\n\t\tfunc() (bool, error) {\n\t\t\tbrokerServer, err = brokerClient.Get(name)\n\t\t\tif nil != err {\n\t\t\t\treturn false,\n\t\t\t\t\tfmt.Errorf(\"error getting broker %s (%s)\",\n\t\t\t\t\t\tname, err)\n\t\t\t} else if len(brokerServer.Status.Conditions) > 0 {\n\t\t\t\tt.Log(brokerServer)\n\t\t\t\treturn true, nil\n\t\t\t} else {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t},\n\t); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check\n\tserviceClassClient := catalogClient.Servicecatalog().ServiceClasses()\n\t_, err = serviceClassClient.Get(\"test-service\")\n\tif nil != err {\n\t\tt.Fatal(\"could not find the test service\", err)\n\t}\n\n\t// cleanup our broker\n\terr = brokerClient.Delete(name, &v1.DeleteOptions{})\n\tif nil != err {\n\t\tt.Fatalf(\"broker should be deleted (%s)\", err)\n\t}\n\n\t// uncomment if/when deleting a broker deletes the associated service\n\t// if class, err := serviceClassClient.Get(\"test-service\"); nil == err {\n\t// \tt.Fatal(\"found the test service that should have been deleted\", err, class)\n\t// }\n}", "func TestConcurrent(t *testing.T) {\n\tt.Parallel()\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tt.Cleanup(cancel)\n\n\tconfig := Config{MaxConcurrency: 4}\n\tcountdown := NewCountdown(config.MaxConcurrency)\n\tprocess := NewMockEventsProcess(ctx, t, config, func(ctx context.Context, event types.Event) error {\n\t\tdefer countdown.Decrement()\n\t\ttime.Sleep(time.Second)\n\t\treturn trace.Wrap(ctx.Err())\n\t})\n\n\ttimeBefore := time.Now()\n\tfor i := 0; i < config.MaxConcurrency; i++ {\n\t\tresource, err := types.NewAccessRequest(fmt.Sprintf(\"REQ-%v\", i+1), \"foo\", \"admin\")\n\t\trequire.NoError(t, err)\n\t\tprocess.Events.Fire(types.Event{Type: types.OpPut, Resource: resource})\n\t}\n\trequire.NoError(t, countdown.Wait(ctx))\n\n\ttimeAfter := time.Now()\n\tassert.InDelta(t, time.Second, timeAfter.Sub(timeBefore), float64(500*time.Millisecond))\n}", "func TestControllerHandleEvents(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\taddServices []*corev1.Service\n\t\tupdateServices []string\n\t\tdelServices []string\n\t\texpAddedServices []string\n\t\texpDeletedServices []string\n\t}{\n\t\t{\n\t\t\tname: \"If a controller is watching services it should react to the service change events.\",\n\t\t\taddServices: []*corev1.Service{\n\t\t\t\t{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"svc1\"},\n\t\t\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\t\t\tType: \"ClusterIP\",\n\t\t\t\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t\t\t\tcorev1.ServicePort{Name: \"port1\", Port: 8080},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"svc2\"},\n\t\t\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\t\t\tType: \"ClusterIP\",\n\t\t\t\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t\t\t\tcorev1.ServicePort{Name: \"port1\", Port: 8080},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tupdateServices: []string{\"svc1\"},\n\t\t\tdelServices: []string{\"svc1\", \"svc2\"},\n\t\t\texpAddedServices: []string{\"svc1\", \"svc2\", \"svc1\"},\n\t\t\texpDeletedServices: []string{\"svc1\", \"svc2\"},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\trequire := require.New(t)\n\t\t\tassert := assert.New(t)\n\t\t\tresync := 30 * time.Second\n\t\t\tstopC := make(chan struct{})\n\t\t\tvar gotAddedServices []string\n\t\t\tvar gotDeletedServices []string\n\n\t\t\t// Create the kubernetes client.\n\t\t\tk8scli, _, _, err := cli.GetK8sClients(\"\")\n\n\t\t\trequire.NoError(err, \"kubernetes client is required\")\n\n\t\t\t// Prepare the environment on the cluster.\n\t\t\tprep := prepare.New(k8scli, t)\n\t\t\tprep.SetUp()\n\t\t\tdefer prep.TearDown()\n\n\t\t\t// Create the reitrever.\n\t\t\trt := &retrieve.Resource{\n\t\t\t\tListerWatcher: cache.NewListWatchFromClient(k8scli.CoreV1().RESTClient(), \"services\", prep.Namespace().Name, fields.Everything()),\n\t\t\t\tObject: &corev1.Service{},\n\t\t\t}\n\n\t\t\t// Call times are the number of times the handler should be called before sending the termination signal.\n\t\t\tstopCallTimes := len(test.addServices) + len(test.updateServices) + len(test.delServices)\n\t\t\tcalledTimes := 0\n\t\t\tvar mx sync.Mutex\n\n\t\t\t// Create the handler.\n\t\t\thl := &handler.HandlerFunc{\n\t\t\t\tAddFunc: func(_ context.Context, obj runtime.Object) error {\n\t\t\t\t\tmx.Lock()\n\t\t\t\t\tcalledTimes++\n\t\t\t\t\tmx.Unlock()\n\n\t\t\t\t\tsvc := obj.(*corev1.Service)\n\t\t\t\t\tgotAddedServices = append(gotAddedServices, svc.Name)\n\t\t\t\t\tif calledTimes >= stopCallTimes {\n\t\t\t\t\t\tclose(stopC)\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t},\n\t\t\t\tDeleteFunc: func(_ context.Context, id string) error {\n\t\t\t\t\tmx.Lock()\n\t\t\t\t\tcalledTimes++\n\t\t\t\t\tmx.Unlock()\n\n\t\t\t\t\t// Ignore namespace.\n\t\t\t\t\tid = strings.Split(id, \"/\")[1]\n\t\t\t\t\tgotDeletedServices = append(gotDeletedServices, id)\n\t\t\t\t\tif calledTimes >= stopCallTimes {\n\t\t\t\t\t\tclose(stopC)\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t},\n\t\t\t}\n\n\t\t\t// Create a Pod controller.\n\t\t\tctrl := controller.NewSequential(resync, hl, rt, nil, log.Dummy)\n\t\t\trequire.NotNil(ctrl, \"controller is required\")\n\t\t\tgo ctrl.Run(stopC)\n\n\t\t\t// Create the required services.\n\t\t\tfor _, svc := range test.addServices {\n\t\t\t\t_, err := k8scli.CoreV1().Services(prep.Namespace().Name).Create(svc)\n\t\t\t\tassert.NoError(err)\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t}\n\n\t\t\tfor _, svc := range test.updateServices {\n\t\t\t\torigSvc, err := k8scli.CoreV1().Services(prep.Namespace().Name).Get(svc, metav1.GetOptions{})\n\t\t\t\tif assert.NoError(err) {\n\t\t\t\t\t// Change something\n\t\t\t\t\torigSvc.Spec.Ports = append(origSvc.Spec.Ports, corev1.ServicePort{Name: \"updateport\", Port: 9876})\n\t\t\t\t\t_, err := k8scli.CoreV1().Services(prep.Namespace().Name).Update(origSvc)\n\t\t\t\t\tassert.NoError(err)\n\t\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Delete the required services.\n\t\t\tfor _, svc := range test.delServices {\n\t\t\t\terr := k8scli.CoreV1().Services(prep.Namespace().Name).Delete(svc, &metav1.DeleteOptions{})\n\t\t\t\tassert.NoError(err)\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t}\n\n\t\t\t// Wait until we have finished.\n\t\t\tselect {\n\t\t\t// Timeout.\n\t\t\tcase <-time.After(20 * time.Second):\n\t\t\t// Finished.\n\t\t\tcase <-stopC:\n\t\t\t}\n\n\t\t\t// Check.\n\t\t\tassert.Equal(test.expAddedServices, gotAddedServices)\n\t\t\tassert.Equal(test.expDeletedServices, gotDeletedServices)\n\t\t})\n\t}\n}", "func TestBatch(t *testing.T) {\n\tpre := config.Presubmit{\n\t\tName: \"pr-some-job\",\n\t\tAgent: \"jenkins\",\n\t\tContext: \"Some Job Context\",\n\t}\n\tfc := &fkc{\n\t\tprowjobs: []kube.ProwJob{pjutil.NewProwJob(pjutil.BatchSpec(pre, kube.Refs{\n\t\t\tOrg: \"o\",\n\t\t\tRepo: \"r\",\n\t\t\tBaseRef: \"master\",\n\t\t\tBaseSHA: \"123\",\n\t\t\tPulls: []kube.Pull{\n\t\t\t\t{\n\t\t\t\t\tNumber: 1,\n\t\t\t\t\tSHA: \"abc\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tNumber: 2,\n\t\t\t\t\tSHA: \"qwe\",\n\t\t\t\t},\n\t\t\t},\n\t\t}))},\n\t}\n\tjc := &fjc{}\n\tc := Controller{\n\t\tkc: fc,\n\t\tjc: jc,\n\t\tca: newFakeConfigAgent(t),\n\t\tpendingJobs: make(map[string]int),\n\t\tlock: sync.RWMutex{},\n\t}\n\n\tif err := c.Sync(); err != nil {\n\t\tt.Fatalf(\"Error on first sync: %v\", err)\n\t}\n\tif fc.prowjobs[0].Status.State != kube.PendingState {\n\t\tt.Fatalf(\"Wrong state: %v\", fc.prowjobs[0].Status.State)\n\t}\n\tif !fc.prowjobs[0].Status.JenkinsEnqueued {\n\t\tt.Fatal(\"Wrong enqueued.\")\n\t}\n\tjc.enqueued = true\n\tif err := c.Sync(); err != nil {\n\t\tt.Fatalf(\"Error on second sync: %v\", err)\n\t}\n\tif !fc.prowjobs[0].Status.JenkinsEnqueued {\n\t\tt.Fatal(\"Wrong enqueued steady state.\")\n\t}\n\tjc.enqueued = false\n\tif err := c.Sync(); err != nil {\n\t\tt.Fatalf(\"Error on third sync: %v\", err)\n\t}\n\tif fc.prowjobs[0].Status.JenkinsEnqueued {\n\t\tt.Fatal(\"Wrong enqueued after leaving queue.\")\n\t}\n\tjc.status = Status{Building: true}\n\tif err := c.Sync(); err != nil {\n\t\tt.Fatalf(\"Error on fourth sync: %v\", err)\n\t}\n\tif fc.prowjobs[0].Status.State != kube.PendingState {\n\t\tt.Fatalf(\"Wrong state: %v\", fc.prowjobs[0].Status.State)\n\t}\n\tjc.status = Status{\n\t\tBuilding: false,\n\t\tNumber: 42,\n\t}\n\tif err := c.Sync(); err != nil {\n\t\tt.Fatalf(\"Error on fifth sync: %v\", err)\n\t}\n\tif fc.prowjobs[0].Status.PodName != \"pr-some-job-42\" {\n\t\tt.Fatalf(\"Wrong PodName: %s\", fc.prowjobs[0].Status.PodName)\n\t}\n\tif fc.prowjobs[0].Status.State != kube.FailureState {\n\t\tt.Fatalf(\"Wrong state: %v\", fc.prowjobs[0].Status.State)\n\t}\n\n\t// This is what the SQ reads.\n\tif fc.prowjobs[0].Spec.Context != \"Some Job Context\" {\n\t\tt.Fatalf(\"Wrong context: %v\", fc.prowjobs[0].Spec.Context)\n\t}\n}", "func (m *MockDeploymentControllerFactory) Build(mgr mc_manager.AsyncManager, clusterName string) (controller0.DeploymentController, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", mgr, clusterName)\n\tret0, _ := ret[0].(controller0.DeploymentController)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestCancelManyJobs(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping integration tests in short mode\")\n\t}\n\n\tt.Parallel()\n\tc, _ := minikubetestenv.AcquireCluster(t)\n\n\t// Create an input repo\n\trepo := tu.UniqueString(\"TestCancelManyJobs\")\n\trequire.NoError(t, c.CreateRepo(pfs.DefaultProjectName, repo))\n\n\t// Create sleep pipeline\n\tpipeline := tu.UniqueString(\"pipeline\")\n\trequire.NoError(t, c.CreatePipeline(pfs.DefaultProjectName,\n\t\tpipeline,\n\t\t\"\",\n\t\t[]string{\"sleep\", \"600\"},\n\t\tnil,\n\t\t&pps.ParallelismSpec{\n\t\t\tConstant: 1,\n\t\t},\n\t\tclient.NewPFSInput(pfs.DefaultProjectName, repo, \"/*\"),\n\t\t\"\",\n\t\tfalse,\n\t))\n\n\t// Create 10 input commits, to spawn 10 jobs\n\tvar commits []*pfs.Commit\n\tfor i := 0; i < 10; i++ {\n\t\tcommit, err := c.StartCommit(pfs.DefaultProjectName, repo, \"master\")\n\t\trequire.NoError(t, c.PutFile(commit, \"file\", strings.NewReader(\"foo\")))\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, c.FinishCommit(pfs.DefaultProjectName, repo, commit.Branch.Name, commit.Id))\n\t\tcommits = append(commits, commit)\n\t}\n\n\t// For each expected job: watch to make sure the input job comes up, make\n\t// sure that it's the only job running, then cancel it\n\tfor _, commit := range commits {\n\t\t// Wait until PPS has started processing commit\n\t\tvar jobInfo *pps.JobInfo\n\t\trequire.NoErrorWithinT(t, 30*time.Second, func() error {\n\t\t\treturn backoff.Retry(func() error {\n\t\t\t\tjobInfos, err := c.ListJob(pfs.DefaultProjectName, pipeline, []*pfs.Commit{commit}, -1, true)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif len(jobInfos) != 1 {\n\t\t\t\t\treturn errors.Errorf(\"Expected one job, but got %d: %v\", len(jobInfos), jobInfos)\n\t\t\t\t}\n\t\t\t\tjobInfo = jobInfos[0]\n\t\t\t\treturn nil\n\t\t\t}, backoff.NewTestingBackOff())\n\t\t})\n\n\t\t// Stop the job\n\t\trequire.NoError(t, c.StopJob(pfs.DefaultProjectName, jobInfo.Job.Pipeline.Name, jobInfo.Job.Id))\n\n\t\t// Check that the job is now killed\n\t\trequire.NoErrorWithinT(t, 30*time.Second, func() error {\n\t\t\treturn backoff.Retry(func() error {\n\t\t\t\t// TODO(msteffen): once github.com/pachyderm/pachyderm/v2/pull/2642 is\n\t\t\t\t// submitted, change ListJob here to filter on commit1 as the input commit,\n\t\t\t\t// rather than inspecting the input in the test\n\t\t\t\tupdatedJobInfo, err := c.InspectJob(pfs.DefaultProjectName, jobInfo.Job.Pipeline.Name, jobInfo.Job.Id, false)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif updatedJobInfo.State != pps.JobState_JOB_KILLED {\n\t\t\t\t\treturn errors.Errorf(\"job %s is still running, but should be KILLED\", jobInfo.Job.Id)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}, backoff.NewTestingBackOff())\n\t\t})\n\t}\n}", "func OperatorRunningTest(bundle *apimanifests.Bundle) scapiv1alpha3.TestStatus {\n\tr := scapiv1alpha3.TestResult{}\n\tr.Name = OperatorRunningTestName\n\tr.State = scapiv1alpha3.PassState\n\tr.Errors = make([]string, 0)\n\tr.Suggestions = make([]string, 0)\n\n\t//\ttime.Sleep(20 * time.Second)\n\n\t//clientset, config, err := util.GetKubeClient()\n\tclientset, _, err := util.GetKubeClient()\n\tif err != nil {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, \"unable to connect to kube\")\n\t\treturn wrapResult(r)\n\t}\n\n\tns := \"tekton-pipelines\"\n\n\tnamespaces, err := clientset.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, fmt.Sprintf(\"error getting namespaces %s\", err.Error()))\n\t\treturn wrapResult(r)\n\t}\n\n\tfor i := 0; i < len(namespaces.Items); i++ {\n\t\tn := namespaces.Items[i]\n\t\tif n.Name == \"openshift-pipelines\" {\n\t\t\tns = \"openshift-pipelines\"\n\t\t\tbreak\n\t\t}\n\t\tif n.Name == \"tekton-pipelines\" {\n\t\t\tns = \"tekton-pipelines\"\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvar pods *corev1.PodList\n\tvar p corev1.Pod\n\n\t// look for a pod with this label\n\t//app=tekton-pipelines-controller\n\tselector := \"app=tekton-pipelines-controller\"\n\tlistOpts := metav1.ListOptions{LabelSelector: selector}\n\tpods, err = clientset.CoreV1().Pods(ns).List(context.TODO(), listOpts)\n\tif err != nil {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, fmt.Sprintf(\"error getting pods %s\", err.Error()))\n\t\treturn wrapResult(r)\n\t}\n\tif len(pods.Items) == 0 {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, \"tekton-pipelines-controller pod not found\")\n\t\treturn wrapResult(r)\n\t}\n\tp = pods.Items[0]\n\tif p.Status.Phase != corev1.PodRunning {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, \"tekton-pipelines-controller pod not running\")\n\t\treturn wrapResult(r)\n\t}\n\n\t// look for a pod with this label\n\t//app=tekton-pipelines-webhook\n\tselector = \"app=tekton-pipelines-webhook\"\n\tlistOpts = metav1.ListOptions{LabelSelector: selector}\n\tpods, err = clientset.CoreV1().Pods(ns).List(context.TODO(), listOpts)\n\tif err != nil {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, fmt.Sprintf(\"error getting pods %s\", err.Error()))\n\t\treturn wrapResult(r)\n\t}\n\tif len(pods.Items) == 0 {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, \"tekton-pipelines-webhook pod not found\")\n\t\treturn wrapResult(r)\n\t}\n\n\tp = pods.Items[0]\n\n\tif p.Status.Phase != corev1.PodRunning {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, \"tekton-pipelines-webhook pod not running\")\n\t\treturn wrapResult(r)\n\t}\n\n\treturn wrapResult(r)\n}", "func TestKnativeServingDeploymentRecreationReady(t *testing.T) {\n\tcancel := logstream.Start(t)\n\tdefer cancel()\n\tclients := Setup(t)\n\n\tdpList, err := clients.KubeClient.Kube.AppsV1().Deployments(test.ServingOperatorNamespace).List(metav1.ListOptions{})\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get any deployment under the namespace %q: %v\",\n\t\t\ttest.ServingOperatorNamespace, err)\n\t}\n\t// Delete the deployments one by one to see if they will be recreated.\n\tfor _, deployment := range dpList.Items {\n\t\tif err := clients.KubeClient.Kube.AppsV1().Deployments(deployment.Namespace).Delete(deployment.Name,\n\t\t\t&metav1.DeleteOptions{}); err != nil {\n\t\t\tt.Fatalf(\"Failed to delete deployment %s/%s: %v\", deployment.Namespace, deployment.Name, err)\n\t\t}\n\t\tif _, err = resources.WaitForDeploymentAvailable(clients, deployment.Name, deployment.Namespace,\n\t\t\tresources.IsDeploymentAvailable); err != nil {\n\t\t\tt.Fatalf(\"The deployment %s/%s failed to reach the desired state: %v\",\n\t\t\t\tdeployment.Namespace, deployment.Name, err)\n\t\t}\n\t\tif _, err := resources.WaitForKnativeServingState(clients.KnativeServingAlphaClient, test.ServingOperatorName,\n\t\t\tresources.IsKnativeServingReady); err != nil {\n\t\t\tt.Fatalf(\"KnativeService %q failed to reach the desired state: %v\", test.ServingOperatorName, err)\n\t\t}\n\t\tt.Logf(\"The deployment %s/%s reached the desired state.\", deployment.Namespace, deployment.Name)\n\t}\n}", "func runSyncTests(t *testing.T, ctx context.Context, tests []controllerTest, storageClasses []*storage.StorageClass, pods []*v1.Pod) {\n\tdoit := func(t *testing.T, test controllerTest) {\n\t\t// Initialize the controller\n\t\tclient := &fake.Clientset{}\n\t\tctrl, err := newTestController(ctx, client, nil, true)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %q construct persistent volume failed: %v\", test.name, err)\n\t\t}\n\t\treactor := newVolumeReactor(ctx, client, ctrl, nil, nil, test.errors)\n\t\tfor _, claim := range test.initialClaims {\n\t\t\tif metav1.HasAnnotation(claim.ObjectMeta, annSkipLocalStore) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tctrl.claims.Add(claim)\n\t\t}\n\t\tfor _, volume := range test.initialVolumes {\n\t\t\tif metav1.HasAnnotation(volume.ObjectMeta, annSkipLocalStore) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tctrl.volumes.store.Add(volume)\n\t\t}\n\t\treactor.AddClaims(test.initialClaims)\n\t\treactor.AddVolumes(test.initialVolumes)\n\n\t\t// Inject classes into controller via a custom lister.\n\t\tindexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})\n\t\tfor _, class := range storageClasses {\n\t\t\tindexer.Add(class)\n\t\t}\n\t\tctrl.classLister = storagelisters.NewStorageClassLister(indexer)\n\n\t\tpodIndexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})\n\t\tfor _, pod := range pods {\n\t\t\tpodIndexer.Add(pod)\n\t\t\tctrl.podIndexer.Add(pod)\n\t\t}\n\t\tctrl.podLister = corelisters.NewPodLister(podIndexer)\n\n\t\t// Run the tested functions\n\t\terr = test.test(ctrl, reactor.VolumeReactor, test)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test %q failed: %v\", test.name, err)\n\t\t}\n\n\t\t// Wait for the target state\n\t\terr = reactor.waitTest(test)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test %q failed: %v\", test.name, err)\n\t\t}\n\n\t\tevaluateTestResults(ctx, ctrl, reactor.VolumeReactor, test, t)\n\t}\n\n\tfor _, test := range tests {\n\t\ttest := test\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tdoit(t, test)\n\t\t})\n\t}\n}", "func (m *MockServiceControllerFactory) Build(mgr mc_manager.AsyncManager, clusterName string) (controller1.ServiceController, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", mgr, clusterName)\n\tret0, _ := ret[0].(controller1.ServiceController)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func StartControllers(s *options.MCMServer,\n\tcontrolCoreKubeconfig *rest.Config,\n\ttargetCoreKubeconfig *rest.Config,\n\tcontrolMachineClientBuilder machinecontroller.ClientBuilder,\n\tcontrolCoreClientBuilder corecontroller.ClientBuilder,\n\ttargetCoreClientBuilder corecontroller.ClientBuilder,\n\trecorder record.EventRecorder,\n\tstop <-chan struct{}) error {\n\n\tklog.V(5).Info(\"Getting available resources\")\n\tavailableResources, err := getAvailableResources(controlCoreClientBuilder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontrolMachineClient := controlMachineClientBuilder.ClientOrDie(controllerManagerAgentName).MachineV1alpha1()\n\n\tcontrolCoreKubeconfig = rest.AddUserAgent(controlCoreKubeconfig, controllerManagerAgentName)\n\tcontrolCoreClient, err := kubernetes.NewForConfig(controlCoreKubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\n\ttargetCoreKubeconfig = rest.AddUserAgent(targetCoreKubeconfig, controllerManagerAgentName)\n\ttargetCoreClient, err := kubernetes.NewForConfig(targetCoreKubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\n\tif availableResources[machineGVR] || availableResources[machineSetGVR] || availableResources[machineDeploymentGVR] {\n\t\tklog.V(5).Infof(\"Creating shared informers; resync interval: %v\", s.MinResyncPeriod)\n\n\t\tcontrolMachineInformerFactory := machineinformers.NewFilteredSharedInformerFactory(\n\t\t\tcontrolMachineClientBuilder.ClientOrDie(\"control-machine-shared-informers\"),\n\t\t\ts.MinResyncPeriod.Duration,\n\t\t\ts.Namespace,\n\t\t\tnil,\n\t\t)\n\n\t\tcontrolCoreInformerFactory := coreinformers.NewFilteredSharedInformerFactory(\n\t\t\tcontrolCoreClientBuilder.ClientOrDie(\"control-core-shared-informers\"),\n\t\t\ts.MinResyncPeriod.Duration,\n\t\t\ts.Namespace,\n\t\t\tnil,\n\t\t)\n\n\t\ttargetCoreInformerFactory := coreinformers.NewSharedInformerFactory(\n\t\t\ttargetCoreClientBuilder.ClientOrDie(\"target-core-shared-informers\"),\n\t\t\ts.MinResyncPeriod.Duration,\n\t\t)\n\n\t\t// All shared informers are v1alpha1 API level\n\t\tmachineSharedInformers := controlMachineInformerFactory.Machine().V1alpha1()\n\n\t\tklog.V(5).Infof(\"Creating controllers...\")\n\t\tmcmcontroller, err := mcmcontroller.NewController(\n\t\t\ts.Namespace,\n\t\t\tcontrolMachineClient,\n\t\t\tcontrolCoreClient,\n\t\t\ttargetCoreClient,\n\t\t\ttargetCoreInformerFactory.Core().V1().PersistentVolumeClaims(),\n\t\t\ttargetCoreInformerFactory.Core().V1().PersistentVolumes(),\n\t\t\tcontrolCoreInformerFactory.Core().V1().Secrets(),\n\t\t\ttargetCoreInformerFactory.Core().V1().Nodes(),\n\t\t\tmachineSharedInformers.OpenStackMachineClasses(),\n\t\t\tmachineSharedInformers.AWSMachineClasses(),\n\t\t\tmachineSharedInformers.AzureMachineClasses(),\n\t\t\tmachineSharedInformers.GCPMachineClasses(),\n\t\t\tmachineSharedInformers.AlicloudMachineClasses(),\n\t\t\tmachineSharedInformers.PacketMachineClasses(),\n\t\t\tmachineSharedInformers.Machines(),\n\t\t\tmachineSharedInformers.MachineSets(),\n\t\t\tmachineSharedInformers.MachineDeployments(),\n\t\t\trecorder,\n\t\t\ts.SafetyOptions,\n\t\t\ts.NodeConditions,\n\t\t\ts.BootstrapTokenAuthExtraGroups,\n\t\t\ts.DeleteMigratedMachineClass,\n\t\t\ts.AutoscalerScaleDownAnnotationDuringRollout,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.V(1).Info(\"Starting shared informers\")\n\n\t\tcontrolMachineInformerFactory.Start(stop)\n\t\tcontrolCoreInformerFactory.Start(stop)\n\t\ttargetCoreInformerFactory.Start(stop)\n\n\t\tklog.V(5).Info(\"Running controller\")\n\t\tgo mcmcontroller.Run(int(s.ConcurrentNodeSyncs), stop)\n\n\t} else {\n\t\treturn fmt.Errorf(\"unable to start machine controller: API GroupVersion %q or %q or %q is not available; \\nFound: %#v\", machineGVR, machineSetGVR, machineDeploymentGVR, availableResources)\n\t}\n\n\tselect {}\n}", "func TestCmdDeploy_latestConcurrentRejection(t *testing.T) {\n\tvar existingDeployment *kapi.ReplicationController\n\n\tcommandClient := &deployCommandClientImpl{\n\t\tGetDeploymentFn: func(namespace, name string) (*kapi.ReplicationController, error) {\n\t\t\treturn existingDeployment, nil\n\t\t},\n\t\tUpdateDeploymentConfigFn: func(config *deployapi.DeploymentConfig) (*deployapi.DeploymentConfig, error) {\n\t\t\tt.Fatalf(\"unexpected call to UpdateDeploymentConfig\")\n\t\t\treturn nil, nil\n\t\t},\n\t\tUpdateDeploymentFn: func(deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\tt.Fatalf(\"unexpected call to UpdateDeployment for %s/%s\", deployment.Namespace, deployment.Name)\n\t\t\treturn nil, nil\n\t\t},\n\t}\n\n\tc := &deployLatestCommand{client: commandClient}\n\n\tinvalidStatusList := []deployapi.DeploymentStatus{\n\t\tdeployapi.DeploymentStatusNew,\n\t\tdeployapi.DeploymentStatusPending,\n\t\tdeployapi.DeploymentStatusRunning,\n\t}\n\n\tfor _, status := range invalidStatusList {\n\t\tconfig := deploytest.OkDeploymentConfig(1)\n\t\texistingDeployment = deploymentFor(config, status)\n\t\terr := c.deploy(config, ioutil.Discard)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"expected an error starting deployment with existing status %s\", status)\n\t\t}\n\t}\n}", "func TestHandle_updateOk(t *testing.T) {\n\tvar (\n\t\tconfig *deployapi.DeploymentConfig\n\t\tdeployed *kapi.ReplicationController\n\t\texistingDeployments *kapi.ReplicationControllerList\n\t)\n\n\tcontroller := &DeploymentConfigController{\n\t\tmakeDeployment: func(config *deployapi.DeploymentConfig) (*kapi.ReplicationController, error) {\n\t\t\treturn deployutil.MakeDeployment(config, api.Codec)\n\t\t},\n\t\tdeploymentClient: &deploymentClientImpl{\n\t\t\tcreateDeploymentFunc: func(namespace string, deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\t\tdeployed = deployment\n\t\t\t\treturn deployment, nil\n\t\t\t},\n\t\t\tlistDeploymentsForConfigFunc: func(namespace, configName string) (*kapi.ReplicationControllerList, error) {\n\t\t\t\treturn existingDeployments, nil\n\t\t\t},\n\t\t\tupdateDeploymentFunc: func(namespace string, deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\t\tt.Fatalf(\"unexpected update call with deployment %v\", deployment)\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t\trecorder: &record.FakeRecorder{},\n\t}\n\n\ttype existing struct {\n\t\tversion int\n\t\treplicas int\n\t\tstatus deployapi.DeploymentStatus\n\t}\n\n\ttype scenario struct {\n\t\tversion int\n\t\texpectedReplicas int\n\t\texisting []existing\n\t}\n\n\tscenarios := []scenario{\n\t\t{1, 1, []existing{}},\n\t\t{2, 1, []existing{\n\t\t\t{1, 1, deployapi.DeploymentStatusComplete},\n\t\t}},\n\t\t{3, 4, []existing{\n\t\t\t{1, 0, deployapi.DeploymentStatusComplete},\n\t\t\t{2, 4, deployapi.DeploymentStatusComplete},\n\t\t}},\n\t\t{3, 4, []existing{\n\t\t\t{1, 4, deployapi.DeploymentStatusComplete},\n\t\t\t{2, 1, deployapi.DeploymentStatusFailed},\n\t\t}},\n\t\t{4, 2, []existing{\n\t\t\t{1, 0, deployapi.DeploymentStatusComplete},\n\t\t\t{2, 0, deployapi.DeploymentStatusFailed},\n\t\t\t{3, 2, deployapi.DeploymentStatusComplete},\n\t\t}},\n\t\t// Scramble the order of the previous to ensure we still get it right.\n\t\t{4, 2, []existing{\n\t\t\t{2, 0, deployapi.DeploymentStatusFailed},\n\t\t\t{3, 2, deployapi.DeploymentStatusComplete},\n\t\t\t{1, 0, deployapi.DeploymentStatusComplete},\n\t\t}},\n\t}\n\n\tfor _, scenario := range scenarios {\n\t\tdeployed = nil\n\t\tconfig = deploytest.OkDeploymentConfig(scenario.version)\n\t\texistingDeployments = &kapi.ReplicationControllerList{}\n\t\tfor _, e := range scenario.existing {\n\t\t\td, _ := deployutil.MakeDeployment(deploytest.OkDeploymentConfig(e.version), api.Codec)\n\t\t\td.Spec.Replicas = e.replicas\n\t\t\td.Annotations[deployapi.DeploymentStatusAnnotation] = string(e.status)\n\t\t\texistingDeployments.Items = append(existingDeployments.Items, *d)\n\t\t}\n\t\terr := controller.Handle(config)\n\n\t\tif deployed == nil {\n\t\t\tt.Fatalf(\"expected a deployment\")\n\t\t}\n\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t\t}\n\n\t\tdesired, hasDesired := deployutil.DeploymentDesiredReplicas(deployed)\n\t\tif !hasDesired {\n\t\t\tt.Fatalf(\"expected desired replicas\")\n\t\t}\n\t\tif e, a := scenario.expectedReplicas, desired; e != a {\n\t\t\tt.Errorf(\"expected desired replicas %d, got %d\", e, a)\n\t\t}\n\t}\n}", "func (t *JobUpgradeTest) Test(f *framework.Framework, done <-chan struct{}, upgrade UpgradeType) {\n\t<-done\n\tBy(\"Ensuring active pods == parallelism\")\n\trunning, err := framework.CheckForAllJobPodsRunning(f.ClientSet, t.namespace, t.job.Name, 2)\n\tExpect(err).NotTo(HaveOccurred())\n\tExpect(running).To(BeTrue())\n}", "func TestProject_CreateProject_PollsUntilOperationIsSuccessful(t *testing.T) {\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\n\tcoreClient := azdosdkmocks.NewMockCoreClient(ctrl)\n\toperationsClient := azdosdkmocks.NewMockOperationsClient(ctrl)\n\tclients := &client.AggregatedClient{\n\t\tCoreClient: coreClient,\n\t\tOperationsClient: operationsClient,\n\t\tCtx: context.Background(),\n\t}\n\n\texpectedProjectCreateArgs := core.QueueCreateProjectArgs{ProjectToCreate: &testProject}\n\tmockedOperationReference := operations.OperationReference{Id: &testID}\n\texpectedOperationArgs := operations.GetOperationArgs{OperationId: &testID}\n\n\tcoreClient.\n\t\tEXPECT().\n\t\tQueueCreateProject(clients.Ctx, expectedProjectCreateArgs).\n\t\tReturn(&mockedOperationReference, nil).\n\t\tTimes(1)\n\n\tfirstStatus := operationWithStatus(operations.OperationStatusValues.InProgress)\n\tfirstPoll := operationsClient.\n\t\tEXPECT().\n\t\tGetOperation(clients.Ctx, expectedOperationArgs).\n\t\tReturn(&firstStatus, nil)\n\n\tsecondStatus := operationWithStatus(operations.OperationStatusValues.Succeeded)\n\tsecondPoll := operationsClient.\n\t\tEXPECT().\n\t\tGetOperation(clients.Ctx, expectedOperationArgs).\n\t\tReturn(&secondStatus, nil)\n\n\tgomock.InOrder(firstPoll, secondPoll)\n\n\terr := createProject(clients, &testProject, 10*time.Minute)\n\trequire.Equal(t, nil, err)\n}", "func TestConfigController(t *testing.T) {\n\tvar (\n\t\tname = \"common-service\"\n\t\tnamespace = \"ibm-common-service\"\n\t)\n\n\treq := getReconcileRequest(name, namespace)\n\tr := getReconciler(name, namespace)\n\n\tinitReconcile(t, r, req)\n\n}", "func SetupAddControllers(k kubernetes.Interface, namespace string) kubernetes.Interface {\n\td1 := MockDeploy()\n\tif _, err := k.AppsV1().Deployments(namespace).Create(&d1); err != nil {\n\t\tpanic(err)\n\t}\n\n\ts1 := MockStatefulSet()\n\tif _, err := k.AppsV1().StatefulSets(namespace).Create(&s1); err != nil {\n\t\tpanic(err)\n\t}\n\n\tds1 := MockDaemonSet()\n\tif _, err := k.AppsV1().DaemonSets(namespace).Create(&ds1); err != nil {\n\t\tpanic(err)\n\t}\n\n\tj1 := MockJob()\n\tif _, err := k.BatchV1().Jobs(namespace).Create(&j1); err != nil {\n\t\tpanic(err)\n\t}\n\n\tcj1 := MockCronJob()\n\tif _, err := k.BatchV1beta1().CronJobs(namespace).Create(&cj1); err != nil {\n\t\tpanic(err)\n\t}\n\n\trc1 := MockReplicationController()\n\tif _, err := k.CoreV1().ReplicationControllers(namespace).Create(&rc1); err != nil {\n\t\tpanic(err)\n\t}\n\n\tp1 := MockNakedPod()\n\tif _, err := k.CoreV1().Pods(namespace).Create(&p1); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn k\n}", "func TestCreate(t *testing.T) {\n\t// set up fake web server\n\tr := gin.Default()\n\tbuilds.Mount(r)\n\n\t// test artifacts send to callback URL\n\tr.POST(\"/callback\", func(c *gin.Context) {\n\t\tr, _, err := c.Request.FormFile(\"file\")\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tres, err := testhelper.ShouldIncludeFileInTar(r, \"app\")\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif !res {\n\t\t\tt.Error(\"artifact should be found\")\n\t\t}\n\t})\n\n\t// run web server\n\ts := httptest.NewServer(r)\n\tdefer s.Close()\n\n\t// prepare jobqueue\n\tgo jobqueue.Wait()\n\tdefer jobqueue.Close()\n\n\t// send request\n\tbuild, err := controller_helper.Create(s.URL, \"./example/app.tar\", s.URL+\"/callback\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// wait for finishing build\n\texitCode := make(chan int, 1)\n\tgo func() {\n\t\tfor {\n\t\t\tif res, err := controller_helper.Show(s.URL, build.Id); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t} else {\n\t\t\t\tif res.Job.Finished {\n\t\t\t\t\texitCode <- res.Job.ExitCode\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\ttime.Sleep(200 * time.Millisecond)\n\t\t}\n\t}()\n\n\t// timeout after three seconds\n\tselect {\n\tcase c := <-exitCode:\n\t\tif c != 0 {\n\t\t\tt.Fatal(c)\n\t\t}\n\tcase <-time.After(3 * time.Second):\n\t\tt.Fatal(\"the build should be finished in a few second\")\n\t}\n\n\treq, err := testhelper.Get(s.URL+\"/builds/\"+build.Id+\"/log.txt\", map[string]string{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tc := http.Client{}\n\tres, err := c.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\n\tif b, err := ioutil.ReadAll(res.Body); err != nil {\n\t\tt.Fatal(err)\n\t} else if !strings.Contains(string(b), \"make\") {\n\t\tt.Fatal(\"example build shuold start with make command\")\n\t}\n}", "func TestHandle_existingDeployments(t *testing.T) {\n\tvar updatedDeployments []kapi.ReplicationController\n\tvar (\n\t\tconfig *deployapi.DeploymentConfig\n\t\tdeployed *kapi.ReplicationController\n\t\texistingDeployments *kapi.ReplicationControllerList\n\t)\n\n\tcontroller := &DeploymentConfigController{\n\t\tmakeDeployment: func(config *deployapi.DeploymentConfig) (*kapi.ReplicationController, error) {\n\t\t\treturn deployutil.MakeDeployment(config, api.Codec)\n\t\t},\n\t\tdeploymentClient: &deploymentClientImpl{\n\t\t\tcreateDeploymentFunc: func(namespace string, deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\t\tdeployed = deployment\n\t\t\t\treturn deployment, nil\n\t\t\t},\n\t\t\tlistDeploymentsForConfigFunc: func(namespace, configName string) (*kapi.ReplicationControllerList, error) {\n\t\t\t\treturn existingDeployments, nil\n\t\t\t},\n\t\t\tupdateDeploymentFunc: func(namespace string, deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\t\tupdatedDeployments = append(updatedDeployments, *deployment)\n\t\t\t\t//t.Fatalf(\"unexpected update call with deployment %v\", deployment)\n\t\t\t\treturn deployment, nil\n\t\t\t},\n\t\t},\n\t\trecorder: &record.FakeRecorder{},\n\t}\n\n\ttype existing struct {\n\t\tversion int\n\t\tstatus deployapi.DeploymentStatus\n\t\tshouldCancel bool\n\t}\n\n\ttype scenario struct {\n\t\tversion int\n\t\texisting []existing\n\t\terrorType reflect.Type\n\t\texpectDeployment bool\n\t}\n\n\ttransientErrorType := reflect.TypeOf(transientError(\"\"))\n\tscenarios := []scenario{\n\t\t// No existing deployments\n\t\t{1, []existing{}, nil, true},\n\t\t// A single existing completed deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusComplete, false}}, nil, true},\n\t\t// A single existing failed deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusFailed, false}}, nil, true},\n\t\t// Multiple existing completed/failed deployments\n\t\t{3, []existing{{2, deployapi.DeploymentStatusFailed, false}, {1, deployapi.DeploymentStatusComplete, false}}, nil, true},\n\n\t\t// A single existing deployment in the default state\n\t\t{2, []existing{{1, \"\", false}}, transientErrorType, false},\n\t\t// A single existing new deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusNew, false}}, transientErrorType, false},\n\t\t// A single existing pending deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusPending, false}}, transientErrorType, false},\n\t\t// A single existing running deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusRunning, false}}, transientErrorType, false},\n\t\t// Multiple existing deployments with one in new/pending/running\n\t\t{4, []existing{{3, deployapi.DeploymentStatusRunning, false}, {2, deployapi.DeploymentStatusComplete, false}, {1, deployapi.DeploymentStatusFailed, false}}, transientErrorType, false},\n\n\t\t// Latest deployment exists and has already failed/completed\n\t\t{2, []existing{{2, deployapi.DeploymentStatusFailed, false}, {1, deployapi.DeploymentStatusComplete, false}}, nil, false},\n\t\t// Latest deployment exists and is in new/pending/running state\n\t\t{2, []existing{{2, deployapi.DeploymentStatusRunning, false}, {1, deployapi.DeploymentStatusComplete, false}}, nil, false},\n\n\t\t// Multiple existing deployments with more than one in new/pending/running\n\t\t{4, []existing{{3, deployapi.DeploymentStatusNew, false}, {2, deployapi.DeploymentStatusRunning, true}, {1, deployapi.DeploymentStatusFailed, false}}, transientErrorType, false},\n\t\t// Multiple existing deployments with more than one in new/pending/running\n\t\t// Latest deployment has already failed\n\t\t{6, []existing{{5, deployapi.DeploymentStatusFailed, false}, {4, deployapi.DeploymentStatusRunning, false}, {3, deployapi.DeploymentStatusNew, true}, {2, deployapi.DeploymentStatusComplete, false}, {1, deployapi.DeploymentStatusNew, true}}, transientErrorType, false},\n\t}\n\n\tfor _, scenario := range scenarios {\n\t\tupdatedDeployments = []kapi.ReplicationController{}\n\t\tdeployed = nil\n\t\tconfig = deploytest.OkDeploymentConfig(scenario.version)\n\t\texistingDeployments = &kapi.ReplicationControllerList{}\n\t\tfor _, e := range scenario.existing {\n\t\t\td, _ := deployutil.MakeDeployment(deploytest.OkDeploymentConfig(e.version), api.Codec)\n\t\t\tif e.status != \"\" {\n\t\t\t\td.Annotations[deployapi.DeploymentStatusAnnotation] = string(e.status)\n\t\t\t}\n\t\t\texistingDeployments.Items = append(existingDeployments.Items, *d)\n\t\t}\n\t\terr := controller.Handle(config)\n\n\t\tif scenario.expectDeployment && deployed == nil {\n\t\t\tt.Fatalf(\"expected a deployment\")\n\t\t}\n\n\t\tif scenario.errorType == nil {\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tif err == nil {\n\t\t\t\tt.Fatalf(\"expected error\")\n\t\t\t}\n\t\t\tif reflect.TypeOf(err) != scenario.errorType {\n\t\t\t\tt.Fatalf(\"error expected: %s, got: %s\", scenario.errorType, reflect.TypeOf(err))\n\t\t\t}\n\t\t}\n\n\t\texpectedCancellations := []int{}\n\t\tactualCancellations := []int{}\n\t\tfor _, e := range scenario.existing {\n\t\t\tif e.shouldCancel {\n\t\t\t\texpectedCancellations = append(expectedCancellations, e.version)\n\t\t\t}\n\t\t}\n\t\tfor _, d := range updatedDeployments {\n\t\t\tactualCancellations = append(actualCancellations, deployutil.DeploymentVersionFor(&d))\n\t\t}\n\n\t\tsort.Ints(actualCancellations)\n\t\tsort.Ints(expectedCancellations)\n\t\tif !reflect.DeepEqual(actualCancellations, expectedCancellations) {\n\t\t\tt.Fatalf(\"expected cancellations: %v, actual: %v\", expectedCancellations, actualCancellations)\n\t\t}\n\t}\n}", "func TestApplyStatus(t *testing.T) {\n\tserver, err := apiservertesting.StartTestServer(t, apiservertesting.NewDefaultTestServerOptions(), []string{\"--disable-admission-plugins\", \"ServiceAccount,TaintNodesByCondition\"}, framework.SharedEtcd())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer server.TearDownFn()\n\n\tclient, err := kubernetes.NewForConfig(server.ClientConfig)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdynamicClient, err := dynamic.NewForConfig(server.ClientConfig)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// create CRDs so we can make sure that custom resources do not get lost\n\tetcd.CreateTestCRDs(t, apiextensionsclientset.NewForConfigOrDie(server.ClientConfig), false, etcd.GetCustomResourceDefinitionData()...)\n\tif _, err := client.CoreV1().Namespaces().Create(context.TODO(), &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: testNamespace}}, metav1.CreateOptions{}); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcreateData := etcd.GetEtcdStorageData()\n\n\t// gather resources to test\n\t_, resourceLists, err := client.Discovery().ServerGroupsAndResources()\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get ServerGroupsAndResources with error: %+v\", err)\n\t}\n\n\tfor _, resourceList := range resourceLists {\n\t\tfor _, resource := range resourceList.APIResources {\n\t\t\tif !strings.HasSuffix(resource.Name, \"/status\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmapping, err := createMapping(resourceList.GroupVersion, resource)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tt.Run(mapping.Resource.String(), func(t *testing.T) {\n\t\t\t\t// both spec and status get wiped for CSRs,\n\t\t\t\t// nothing is expected to be managed for it, skip it\n\t\t\t\tif mapping.Resource.Resource == \"certificatesigningrequests\" {\n\t\t\t\t\tt.Skip()\n\t\t\t\t}\n\n\t\t\t\tstatus, ok := statusData[mapping.Resource]\n\t\t\t\tif !ok {\n\t\t\t\t\tstatus = statusDefault\n\t\t\t\t}\n\t\t\t\tnewResource, ok := createData[mapping.Resource]\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Fatalf(\"no test data for %s. Please add a test for your new type to etcd.GetEtcdStorageData().\", mapping.Resource)\n\t\t\t\t}\n\t\t\t\tnewObj := unstructured.Unstructured{}\n\t\t\t\tif err := json.Unmarshal([]byte(newResource.Stub), &newObj.Object); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tnamespace := testNamespace\n\t\t\t\tif mapping.Scope == meta.RESTScopeRoot {\n\t\t\t\t\tnamespace = \"\"\n\t\t\t\t}\n\t\t\t\tname := newObj.GetName()\n\n\t\t\t\t// etcd test stub data doesn't contain apiVersion/kind (!), but apply requires it\n\t\t\t\tnewObj.SetGroupVersionKind(mapping.GroupVersionKind)\n\n\t\t\t\trsc := dynamicClient.Resource(mapping.Resource).Namespace(namespace)\n\t\t\t\t// apply to create\n\t\t\t\t_, err = rsc.Apply(context.TODO(), name, &newObj, metav1.ApplyOptions{FieldManager: \"create_test\"})\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tstatusObj := unstructured.Unstructured{}\n\t\t\t\tif err := json.Unmarshal([]byte(status), &statusObj.Object); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t\tstatusObj.SetAPIVersion(mapping.GroupVersionKind.GroupVersion().String())\n\t\t\t\tstatusObj.SetKind(mapping.GroupVersionKind.Kind)\n\t\t\t\tstatusObj.SetName(name)\n\n\t\t\t\tobj, err := dynamicClient.\n\t\t\t\t\tResource(mapping.Resource).\n\t\t\t\t\tNamespace(namespace).\n\t\t\t\t\tApplyStatus(context.TODO(), name, &statusObj, metav1.ApplyOptions{FieldManager: \"apply_status_test\", Force: true})\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatalf(\"Failed to apply: %v\", err)\n\t\t\t\t}\n\n\t\t\t\taccessor, err := meta.Accessor(obj)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatalf(\"Failed to get meta accessor: %v:\\n%v\", err, obj)\n\t\t\t\t}\n\n\t\t\t\tmanagedFields := accessor.GetManagedFields()\n\t\t\t\tif managedFields == nil {\n\t\t\t\t\tt.Fatal(\"Empty managed fields\")\n\t\t\t\t}\n\t\t\t\tif !findManager(managedFields, \"apply_status_test\") {\n\t\t\t\t\tt.Fatalf(\"Couldn't find apply_status_test: %v\", managedFields)\n\t\t\t\t}\n\t\t\t\tif !findManager(managedFields, \"create_test\") {\n\t\t\t\t\tt.Fatalf(\"Couldn't find create_test: %v\", managedFields)\n\t\t\t\t}\n\n\t\t\t\tif err := rsc.Delete(context.TODO(), name, *metav1.NewDeleteOptions(0)); err != nil {\n\t\t\t\t\tt.Fatalf(\"deleting final object failed: %v\", err)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n}", "func TestShouldReconcileClusterServiceBroker(t *testing.T) {\n\t// Anonymous struct fields:\n\t// name: short description of the test\n\t// broker: broker object to test\n\t// now: what time the interval is calculated with respect to interval\n\t// reconcile: whether or not the reconciler should run, the return of\n\t// shouldReconcileClusterServiceBroker\n\tcases := []struct {\n\t\tname string\n\t\tbroker *v1beta1.ClusterServiceBroker\n\t\tnow time.Time\n\t\treconcile bool\n\t\terr error\n\t}{\n\t\t{\n\t\t\tname: \"no status\",\n\t\t\tbroker: func() *v1beta1.ClusterServiceBroker {\n\t\t\t\tbroker := getTestClusterServiceBroker()\n\t\t\t\tbroker.Spec.RelistDuration = &metav1.Duration{Duration: 3 * time.Minute}\n\t\t\t\treturn broker\n\t\t\t}(),\n\t\t\tnow: time.Now(),\n\t\t\treconcile: true,\n\t\t},\n\t\t{\n\t\t\tname: \"deletionTimestamp set\",\n\t\t\tbroker: func() *v1beta1.ClusterServiceBroker {\n\t\t\t\tbroker := getTestClusterServiceBrokerWithStatus(v1beta1.ConditionTrue)\n\t\t\t\tbroker.DeletionTimestamp = &metav1.Time{}\n\t\t\t\tbroker.Spec.RelistDuration = &metav1.Duration{Duration: 3 * time.Hour}\n\t\t\t\treturn broker\n\t\t\t}(),\n\t\t\tnow: time.Now(),\n\t\t\treconcile: true,\n\t\t},\n\t\t{\n\t\t\tname: \"no ready condition\",\n\t\t\tbroker: func() *v1beta1.ClusterServiceBroker {\n\t\t\t\tbroker := getTestClusterServiceBroker()\n\t\t\t\tbroker.Status = v1beta1.ClusterServiceBrokerStatus{\n\t\t\t\t\tCommonServiceBrokerStatus: v1beta1.CommonServiceBrokerStatus{\n\t\t\t\t\t\tConditions: []v1beta1.ServiceBrokerCondition{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tType: v1beta1.ServiceBrokerConditionType(\"NotARealCondition\"),\n\t\t\t\t\t\t\t\tStatus: v1beta1.ConditionTrue,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tbroker.Spec.RelistDuration = &metav1.Duration{Duration: 3 * time.Minute}\n\t\t\t\treturn broker\n\t\t\t}(),\n\t\t\tnow: time.Now(),\n\t\t\treconcile: true,\n\t\t},\n\t\t{\n\t\t\tname: \"not ready\",\n\t\t\tbroker: func() *v1beta1.ClusterServiceBroker {\n\t\t\t\tbroker := getTestClusterServiceBrokerWithStatus(v1beta1.ConditionFalse)\n\t\t\t\tbroker.Spec.RelistDuration = &metav1.Duration{Duration: 3 * time.Minute}\n\t\t\t\treturn broker\n\t\t\t}(),\n\t\t\tnow: time.Now(),\n\t\t\treconcile: true,\n\t\t},\n\t\t{\n\t\t\tname: \"ready, interval elapsed\",\n\t\t\tbroker: func() *v1beta1.ClusterServiceBroker {\n\t\t\t\tbroker := getTestClusterServiceBrokerWithStatus(v1beta1.ConditionTrue)\n\t\t\t\tbroker.Spec.RelistDuration = &metav1.Duration{Duration: 3 * time.Minute}\n\t\t\t\treturn broker\n\t\t\t}(),\n\t\t\tnow: time.Now(),\n\t\t\treconcile: true,\n\t\t},\n\t\t{\n\t\t\tname: \"good steady state - ready, interval not elapsed, but last state change was a long time ago\",\n\t\t\tbroker: func() *v1beta1.ClusterServiceBroker {\n\t\t\t\tlastTransitionTime := metav1.NewTime(time.Now().Add(-30 * time.Minute))\n\t\t\t\tlastRelistTime := metav1.NewTime(time.Now().Add(-2 * time.Minute))\n\t\t\t\tbroker := getTestClusterServiceBrokerWithStatusAndTime(v1beta1.ConditionTrue, lastTransitionTime, lastRelistTime)\n\t\t\t\tbroker.Spec.RelistDuration = &metav1.Duration{Duration: 3 * time.Minute}\n\t\t\t\treturn broker\n\t\t\t}(),\n\t\t\tnow: time.Now(),\n\t\t\treconcile: false,\n\t\t},\n\t\t{\n\t\t\tname: \"good steady state - ready, interval has elapsed, last state change was a long time ago\",\n\t\t\tbroker: func() *v1beta1.ClusterServiceBroker {\n\t\t\t\tlastTransitionTime := metav1.NewTime(time.Now().Add(-30 * time.Minute))\n\t\t\t\tlastRelistTime := metav1.NewTime(time.Now().Add(-4 * time.Minute))\n\t\t\t\tbroker := getTestClusterServiceBrokerWithStatusAndTime(v1beta1.ConditionTrue, lastTransitionTime, lastRelistTime)\n\t\t\t\tbroker.Spec.RelistDuration = &metav1.Duration{Duration: 3 * time.Minute}\n\t\t\t\treturn broker\n\t\t\t}(),\n\t\t\tnow: time.Now(),\n\t\t\treconcile: true,\n\t\t},\n\t\t{\n\t\t\tname: \"ready, interval not elapsed\",\n\t\t\tbroker: func() *v1beta1.ClusterServiceBroker {\n\t\t\t\tbroker := getTestClusterServiceBrokerWithStatus(v1beta1.ConditionTrue)\n\t\t\t\tbroker.Spec.RelistDuration = &metav1.Duration{Duration: 3 * time.Hour}\n\t\t\t\treturn broker\n\t\t\t}(),\n\t\t\tnow: time.Now(),\n\t\t\treconcile: false,\n\t\t},\n\t\t{\n\t\t\tname: \"ready, interval not elapsed, spec changed\",\n\t\t\tbroker: func() *v1beta1.ClusterServiceBroker {\n\t\t\t\tbroker := getTestClusterServiceBrokerWithStatus(v1beta1.ConditionTrue)\n\t\t\t\tbroker.Generation = 2\n\t\t\t\tbroker.Status.ReconciledGeneration = 1\n\t\t\t\tbroker.Spec.RelistDuration = &metav1.Duration{Duration: 3 * time.Hour}\n\t\t\t\treturn broker\n\t\t\t}(),\n\t\t\tnow: time.Now(),\n\t\t\treconcile: true,\n\t\t},\n\t\t{\n\t\t\tname: \"ready, duration behavior, nil duration\",\n\t\t\tbroker: func() *v1beta1.ClusterServiceBroker {\n\t\t\t\tbroker := getTestClusterServiceBrokerWithStatus(v1beta1.ConditionTrue)\n\t\t\t\tbroker.Spec.RelistBehavior = v1beta1.ServiceBrokerRelistBehaviorDuration\n\t\t\t\tbroker.Spec.RelistDuration = nil\n\t\t\t\treturn broker\n\t\t\t}(),\n\t\t\tnow: time.Now(),\n\t\t\treconcile: false,\n\t\t},\n\t\t{\n\t\t\tname: \"ready, manual behavior\",\n\t\t\tbroker: func() *v1beta1.ClusterServiceBroker {\n\t\t\t\tbroker := getTestClusterServiceBrokerWithStatus(v1beta1.ConditionTrue)\n\t\t\t\tbroker.Spec.RelistBehavior = v1beta1.ServiceBrokerRelistBehaviorManual\n\t\t\t\treturn broker\n\t\t\t}(),\n\t\t\tnow: time.Now(),\n\t\t\treconcile: false,\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\tvar ltt *time.Time\n\t\tif len(tc.broker.Status.Conditions) != 0 {\n\t\t\tltt = &tc.broker.Status.Conditions[0].LastTransitionTime.Time\n\t\t}\n\n\t\tif tc.broker.Spec.RelistDuration != nil {\n\t\t\tinterval := tc.broker.Spec.RelistDuration.Duration\n\t\t\tlastRelistTime := tc.broker.Status.LastCatalogRetrievalTime\n\t\t\tt.Logf(\"%v: now: %v, interval: %v, last transition time: %v, last relist time: %v\", tc.name, tc.now, interval, ltt, lastRelistTime)\n\t\t} else {\n\t\t\tt.Logf(\"broker.Spec.RelistDuration set to nil\")\n\t\t}\n\n\t\tactual := shouldReconcileClusterServiceBroker(tc.broker, tc.now)\n\n\t\tif e, a := tc.reconcile, actual; e != a {\n\t\t\tt.Errorf(\"%v: unexpected result: %s\", tc.name, expectedGot(e, a))\n\t\t}\n\t}\n}", "func waitForPods(cs *framework.ClientSet, expectedTotal, min, max int32) error {\n\terr := wait.PollImmediate(1*time.Second, 5*time.Minute, func() (bool, error) {\n\t\td, err := cs.AppsV1Interface.Deployments(\"openshift-machine-config-operator\").Get(context.TODO(), \"etcd-quorum-guard\", metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\t// By this point the deployment should exist.\n\t\t\tfmt.Printf(\" error waiting for etcd-quorum-guard deployment to exist: %v\\n\", err)\n\t\t\treturn true, err\n\t\t}\n\t\tif d.Status.Replicas < 1 {\n\t\t\tfmt.Println(\"operator deployment has no replicas\")\n\t\t\treturn false, nil\n\t\t}\n\t\tif d.Status.Replicas == expectedTotal &&\n\t\t\td.Status.AvailableReplicas >= min &&\n\t\t\td.Status.AvailableReplicas <= max {\n\t\t\tfmt.Printf(\" Deployment is ready! %d %d\\n\", d.Status.Replicas, d.Status.AvailableReplicas)\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor pod, info := range pods {\n\t\tif info.status == \"Running\" {\n\t\t\tnode := info.node\n\t\t\tif node == \"\" {\n\t\t\t\treturn fmt.Errorf(\"Pod %s not associated with a node\", pod)\n\t\t\t}\n\t\t\tif _, ok := nodes[node]; !ok {\n\t\t\t\treturn fmt.Errorf(\"pod %s running on %s, not a master\", pod, node)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func TestCmdDeploy_cancelOk(t *testing.T) {\n\tvar (\n\t\tconfig *deployapi.DeploymentConfig\n\t\texistingDeployments *kapi.ReplicationControllerList\n\t\tupdatedDeployments []kapi.ReplicationController\n\t)\n\n\tcommandClient := &deployCommandClientImpl{\n\t\tGetDeploymentFn: func(namespace, name string) (*kapi.ReplicationController, error) {\n\t\t\tt.Fatalf(\"unexpected call to GetDeployment: %s\", name)\n\t\t\treturn nil, nil\n\t\t},\n\t\tListDeploymentsForConfigFn: func(namespace, configName string) (*kapi.ReplicationControllerList, error) {\n\t\t\treturn existingDeployments, nil\n\t\t},\n\t\tUpdateDeploymentConfigFn: func(config *deployapi.DeploymentConfig) (*deployapi.DeploymentConfig, error) {\n\t\t\tt.Fatalf(\"unexpected call to UpdateDeploymentConfig\")\n\t\t\treturn nil, nil\n\t\t},\n\t\tUpdateDeploymentFn: func(deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\tupdatedDeployments = append(updatedDeployments, *deployment)\n\t\t\treturn deployment, nil\n\t\t},\n\t}\n\n\ttype existing struct {\n\t\tversion int\n\t\tstatus deployapi.DeploymentStatus\n\t\tshouldCancel bool\n\t}\n\ttype scenario struct {\n\t\tversion int\n\t\texisting []existing\n\t}\n\n\tscenarios := []scenario{\n\t\t// No existing deployments\n\t\t{1, []existing{{1, deployapi.DeploymentStatusComplete, false}}},\n\t\t// A single existing failed deployment\n\t\t{1, []existing{{1, deployapi.DeploymentStatusFailed, false}}},\n\t\t// Multiple existing completed/failed deployments\n\t\t{2, []existing{{2, deployapi.DeploymentStatusFailed, false}, {1, deployapi.DeploymentStatusComplete, false}}},\n\t\t// A single existing new deployment\n\t\t{1, []existing{{1, deployapi.DeploymentStatusNew, true}}},\n\t\t// A single existing pending deployment\n\t\t{1, []existing{{1, deployapi.DeploymentStatusPending, true}}},\n\t\t// A single existing running deployment\n\t\t{1, []existing{{1, deployapi.DeploymentStatusRunning, true}}},\n\t\t// Multiple existing deployments with one in new/pending/running\n\t\t{3, []existing{{3, deployapi.DeploymentStatusRunning, true}, {2, deployapi.DeploymentStatusComplete, false}, {1, deployapi.DeploymentStatusFailed, false}}},\n\t\t// Multiple existing deployments with more than one in new/pending/running\n\t\t{3, []existing{{3, deployapi.DeploymentStatusNew, true}, {2, deployapi.DeploymentStatusRunning, true}, {1, deployapi.DeploymentStatusFailed, false}}},\n\t}\n\n\tc := &cancelDeploymentCommand{client: commandClient}\n\tfor _, scenario := range scenarios {\n\t\tupdatedDeployments = []kapi.ReplicationController{}\n\t\tconfig = deploytest.OkDeploymentConfig(scenario.version)\n\t\texistingDeployments = &kapi.ReplicationControllerList{}\n\t\tfor _, e := range scenario.existing {\n\t\t\td, _ := deployutil.MakeDeployment(deploytest.OkDeploymentConfig(e.version), api.Codec)\n\t\t\td.Annotations[deployapi.DeploymentStatusAnnotation] = string(e.status)\n\t\t\texistingDeployments.Items = append(existingDeployments.Items, *d)\n\t\t}\n\n\t\terr := c.cancel(config, ioutil.Discard)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t\t}\n\n\t\texpectedCancellations := []int{}\n\t\tactualCancellations := []int{}\n\t\tfor _, e := range scenario.existing {\n\t\t\tif e.shouldCancel {\n\t\t\t\texpectedCancellations = append(expectedCancellations, e.version)\n\t\t\t}\n\t\t}\n\t\tfor _, d := range updatedDeployments {\n\t\t\tactualCancellations = append(actualCancellations, deployutil.DeploymentVersionFor(&d))\n\t\t}\n\n\t\tsort.Ints(actualCancellations)\n\t\tsort.Ints(expectedCancellations)\n\t\tif !reflect.DeepEqual(actualCancellations, expectedCancellations) {\n\t\t\tt.Fatalf(\"expected cancellations: %v, actual: %v\", expectedCancellations, actualCancellations)\n\t\t}\n\t}\n}", "func assertPodsPendingForDuration(c clientset.Interface, deployment *appsv1.Deployment, pendingPodsNum int, pendingDuration time.Duration) error {\n\n\tpendingPods := make(map[string]time.Time)\n\n\terr := wait.PollImmediate(pollInterval, pollTimeout+pendingDuration, func() (bool, error) {\n\t\tvar err error\n\t\tcurrentPodList, err := framework_deployment.GetPodsForDeployment(c, deployment)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tmissingPods := make(map[string]bool)\n\t\tfor podName := range pendingPods {\n\t\t\tmissingPods[podName] = true\n\t\t}\n\n\t\tnow := time.Now()\n\t\tfor _, pod := range currentPodList.Items {\n\t\t\tdelete(missingPods, pod.Name)\n\t\t\tswitch pod.Status.Phase {\n\t\t\tcase apiv1.PodPending:\n\t\t\t\t_, ok := pendingPods[pod.Name]\n\t\t\t\tif !ok {\n\t\t\t\t\tpendingPods[pod.Name] = now\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tdelete(pendingPods, pod.Name)\n\t\t\t}\n\t\t}\n\n\t\tfor missingPod := range missingPods {\n\t\t\tdelete(pendingPods, missingPod)\n\t\t}\n\n\t\tif len(pendingPods) < pendingPodsNum {\n\t\t\treturn false, nil\n\t\t}\n\n\t\tif len(pendingPods) > pendingPodsNum {\n\t\t\treturn false, fmt.Errorf(\"%v pending pods seen - expecting %v\", len(pendingPods), pendingPodsNum)\n\t\t}\n\n\t\tfor p, t := range pendingPods {\n\t\t\tfmt.Println(\"task\", now, p, t, now.Sub(t), pendingDuration)\n\t\t\tif now.Sub(t) < pendingDuration {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\n\t\treturn true, nil\n\t})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"assertion failed for pending pods in %v: %v\", deployment.Name, err)\n\t}\n\treturn nil\n}", "func checkConcurrency(t *testing.T, expectedConcurrency *int, run *v1alpha1.Run,\n\texpectedTaskRuns []*v1beta1.TaskRun, actualTaskRunList *v1beta1.TaskRunList) {\n\n\ttype taskRunEventType int\n\tconst (\n\t\ttrCreated taskRunEventType = iota\n\t\ttrCompleted taskRunEventType = iota\n\t)\n\n\ttype taskRunEvent struct {\n\t\teventTime metav1.Time\n\t\teventType taskRunEventType\n\t\ttrName string\n\t}\n\n\tevents := []taskRunEvent{}\n\tfor _, actualTaskRun := range actualTaskRunList.Items {\n\t\t// This shouldn't happen unless something really went wrong but we need to test it to avoid a panic dereferencing the pointer.\n\t\tif actualTaskRun.Status.CompletionTime == nil {\n\t\t\tt.Errorf(\"TaskRun %s does not have a completion time\", actualTaskRun.Name)\n\t\t\tcontinue\n\t\t}\n\t\tevents = append(events,\n\t\t\ttaskRunEvent{eventTime: actualTaskRun.ObjectMeta.CreationTimestamp, eventType: trCreated, trName: actualTaskRun.ObjectMeta.Name},\n\t\t\ttaskRunEvent{eventTime: *actualTaskRun.Status.CompletionTime, eventType: trCompleted, trName: actualTaskRun.ObjectMeta.Name},\n\t\t)\n\t}\n\n\tsort.Slice(events, func(i, j int) bool {\n\t\t// Unfortunately the timestamp resolution is only 1 second which makes event ordering imprecise.\n\t\t// This could trigger a false limit failure if TaskRun B was created a few milliseconds after TaskRun A completed\n\t\t// but the events were sorted the other way. In order to address this, the sort places TaskRun completion\n\t\t// before TaskRun creation when the times are equal and the TaskRun names are different. There is a small\n\t\t// chance this could mask a problem but it's the best that can be done with the limited timestamp resolution.\n\t\treturn events[i].eventTime.Before(&events[j].eventTime) ||\n\t\t\t(events[i].eventTime.Equal(&events[j].eventTime) &&\n\t\t\t\t((events[i].trName == events[j].trName && events[i].eventType == trCreated) ||\n\t\t\t\t\t(events[i].trName != events[j].trName && events[i].eventType == trCompleted)))\n\t})\n\n\tt.Logf(\"Sorted taskrun event table: %v\", events)\n\n\t// Determine how many TaskRuns were \"alive\" at any given time, where \"alive\" means the TaskRun was created\n\t// and thus eligible to run and not yet completed.\n\tconcurrency := 0\n\tmaxConcurrency := 0\n\tconcurrencyLimit := 1\n\tif expectedConcurrency != nil {\n\t\tconcurrencyLimit = *expectedConcurrency\n\t}\n\toffender := \"\"\n\tvar firstCreationTime, lastCompletionTime metav1.Time\n\tfirstCreationTime = metav1.Unix(1<<63-62135596801, 999999999) // max time\n\tfor _, event := range events {\n\t\tif event.eventType == trCreated {\n\t\t\tconcurrency++\n\t\t} else {\n\t\t\tconcurrency--\n\t\t}\n\t\t// If the concurrency limit was breached, record the first TaskRun where it happened.\n\t\tif concurrencyLimit > 0 && concurrency > concurrencyLimit && offender == \"\" {\n\t\t\toffender = event.trName\n\t\t}\n\t\t// Track the peak number of active TaskRuns.\n\t\tif concurrency > maxConcurrency {\n\t\t\tmaxConcurrency = concurrency\n\t\t}\n\t\tif event.eventType == trCreated {\n\t\t\tif event.eventTime.Before(&firstCreationTime) {\n\t\t\t\tfirstCreationTime = event.eventTime\n\t\t\t}\n\t\t} else {\n\t\t\tif lastCompletionTime.Before(&event.eventTime) {\n\t\t\t\tlastCompletionTime = event.eventTime\n\t\t\t}\n\t\t}\n\t}\n\n\tt.Logf(\"maxConcurrency=%v\", maxConcurrency)\n\n\tif concurrencyLimit <= 0 {\n\t\t// There is no limit so all of the expected TaskRuns should have been created at once.\n\t\t// This check assumes that the controller can create all of the TaskRuns before any of them complete.\n\t\t// It would take a very fast TaskRun and a very slow controller to violate that but using a sleep in\n\t\t// the task helps to make that unlikely.\n\t\tif maxConcurrency < len(expectedTaskRuns) {\n\t\t\tt.Errorf(\"Concurrency is unlimited so all %d expected TaskRuns should have been active at once but only %d were.\",\n\t\t\t\tlen(expectedTaskRuns), maxConcurrency)\n\t\t}\n\t} else {\n\t\t// There is a limit so there shouldn't be more TaskRuns than that alive at any moment.\n\t\tif maxConcurrency > concurrencyLimit {\n\t\t\tt.Errorf(\"Concurrency limit %d was broken. \"+\n\t\t\t\t\"%d TaskRuns were running or eligible to run at one point. \"+\n\t\t\t\t\"The limit was first crossed when TaskRun %s was created.\",\n\t\t\t\tconcurrencyLimit, maxConcurrency, offender)\n\t\t} else {\n\t\t\t// The limit should be equaled when TaskRuns are created for the first set of iterations,\n\t\t\t// unless there are fewer TaskRuns than the limit.\n\t\t\texpectedPeak := concurrencyLimit\n\t\t\tif len(expectedTaskRuns) < concurrencyLimit {\n\t\t\t\texpectedPeak = len(expectedTaskRuns)\n\t\t\t}\n\t\t\tif maxConcurrency < expectedPeak {\n\t\t\t\tt.Errorf(\"Concurrency limit %d was not reached. \"+\n\t\t\t\t\t\"At most only %d TaskRuns were running or eligible to run.\",\n\t\t\t\t\tconcurrencyLimit, maxConcurrency)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check that the Run's start and completion times are set appropriately.\n\tif run.Status.StartTime == nil {\n\t\tt.Errorf(\"The Run start time is not set!\")\n\t} else if firstCreationTime.Before(run.Status.StartTime) {\n\t\tt.Errorf(\"The Run start time %v is after the first TaskRun's creation time %v\", run.Status.StartTime, firstCreationTime)\n\t}\n\tif run.Status.CompletionTime == nil {\n\t\tt.Errorf(\"The Run completion time is not set!\")\n\t} else if run.Status.CompletionTime.Before(&lastCompletionTime) {\n\t\tt.Errorf(\"The Run completion time %v is before the last TaskRun's completion time %v\", run.Status.CompletionTime, lastCompletionTime)\n\t}\n}", "func ConcurrencyTest(t *testing.T, hc HandlerConstructor, requestNumber int, limit int) ConcurrencyTestResult {\n\n\tvar oopsCount uint64\n\n\tcounter := make(chan int)\n\tcodes := make(chan int)\n\n\thandler := hc(requestNumber, limit, counter)\n\n\tts := httptest.NewServer(handler)\n\tdefer ts.Close()\n\n\tvar requestsWg sync.WaitGroup\n\tfor i := 0; i < requestNumber; i++ {\n\t\trequestsWg.Add(1)\n\t\tgo func() {\n\t\t\tres, err := http.Get(ts.URL)\n\t\t\tassert.NoError(t, err)\n\t\t\tif err == nil {\n\t\t\t\tcodes <- res.StatusCode\n\t\t\t} else {\n\t\t\t\tatomic.AddUint64(&oopsCount, 1)\n\t\t\t}\n\t\t\trequestsWg.Done()\n\t\t}()\n\t}\n\n\tvar resultsWg sync.WaitGroup\n\tvar result ConcurrencyTestResult\n\n\tresultsWg.Add(2)\n\tgo func() {\n\t\tvar concurrencyNow int\n\t\tfor number := range counter {\n\t\t\tconcurrencyNow += number\n\t\t\tif concurrencyNow > result.maxConcurrency {\n\t\t\t\tresult.maxConcurrency = concurrencyNow\n\t\t\t}\n\t\t}\n\t\tresultsWg.Done()\n\t}()\n\tgo func() {\n\t\tfor number := range codes {\n\t\t\tswitch number {\n\t\t\tcase http.StatusOK:\n\t\t\t\tresult.accepted++\n\t\t\tcase http.StatusTooManyRequests:\n\t\t\t\tresult.denied++\n\t\t\tdefault:\n\t\t\t\tassert.Failf(t, \"bad response\", \"unexpected status code: %v\", number)\n\t\t\t}\n\t\t}\n\t\tresultsWg.Done()\n\t}()\n\n\trequestsWg.Wait()\n\tif oopsCount > 0 {\n\t\tfmt.Printf(\"Saw a number of errors, count is: %d\\n\", oopsCount)\n\t}\n\tclose(counter)\n\tclose(codes)\n\tresultsWg.Wait()\n\n\treturn result\n}", "func TestConcurrentAccessToRelatedVolumes(ctx context.Context, f *framework.Framework, cs clientset.Interface, ns string,\n\tnode e2epod.NodeSelection, pvcs []*v1.PersistentVolumeClaim, expectedContent string) {\n\n\tvar pods []*v1.Pod\n\n\t// Create each pod with pvc\n\tfor i := range pvcs {\n\t\tindex := i + 1\n\t\tginkgo.By(fmt.Sprintf(\"Creating pod%d with a volume on %+v\", index, node))\n\t\tpodConfig := e2epod.Config{\n\t\t\tNS: ns,\n\t\t\tPVCs: []*v1.PersistentVolumeClaim{pvcs[i]},\n\t\t\tSeLinuxLabel: e2epod.GetLinuxLabel(),\n\t\t\tNodeSelection: node,\n\t\t\tPVCsReadOnly: false,\n\t\t\tImageID: e2epod.GetTestImageID(imageutils.JessieDnsutils),\n\t\t}\n\t\tpod, err := e2epod.CreateSecPodWithNodeSelection(ctx, cs, &podConfig, f.Timeouts.PodStart)\n\t\tdefer func() {\n\t\t\tframework.ExpectNoError(e2epod.DeletePodWithWait(ctx, cs, pod))\n\t\t}()\n\t\tframework.ExpectNoError(err)\n\t\tpods = append(pods, pod)\n\t\tactualNodeName := pod.Spec.NodeName\n\n\t\t// Always run the subsequent pods on the same node.\n\t\te2epod.SetAffinity(&node, actualNodeName)\n\t}\n\n\tfor i, pvc := range pvcs {\n\t\tvar commands []string\n\n\t\tif *pvc.Spec.VolumeMode == v1.PersistentVolumeBlock {\n\t\t\tfileName := \"/mnt/volume1\"\n\t\t\tcommands = e2evolume.GenerateReadBlockCmd(fileName, len(expectedContent))\n\t\t\t// Check that all pods have the same content\n\t\t\tindex := i + 1\n\t\t\tginkgo.By(fmt.Sprintf(\"Checking if the volume in pod%d has expected initial content\", index))\n\t\t\t_, err := e2eoutput.LookForStringInPodExec(pods[i].Namespace, pods[i].Name, commands, expectedContent, time.Minute)\n\t\t\tframework.ExpectNoError(err, \"failed: finding the contents of the block volume %s.\", fileName)\n\t\t} else {\n\t\t\tfileName := \"/mnt/volume1/index.html\"\n\t\t\tcommands = e2evolume.GenerateReadFileCmd(fileName)\n\t\t\t// Check that all pods have the same content\n\t\t\tindex := i + 1\n\t\t\tginkgo.By(fmt.Sprintf(\"Checking if the volume in pod%d has expected initial content\", index))\n\t\t\t_, err := e2eoutput.LookForStringInPodExec(pods[i].Namespace, pods[i].Name, commands, expectedContent, time.Minute)\n\t\t\tframework.ExpectNoError(err, \"failed: finding the contents of the mounted file %s.\", fileName)\n\t\t}\n\t}\n}", "func TestReconcile(t *testing.T) {\n\n\t//\n\t// Define The KafkaChannel Reconciler Test Cases\n\t//\n\t// Note - Knative testing framework assumes ALL actions will be in the same Namespace\n\t// as the Key so we have to set SkipNamespaceValidation in all tests!\n\t//\n\t// Note - Knative reconciler framework expects Events (not errors) from ReconcileKind()\n\t// so WantErr is only for higher level failures in the injected Reconcile() function.\n\t//\n\tcommontesting.SetTestEnvironment(t)\n\ttableTest := TableTest{\n\n\t\t//\n\t\t// Top Level Use Cases\n\t\t//\n\n\t\t{\n\t\t\tName: \"Bad KafkaChannel Key\",\n\t\t\tKey: \"too/many/parts\",\n\t\t},\n\t\t{\n\t\t\tName: \"KafkaChannel Key Not Found\",\n\t\t\tKey: \"foo/not-found\",\n\t\t},\n\n\t\t//\n\t\t// Full Reconciliation\n\t\t//\n\n\t\t{\n\t\t\tName: \"Complete Reconciliation Success\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(controllertesting.WithInitializedConditions),\n\t\t\t},\n\t\t\tWantCreates: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(),\n\t\t\t},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\t{\n\t\t\t\t\tObject: controllertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWantUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\tcontrollertesting.NewKafkaChannelLabelUpdate(\n\t\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t},\n\t\t\tWantPatches: []clientgotesting.PatchActionImpl{controllertesting.NewFinalizerPatchActionImpl()},\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaChannelFinalizerUpdateEvent(),\n\t\t\t\tcontrollertesting.NewKafkaChannelSuccessfulReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Complete Reconciliation Success, No Dispatcher Resource Requests Or Limits\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(controllertesting.WithInitializedConditions),\n\t\t\t},\n\t\t\tWantCreates: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(controllertesting.WithoutResources),\n\t\t\t},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\t{\n\t\t\t\t\tObject: controllertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWantUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\tcontrollertesting.NewKafkaChannelLabelUpdate(\n\t\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t},\n\t\t\tWantPatches: []clientgotesting.PatchActionImpl{controllertesting.NewFinalizerPatchActionImpl()},\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaChannelFinalizerUpdateEvent(),\n\t\t\t\tcontrollertesting.NewKafkaChannelSuccessfulReconciliationEvent(),\n\t\t\t},\n\t\t\tOtherTestData: map[string]interface{}{\n\t\t\t\t\"configOptions\": []controllertesting.KafkaConfigOption{controllertesting.WithNoDispatcherResources},\n\t\t\t},\n\t\t},\n\n\t\t//\n\t\t// KafkaChannel Deletion (Finalizer)\n\t\t//\n\n\t\t{\n\t\t\tName: \"Finalize Deleted KafkaChannel With Dispatcher\",\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithLabels,\n\t\t\t\t\tcontrollertesting.WithDeletionTimestamp,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(),\n\t\t\t},\n\t\t\tWantUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\tcontrollertesting.NewServiceUpdateActionImpl(controllertesting.NewKafkaChannelDispatcherService(controllertesting.WithoutFinalizersService)),\n\t\t\t\tcontrollertesting.NewDeploymentUpdateActionImpl(controllertesting.NewKafkaChannelDispatcherDeployment(controllertesting.WithoutFinalizersDeployment)),\n\t\t\t},\n\t\t\tWantDeletes: []clientgotesting.DeleteActionImpl{\n\t\t\t\tcontrollertesting.NewServiceDeleteActionImpl(controllertesting.NewKafkaChannelDispatcherService(controllertesting.WithoutFinalizersService)),\n\t\t\t\tcontrollertesting.NewDeploymentDeleteActionImpl(controllertesting.NewKafkaChannelDispatcherDeployment(controllertesting.WithoutFinalizersDeployment)),\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaChannelSuccessfulFinalizedEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Finalize Deleted KafkaChannel Without Dispatcher\",\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithLabels,\n\t\t\t\t\tcontrollertesting.WithDeletionTimestamp,\n\t\t\t\t),\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaChannelSuccessfulFinalizedEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Finalize Deleted KafkaChannel Errors(Delete)\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithLabels,\n\t\t\t\t\tcontrollertesting.WithDeletionTimestamp,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(),\n\t\t\t},\n\t\t\tWithReactors: []clientgotesting.ReactionFunc{\n\t\t\t\tInduceFailure(\"delete\", \"Services\"),\n\t\t\t\tInduceFailure(\"delete\", \"Deployments\"),\n\t\t\t},\n\t\t\tWantUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\tcontrollertesting.NewServiceUpdateActionImpl(controllertesting.NewKafkaChannelDispatcherService(controllertesting.WithoutFinalizersService)),\n\t\t\t\tcontrollertesting.NewDeploymentUpdateActionImpl(controllertesting.NewKafkaChannelDispatcherDeployment(controllertesting.WithoutFinalizersDeployment)),\n\t\t\t},\n\t\t\tWantDeletes: []clientgotesting.DeleteActionImpl{\n\t\t\t\tcontrollertesting.NewServiceDeleteActionImpl(controllertesting.NewKafkaChannelDispatcherService(controllertesting.WithoutFinalizersService)),\n\t\t\t\tcontrollertesting.NewDeploymentDeleteActionImpl(controllertesting.NewKafkaChannelDispatcherDeployment(controllertesting.WithoutFinalizersDeployment)),\n\t\t\t},\n\t\t\tWantErr: true,\n\t\t\tWantEvents: []string{\n\t\t\t\tEventf(corev1.EventTypeWarning, event.DispatcherServiceFinalizationFailed.String(), \"Failed To Finalize Dispatcher Service: inducing failure for delete services\"),\n\t\t\t\tEventf(corev1.EventTypeWarning, event.DispatcherDeploymentFinalizationFailed.String(), \"Failed To Finalize Dispatcher Deployment: inducing failure for delete deployments\"),\n\t\t\t\tcontrollertesting.NewKafkaChannelFailedFinalizationEvent(),\n\t\t\t},\n\t\t},\n\n\t\t//\n\t\t// KafkaChannel Service\n\t\t//\n\n\t\t{\n\t\t\tName: \"Reconcile Missing KafkaChannel Service Success\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(),\n\t\t\t},\n\t\t\tWantCreates: []runtime.Object{controllertesting.NewKafkaChannelService()},\n\t\t\tWantEvents: []string{controllertesting.NewKafkaChannelSuccessfulReconciliationEvent()},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Missing KafkaChannel Service Error(Create)\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(),\n\t\t\t},\n\t\t\tWithReactors: []clientgotesting.ReactionFunc{InduceFailure(\"create\", \"Services\")},\n\t\t\tWantErr: true,\n\t\t\tWantCreates: []runtime.Object{controllertesting.NewKafkaChannelService()},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\t{\n\t\t\t\t\tObject: controllertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceFailed,\n\t\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tEventf(corev1.EventTypeWarning, event.KafkaChannelServiceReconciliationFailed.String(), \"Failed To Reconcile KafkaChannel Service: inducing failure for create services\"),\n\t\t\t\tcontrollertesting.NewKafkaChannelFailedReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile KafkaChannel Service With Deletion Timestamp\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(controllertesting.WithDeletionTimestampService),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(),\n\t\t\t},\n\t\t\tWantErr: true,\n\t\t\tWantEvents: []string{\n\t\t\t\tEventf(corev1.EventTypeWarning, event.KafkaChannelServiceReconciliationFailed.String(), \"Failed To Reconcile KafkaChannel Service: encountered KafkaChannel Service with DeletionTimestamp kafkachannel-namespace/kafkachannel-name-kn-channel - potential race condition\"),\n\t\t\t\tcontrollertesting.NewKafkaChannelFailedReconciliationEvent(),\n\t\t\t},\n\t\t},\n\n\t\t//\n\t\t// KafkaChannel Dispatcher Service\n\t\t//\n\n\t\t{\n\t\t\tName: \"Reconcile Missing Dispatcher Service Success\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(),\n\t\t\t},\n\t\t\tWantCreates: []runtime.Object{controllertesting.NewKafkaChannelDispatcherService()},\n\t\t\tWantEvents: []string{controllertesting.NewKafkaChannelSuccessfulReconciliationEvent()},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Missing Dispatcher Service Error(Create)\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(),\n\t\t\t},\n\t\t\tWithReactors: []clientgotesting.ReactionFunc{InduceFailure(\"create\", \"Services\")},\n\t\t\tWantErr: true,\n\t\t\tWantCreates: []runtime.Object{controllertesting.NewKafkaChannelDispatcherService()},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\t// Note - Not currently tracking status for the Dispatcher Service since it is only for Prometheus\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tEventf(corev1.EventTypeWarning, event.DispatcherServiceReconciliationFailed.String(), \"Failed To Reconcile Dispatcher Service: inducing failure for create services\"),\n\t\t\t\tcontrollertesting.NewKafkaChannelFailedReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Dispatcher Service With Deletion Timestamp And Finalizer\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(controllertesting.WithDeletionTimestampService),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(),\n\t\t\t},\n\t\t\tWantErr: false,\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaChannelSuccessfulReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Dispatcher Service With Deletion Timestamp And Missing Finalizer\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(controllertesting.WithoutFinalizersService, controllertesting.WithDeletionTimestampService),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(),\n\t\t\t},\n\t\t\tWantErr: false,\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaChannelSuccessfulReconciliationEvent(),\n\t\t\t},\n\t\t},\n\n\t\t//\n\t\t// KafkaChannel Dispatcher Deployment\n\t\t//\n\n\t\t{\n\t\t\tName: \"Reconcile Missing Dispatcher Deployment Success\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t},\n\t\t\tWantCreates: []runtime.Object{controllertesting.NewKafkaChannelDispatcherDeployment()},\n\t\t\tWantEvents: []string{controllertesting.NewKafkaChannelSuccessfulReconciliationEvent()},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Missing Dispatcher Deployment Error(Create)\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t},\n\t\t\tWithReactors: []clientgotesting.ReactionFunc{InduceFailure(\"create\", \"Deployments\")},\n\t\t\tWantErr: true,\n\t\t\tWantCreates: []runtime.Object{controllertesting.NewKafkaChannelDispatcherDeployment()},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\t{\n\t\t\t\t\tObject: controllertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t\t\tcontrollertesting.WithDispatcherFailed,\n\t\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tEventf(corev1.EventTypeWarning, event.DispatcherDeploymentReconciliationFailed.String(), \"Failed To Reconcile Dispatcher Deployment: inducing failure for create deployments\"),\n\t\t\t\tcontrollertesting.NewKafkaChannelFailedReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Dispatcher Deployment With Deletion Timestamp And Finalizer\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(controllertesting.WithDeletionTimestampDeployment),\n\t\t\t},\n\t\t\tWantErr: false,\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaChannelSuccessfulReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Dispatcher Deployment With Deletion Timestamp And Missing Finalizer\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(controllertesting.WithoutFinalizersDeployment, controllertesting.WithDeletionTimestampDeployment),\n\t\t\t},\n\t\t\tWantErr: false,\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaChannelSuccessfulReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Dispatcher Deployment - Redeployment on ConfigMapHash change\",\n\t\t\tSkipNamespaceValidation: true,\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\tcontrollertesting.WithMetaData,\n\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithDispatcherDeploymentReady,\n\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(controllertesting.WithConfigMapHash(\"initial-hash-to-be-overridden-by-controller\")),\n\t\t\t},\n\t\t\tWantUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\tcontrollertesting.NewDeploymentUpdateActionImpl(controllertesting.NewKafkaChannelDispatcherDeployment()),\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeploymentUpdatedEvent(),\n\t\t\t\tcontrollertesting.NewKafkaChannelSuccessfulReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Missing KafkaSecret - Error\",\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(controllertesting.WithFinalizer),\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tEventf(corev1.EventTypeWarning, \"InternalError\", \"reconciliation failed\"),\n\t\t\t},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\t{\n\t\t\t\t\tObject: controllertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\t\tcontrollertesting.WithKafkaChannelConfigurationFailedNoSecret,\n\t\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWantErr: true,\n\t\t\tOtherTestData: map[string]interface{}{\n\t\t\t\t\"reconcilerOptions\": []reconcilerOption{withEmptyKafkaSecret},\n\t\t\t},\n\t\t},\n\n\t\t//\n\t\t// Deployment Updating - Repairing Incorrect Or Missing Fields In Existing Deployments\n\t\t//\n\n\t\tnewDispatcherUpdateTest(\"No Resources\", controllertesting.WithoutResources),\n\t\tnewDispatcherUpdateTest(\"Different Name\", controllertesting.WithDifferentName),\n\t\tnewDispatcherUpdateTest(\"Different Image\", controllertesting.WithDifferentImage),\n\t\tnewDispatcherUpdateTest(\"Different Command\", controllertesting.WithDifferentCommand),\n\t\tnewDispatcherUpdateTest(\"Different Args\", controllertesting.WithDifferentArgs),\n\t\tnewDispatcherUpdateTest(\"Different WorkingDir\", controllertesting.WithDifferentWorkingDir),\n\t\tnewDispatcherUpdateTest(\"Different Ports\", controllertesting.WithDifferentPorts),\n\t\tnewDispatcherUpdateTest(\"Different Environment\", controllertesting.WithMissingEnvironment),\n\t\tnewDispatcherUpdateTest(\"Different Environment\", controllertesting.WithDifferentEnvironment),\n\t\tnewDispatcherUpdateTest(\"Different VolumeMounts\", controllertesting.WithDifferentVolumeMounts),\n\t\tnewDispatcherUpdateTest(\"Different VolumeDevices\", controllertesting.WithDifferentVolumeDevices),\n\t\tnewDispatcherUpdateTest(\"Different LivenessProbe\", controllertesting.WithDifferentLivenessProbe),\n\t\tnewDispatcherUpdateTest(\"Different ReadinessProbe\", controllertesting.WithDifferentReadinessProbe),\n\t\tnewDispatcherUpdateTest(\"Missing Labels\", controllertesting.WithoutLabels),\n\t\tnewDispatcherUpdateTest(\"Missing Annotations\", controllertesting.WithoutAnnotations),\n\t\tnewDispatcherNoUpdateTest(\"Different Lifecycle\", controllertesting.WithDifferentLifecycle),\n\t\tnewDispatcherNoUpdateTest(\"Different TerminationPath\", controllertesting.WithDifferentTerminationPath),\n\t\tnewDispatcherNoUpdateTest(\"Different TerminationPolicy\", controllertesting.WithDifferentTerminationPolicy),\n\t\tnewDispatcherNoUpdateTest(\"Different ImagePullPolicy\", controllertesting.WithDifferentImagePullPolicy),\n\t\tnewDispatcherNoUpdateTest(\"Different SecurityContext\", controllertesting.WithDifferentSecurityContext),\n\t\tnewDispatcherNoUpdateTest(\"Different Replicas\", controllertesting.WithDifferentReplicas),\n\t\tnewDispatcherNoUpdateTest(\"Extra Labels\", controllertesting.WithExtraLabels),\n\t\tnewDispatcherNoUpdateTest(\"Extra Annotations\", controllertesting.WithExtraAnnotations),\n\n\t\t//\n\t\t// Deployment Update Failure\n\t\t//\n\n\t\t{\n\t\t\tName: \"Existing Dispatcher Deployment, Different Image, Update Error\",\n\t\t\tKey: controllertesting.KafkaChannelKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannel(controllertesting.WithFinalizer),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(controllertesting.WithDifferentImage),\n\t\t\t},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\t{\n\t\t\t\t\tObject: controllertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithFinalizer,\n\t\t\t\t\t\tcontrollertesting.WithAddress,\n\t\t\t\t\t\tcontrollertesting.WithInitializedConditions,\n\t\t\t\t\t\tcontrollertesting.WithKafkaChannelServiceReady,\n\t\t\t\t\t\tcontrollertesting.WithDispatcherUpdateFailed,\n\t\t\t\t\t\tcontrollertesting.WithTopicReady,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWantUpdates: []clientgotesting.UpdateActionImpl{{Object: controllertesting.NewKafkaChannelDispatcherDeployment()}},\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeploymentUpdateFailedEvent(),\n\t\t\t\tEventf(corev1.EventTypeWarning, event.DispatcherDeploymentReconciliationFailed.String(), \"Failed To Reconcile Dispatcher Deployment: inducing failure for update deployments\"),\n\t\t\t\tcontrollertesting.NewKafkaChannelFailedReconciliationEvent(),\n\t\t\t},\n\t\t\tWithReactors: []clientgotesting.ReactionFunc{\n\t\t\t\tInduceFailure(\"update\", \"Deployments\"),\n\t\t\t},\n\t\t\tWantErr: true,\n\t\t},\n\n\t\t//\n\t\t// Service Patching - Repairing Incorrect Or Missing Fields In Existing Services\n\t\t//\n\n\t\tnewServicePatchTest(\"Missing Ports\", controllertesting.WithoutServicePorts),\n\t\tnewServicePatchTest(\"Missing App Label Selector\", controllertesting.WithoutServiceSelector),\n\t\tnewServicePatchTest(\"Missing Labels\", controllertesting.WithoutServiceLabels),\n\t\tnewServiceNoPatchTest(\"Extra Labels\", controllertesting.WithExtraServiceLabels),\n\t\tnewServiceNoPatchTest(\"Different Status\", controllertesting.WithDifferentServiceStatus),\n\n\t\t//\n\t\t// Service Patch Failure\n\t\t//\n\n\t\tnewServicePatchFailureTest(\"Missing Ports\", controllertesting.WithoutServicePorts),\n\t\tnewServicePatchFailureTest(\"Missing Labels\", controllertesting.WithoutServiceLabels),\n\t}\n\n\t// Create A Mock AdminClient\n\tmockAdminClient := &controllertesting.MockAdminClient{}\n\n\t// Stub The Creation Of AdminClient\n\tkafkaadmintesting.StubNewAdminClientFn(kafkaadmintesting.NonValidatingNewAdminClientFn(mockAdminClient))\n\tdefer kafkaadmintesting.RestoreNewAdminClientFn()\n\n\t// Run The TableTest Using The KafkaChannel Reconciler Provided By The Factory\n\tlogger := logtesting.TestLogger(t)\n\ttableTest.Test(t, controllertesting.MakeFactory(func(ctx context.Context, listers *controllertesting.Listers, cmw configmap.Watcher, options map[string]interface{}) controller.Reconciler {\n\n\t\tconfigOptionsInt, ok := options[\"configOptions\"]\n\t\tif !ok || configOptionsInt == nil {\n\t\t\tconfigOptionsInt = []controllertesting.KafkaConfigOption{}\n\t\t}\n\t\tconfigOptions := configOptionsInt.([]controllertesting.KafkaConfigOption)\n\n\t\tr := &Reconciler{\n\t\t\tkubeClientset: kubeclient.Get(ctx),\n\t\t\tadminClientType: types.Kafka,\n\t\t\tadminClient: nil,\n\t\t\tenvironment: controllertesting.NewEnvironment(),\n\t\t\tconfig: controllertesting.NewConfig(configOptions...),\n\t\t\tkafkachannelLister: listers.GetKafkaChannelLister(),\n\t\t\tkafkachannelInformer: nil,\n\t\t\tdeploymentLister: listers.GetDeploymentLister(),\n\t\t\tserviceLister: listers.GetServiceLister(),\n\t\t\tkafkaClientSet: fakekafkaclient.Get(ctx),\n\t\t\tadminMutex: &sync.Mutex{},\n\t\t\tkafkaBrokers: controllertesting.KafkaSecretDataValueBrokers,\n\t\t\tkafkaSecret: controllertesting.KafkaSecretName,\n\t\t\tkafkaUsername: controllertesting.KafkaSecretDataValueUsername,\n\t\t\tkafkaPassword: controllertesting.KafkaSecretDataValuePassword,\n\t\t\tkafkaSaslType: controllertesting.KafkaSecretDataValueSaslType,\n\t\t\tkafkaConfigMapHash: controllertesting.ConfigMapHash,\n\t\t}\n\n\t\treconcilerOptions, ok := options[\"reconcilerOptions\"]\n\t\tif ok {\n\t\t\tfor _, option := range reconcilerOptions.([]reconcilerOption) {\n\t\t\t\toption(r)\n\t\t\t}\n\t\t}\n\n\t\treturn kafkachannelreconciler.NewReconciler(ctx, logger, r.kafkaClientSet, listers.GetKafkaChannelLister(), controller.GetEventRecorder(ctx), r)\n\t}, logger.Desugar()))\n}", "func TestConcurrentCreateBigDocuments(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skip on short tests\")\n\t}\n\n\t// Disable those tests for active failover\n\tif getTestMode() == testModeResilientSingle {\n\t\tt.Skip(\"Disabled in active failover mode\")\n\t}\n\n\t// don't use disallowUnknownFields in this test - we have here custom structs defined\n\tc := createClient(t, &testsClientConfig{skipDisallowUnknownFields: true})\n\n\tversion, err := c.Version(nil)\n\tif err != nil {\n\t\tt.Fatalf(\"Version failed: %s\", describe(err))\n\t}\n\tisv33p := version.Version.CompareTo(\"3.3\") >= 0\n\tif !isv33p && os.Getenv(\"TEST_CONNECTION\") == \"vst\" {\n\t\tt.Skip(\"Skipping VST load test on 3.2\")\n\t} else {\n\t\tdb := ensureDatabase(nil, c, \"document_test\", nil, t)\n\t\tcol := ensureCollection(nil, db, \"TestConcurrentCreateBigDocuments\", nil, t)\n\n\t\tdocChan := make(chan driver.DocumentMeta, 16*1024)\n\n\t\tcreator := func(limit, interval int) {\n\t\t\tdata := make([]byte, 1024)\n\t\t\tfor i := 0; i < limit; i++ {\n\t\t\t\trand.Read(data)\n\t\t\t\tctx := context.Background()\n\t\t\t\tdoc := UserDoc{\n\t\t\t\t\t\"Jan\" + strconv.Itoa(i) + hex.EncodeToString(data),\n\t\t\t\t\ti * interval,\n\t\t\t\t}\n\t\t\t\tmeta, err := col.CreateDocument(ctx, doc)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatalf(\"Failed to create new document: %s\", describe(err))\n\t\t\t\t}\n\t\t\t\tdocChan <- meta\n\t\t\t}\n\t\t}\n\n\t\treader := func() {\n\t\t\tfor {\n\t\t\t\tmeta, ok := <-docChan\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Document must exists now\n\t\t\t\tif found, err := col.DocumentExists(nil, meta.Key); err != nil {\n\t\t\t\t\tt.Fatalf(\"DocumentExists failed for '%s': %s\", meta.Key, describe(err))\n\t\t\t\t} else if !found {\n\t\t\t\t\tt.Errorf(\"DocumentExists returned false for '%s', expected true\", meta.Key)\n\t\t\t\t}\n\t\t\t\t// Read document\n\t\t\t\tvar readDoc UserDoc\n\t\t\t\tif _, err := col.ReadDocument(nil, meta.Key, &readDoc); err != nil {\n\t\t\t\t\tt.Fatalf(\"Failed to read document '%s': %s\", meta.Key, describe(err))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnoCreators := getIntFromEnv(\"NOCREATORS\", 25)\n\t\tnoReaders := getIntFromEnv(\"NOREADERS\", 50)\n\t\tnoDocuments := getIntFromEnv(\"NODOCUMENTS\", 100) // per creator\n\n\t\twgCreators := sync.WaitGroup{}\n\t\t// Run N concurrent creators\n\t\tfor i := 0; i < noCreators; i++ {\n\t\t\twgCreators.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wgCreators.Done()\n\t\t\t\tcreator(noDocuments, noCreators)\n\t\t\t}()\n\t\t}\n\t\twgReaders := sync.WaitGroup{}\n\t\t// Run M readers\n\t\tfor i := 0; i < noReaders; i++ {\n\t\t\twgReaders.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wgReaders.Done()\n\t\t\t\treader()\n\t\t\t}()\n\t\t}\n\t\twgCreators.Wait()\n\t\tclose(docChan)\n\t\twgReaders.Wait()\n\t}\n}", "func (m *MockFullNode) Concurrent(arg0 context.Context) int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Concurrent\", arg0)\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func TestActiveReplicatorPushFromCheckpointIgnored(t *testing.T) {\n\n\tbase.RequireNumTestBuckets(t, 2)\n\n\tbase.SetUpTestLogging(t, logger.LevelInfo, logger.KeyReplicate, logger.KeyHTTP, logger.KeyHTTPResp, logger.KeySync, logger.KeySyncMsg)\n\n\tconst (\n\t\tchangesBatchSize = 10\n\t\tnumRT1DocsInitial = 13 // 2 batches of changes\n\t\tnumRT1DocsTotal = 24 // 2 more batches\n\t)\n\n\t// Active\n\ttb1 := base.GetTestBucket(t)\n\trt1 := NewRestTester(t, &RestTesterConfig{\n\t\tTestBucket: tb1,\n\t})\n\tdefer rt1.Close()\n\n\t// Passive\n\ttb2 := base.GetTestBucket(t)\n\trt2 := NewRestTester(t, &RestTesterConfig{\n\t\tTestBucket: tb2,\n\t\tDatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{\n\t\t\tUsers: map[string]*db.PrincipalConfig{\n\t\t\t\t\"alice\": {\n\t\t\t\t\tPassword: base.StringPtr(\"pass\"),\n\t\t\t\t\tExplicitChannels: utils.SetOf(\"alice\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}},\n\t})\n\tdefer rt2.Close()\n\n\t// Create first batch of docs\n\tdocIDPrefix := t.Name() + \"doc\"\n\tfor i := 0; i < numRT1DocsInitial; i++ {\n\t\tresp := rt1.SendAdminRequest(http.MethodPut, fmt.Sprintf(\"/db/%s%d\", docIDPrefix, i), `{\"channels\":[\"alice\"]}`)\n\t\tassertStatus(t, resp, http.StatusCreated)\n\t\trt1RevID := respRevID(t, resp)\n\t\tresp = rt2.SendAdminRequest(http.MethodPut, fmt.Sprintf(\"/db/%s%d\", docIDPrefix, i), `{\"channels\":[\"alice\"]}`)\n\t\tassertStatus(t, resp, http.StatusCreated)\n\t\trt2RevID := respRevID(t, resp)\n\t\trequire.Equal(t, rt1RevID, rt2RevID)\n\t}\n\n\t// Make rt2 listen on an actual HTTP port, so it can receive the blipsync request from rt1\n\tsrv := httptest.NewServer(rt2.TestPublicHandler())\n\tdefer srv.Close()\n\n\t// Build passiveDBURL with basic auth creds\n\tpassiveDBURL, err := url.Parse(srv.URL + \"/db\")\n\trequire.NoError(t, err)\n\tpassiveDBURL.User = url.UserPassword(\"alice\", \"pass\")\n\n\tarConfig := db.ActiveReplicatorConfig{\n\t\tID: t.Name(),\n\t\tDirection: db.ActiveReplicatorTypePush,\n\t\tRemoteDBURL: passiveDBURL,\n\t\tActiveDB: &db.Database{\n\t\t\tDatabaseContext: rt1.GetDatabase(),\n\t\t},\n\t\tContinuous: true,\n\t\tChangesBatchSize: changesBatchSize,\n\t\tReplicationStatsMap: base.SyncGatewayStats.NewDBStats(t.Name(), false, false, false).DBReplicatorStats(t.Name()),\n\t}\n\n\t// Create the first active replicator to pull from seq:0\n\tar := db.NewActiveReplicator(&arConfig)\n\n\tstartNumChangesRequestedFromZeroTotal := rt1.GetDatabase().DbStats.CBLReplicationPull().NumPullReplSinceZero.Value()\n\n\tassert.NoError(t, ar.Start())\n\n\t_, ok := base.WaitForStat(func() int64 {\n\t\treturn ar.Push.Checkpointer.Stats().AlreadyKnownSequenceCount\n\t}, numRT1DocsInitial)\n\tassert.True(t, ok)\n\n\t// one _changes from seq:0 with initial number of docs sent\n\tnumChangesRequestedFromZeroTotal := rt1.GetDatabase().DbStats.CBLReplicationPull().NumPullReplSinceZero.Value()\n\tassert.Equal(t, startNumChangesRequestedFromZeroTotal+1, numChangesRequestedFromZeroTotal)\n\n\t// rev assertions\n\tnumRevsSentTotal := ar.Push.GetStats().SendRevCount.Value()\n\tassert.Equal(t, int64(0), numRevsSentTotal)\n\tassert.Equal(t, int64(0), ar.Push.Checkpointer.Stats().ProcessedSequenceCount)\n\tassert.Equal(t, int64(0), ar.Push.Checkpointer.Stats().ExpectedSequenceCount)\n\n\t// checkpoint assertions\n\tassert.Equal(t, int64(0), ar.Push.Checkpointer.Stats().GetCheckpointHitCount)\n\tassert.Equal(t, int64(1), ar.Push.Checkpointer.Stats().GetCheckpointMissCount)\n\tassert.Equal(t, int64(0), ar.Push.Checkpointer.Stats().SetCheckpointCount)\n\n\tassert.NoError(t, ar.Stop())\n\n\t// Second batch of docs\n\tfor i := numRT1DocsInitial; i < numRT1DocsTotal; i++ {\n\t\tresp := rt1.SendAdminRequest(http.MethodPut, fmt.Sprintf(\"/db/%s%d\", docIDPrefix, i), `{\"channels\":[\"alice\"]}`)\n\t\tassertStatus(t, resp, http.StatusCreated)\n\t\trt1RevID := respRevID(t, resp)\n\t\tresp = rt2.SendAdminRequest(http.MethodPut, fmt.Sprintf(\"/db/%s%d\", docIDPrefix, i), `{\"channels\":[\"alice\"]}`)\n\t\tassertStatus(t, resp, http.StatusCreated)\n\t\trt2RevID := respRevID(t, resp)\n\t\trequire.Equal(t, rt1RevID, rt2RevID)\n\t}\n\n\t// Create a new replicator using the same config, which should use the checkpoint set from the first.\n\tar = db.NewActiveReplicator(&arConfig)\n\tdefer func() { assert.NoError(t, ar.Stop()) }()\n\tassert.NoError(t, ar.Start())\n\n\t_, ok = base.WaitForStat(func() int64 {\n\t\treturn ar.Push.Checkpointer.Stats().AlreadyKnownSequenceCount\n\t}, numRT1DocsTotal-numRT1DocsInitial)\n\tassert.True(t, ok)\n\n\t// Make sure we've not started any more since:0 replications on rt1 since the first one\n\tendNumChangesRequestedFromZeroTotal := rt1.GetDatabase().DbStats.CBLReplicationPull().NumPullReplSinceZero.Value()\n\tassert.Equal(t, numChangesRequestedFromZeroTotal, endNumChangesRequestedFromZeroTotal)\n\n\t// make sure rt1 thinks it has sent all of the revs via a 2.x replicator\n\tnumRevsSentTotal = ar.Push.GetStats().SendRevCount.Value()\n\tassert.Equal(t, int64(0), numRevsSentTotal)\n\tassert.Equal(t, int64(0), ar.Push.Checkpointer.Stats().ProcessedSequenceCount)\n\tassert.Equal(t, int64(0), ar.Push.Checkpointer.Stats().ExpectedSequenceCount)\n\n\t// assert the second active replicator stats\n\tassert.Equal(t, int64(1), ar.Push.Checkpointer.Stats().GetCheckpointHitCount)\n\tassert.Equal(t, int64(0), ar.Push.Checkpointer.Stats().GetCheckpointMissCount)\n\tassert.Equal(t, int64(0), ar.Push.Checkpointer.Stats().SetCheckpointCount)\n\tar.Push.Checkpointer.CheckpointNow()\n\tassert.Equal(t, int64(1), ar.Push.Checkpointer.Stats().SetCheckpointCount)\n}", "func updatePodTests() []*SerialTestCase {\n\tsequence1Tests := []*SerialTestCase{\n\t\t{\n\t\t\tDescription: \"Sequence 1: Pod A create --> Policy create --> Pod A cleanup --> Pod B create\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// old labels (not yet garbage collected)\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t\t// new labels\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tDescription: \"Sequence 1: Policy create --> Pod A create --> Pod A cleanup --> Pod B create\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// old labels (not yet garbage collected)\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t\t// new labels\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tDescription: \"Sequence 1: Policy create --> Pod A create --> Pod A cleanup --> Pod B create (skip first apply DP)\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// old labels (not yet garbage collected)\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t\t// new labels\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tDescription: \"Sequence 1: Policy create --> Pod A create --> Pod A cleanup --> Pod B create (skip first two apply DP)\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// old labels (not yet garbage collected)\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t\t// new labels\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tsequence2Tests := []*SerialTestCase{\n\t\t{\n\t\t\tDescription: \"Sequence 2 with Calico network\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: windowsCalicoDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// IP temporarily associated with IPSets of both pod A and pod B\n\t\t\t\t\t// Pod A sets\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set, ip1),\n\t\t\t\t\t// Pod B sets\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-baseazurewireserver\",\n\t\t\t\t\t\t\tAction: \"Block\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tPriority: 200,\n\t\t\t\t\t\t\tRemoteAddresses: \"168.63.129.16/32\",\n\t\t\t\t\t\t\tRemotePorts: \"80\",\n\t\t\t\t\t\t\tProtocols: \"6\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-baseallowinswitch\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tPriority: 65499,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-baseallowoutswitch\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tPriority: 65499,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-baseallowinhost\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tPriority: 0,\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\t// RuleType is unsupported in FakeEndpointPolicy\n\t\t\t\t\t\t\t// RuleType: \"Host\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-baseallowouthost\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tPriority: 0,\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\t// RuleType is unsupported in FakeEndpointPolicy\n\t\t\t\t\t\t\t// RuleType: \"Host\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tDescription: \"Sequence 2: Policy create --> Pod A Create --> Pod B create\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// IP temporarily associated with IPSets of both pod A and pod B\n\t\t\t\t\t// Pod A sets\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set, ip1),\n\t\t\t\t\t// Pod B sets\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tDescription: \"Sequence 2: Policy create --> Pod A Create --> Pod B create --> Pod A cleanup\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// old labels (not yet garbage collected)\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t\t// new labels\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// skipping this test. See PR #1856\n\t\t\tDescription: \"Sequence 2: Policy create --> Pod A Create --> Pod B create (skip first ApplyDP())\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// IP temporarily associated with IPSets of both pod A and pod B\n\t\t\t\t\t// Pod A sets\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set, ip1),\n\t\t\t\t\t// Pod B sets\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// skipping this test. See PR #1856\n\t\t\tDescription: \"Sequence 2: Policy create --> Pod A Create --> Pod B create --> Pod A cleanup (skip first two ApplyDP())\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// old labels (not yet garbage collected)\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t\t// new labels\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\totherTests := []*SerialTestCase{\n\t\t{\n\t\t\tDescription: \"ignore Pod update if added then deleted before ApplyDP()\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet),\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// doesn't really enforce behavior in DP, but one could look at logs to make sure we don't make a reset ACL SysCall into HNS\n\t\t\tDescription: \"ignore Pod delete for deleted endpoint\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tDeleteEndpoint(endpoint1),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet),\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: nil,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// doesn't really enforce behavior in DP, but one could look at logs to make sure we don't make a reset ACL SysCall into HNS\n\t\t\tDescription: \"ignore Pod delete for deleted endpoint (skip first ApplyDP())\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tDeleteEndpoint(endpoint1),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet),\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: nil,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// doesn't really enforce behavior in DP, but one could look at logs to make sure we don't make an add ACL SysCall into HNS\"\n\t\t\tDescription: \"ignore Pod update when there's no corresponding endpoint\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tDeleteEndpoint(endpoint1),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: nil,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tDescription: \"two endpoints, one with policy, one without\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tCreateEndpoint(endpoint2, ip2),\n\t\t\t\tCreatePod(\"x\", \"b\", ip2, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1, ip2),\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip2),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip2),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {},\n\t\t\t\t\tendpoint2: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tallTests := sequence1Tests\n\tallTests = append(allTests, sequence2Tests...)\n\t// allTests = append(allTests, podAssignmentSequence3Tests()...)\n\t// make golint happy\n\t_ = podAssignmentSequence3Tests()\n\tallTests = append(allTests, otherTests...)\n\treturn allTests\n}", "func TestConsulStateDriverWatchAllStateCreate(t *testing.T) {\n\tdriver := setupConsulDriver(t)\n\tcommonTestStateDriverWatchAllStateCreate(t, driver)\n}", "func (factory *DeploymentCancellationControllerFactory) Create() controller.RunnableController {\n\tdeploymentLW := &deployutil.ListWatcherImpl{\n\t\t// TODO: Investigate specifying annotation field selectors to fetch only 'deployments'\n\t\t// Currently field selectors are not supported for replication controllers\n\t\tListFunc: func() (runtime.Object, error) {\n\t\t\treturn factory.KubeClient.ReplicationControllers(kapi.NamespaceAll).List(labels.Everything())\n\t\t},\n\t\tWatchFunc: func(resourceVersion string) (watch.Interface, error) {\n\t\t\treturn factory.KubeClient.ReplicationControllers(kapi.NamespaceAll).Watch(labels.Everything(), fields.Everything(), resourceVersion)\n\t\t},\n\t}\n\tdeploymentQueue := cache.NewFIFO(cache.MetaNamespaceKeyFunc)\n\tcache.NewReflector(deploymentLW, &kapi.ReplicationController{}, deploymentQueue, 2*time.Minute).Run()\n\n\teventBroadcaster := record.NewBroadcaster()\n\teventBroadcaster.StartRecordingToSink(factory.KubeClient.Events(\"\"))\n\n\tdeployController := &DeploymentCancellationController{\n\t\tpodClient: &podClientImpl{\n\t\t\tgetPodFunc: func(namespace, name string) (*kapi.Pod, error) {\n\t\t\t\treturn factory.KubeClient.Pods(namespace).Get(name)\n\t\t\t},\n\t\t\tupdatePodFunc: func(namespace string, pod *kapi.Pod) (*kapi.Pod, error) {\n\t\t\t\treturn factory.KubeClient.Pods(namespace).Update(pod)\n\t\t\t},\n\t\t},\n\t\trecorder: eventBroadcaster.NewRecorder(kapi.EventSource{Component: \"deployer\"}),\n\t}\n\n\treturn &controller.RetryController{\n\t\tQueue: deploymentQueue,\n\t\tRetryManager: controller.NewQueueRetryManager(\n\t\t\tdeploymentQueue,\n\t\t\tcache.MetaNamespaceKeyFunc,\n\t\t\tfunc(obj interface{}, err error, retries controller.Retry) bool { return retries.Count < 1 },\n\t\t\tkutil.NewTokenBucketRateLimiter(1, 10),\n\t\t),\n\t\tHandle: func(obj interface{}) error {\n\t\t\tdeployment := obj.(*kapi.ReplicationController)\n\t\t\treturn deployController.Handle(deployment)\n\t\t},\n\t}\n}", "func CreatePods(f *framework.Framework, appName string, ns string, labels map[string]string, spec v1.PodSpec, maxCount int, tuning *TuningSetType) {\n\tfor i := 0; i < maxCount; i++ {\n\t\tframework.Logf(\"%v/%v : Creating pod\", i+1, maxCount)\n\t\t// Retry on pod creation failure\n\t\tfor retryCount := 0; retryCount < maxRetries; retryCount++ {\n\t\t\t_, err := f.ClientSet.Core().Pods(ns).Create(&v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: fmt.Sprintf(appName+\"-pod-%v\", i),\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: spec,\n\t\t\t})\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tframework.ExpectNoError(err)\n\t\t}\n\t\tif tuning != nil {\n\t\t\t// If a rate limit has been defined we wait for N ms between creation\n\t\t\tif tuning.Pods.RateLimit.Delay != 0 {\n\t\t\t\tframework.Logf(\"Sleeping %d ms between podcreation.\", tuning.Pods.RateLimit.Delay)\n\t\t\t\ttime.Sleep(tuning.Pods.RateLimit.Delay * time.Millisecond)\n\t\t\t}\n\t\t\t// If a stepping tuningset has been defined in the config, we wait for the step of pods to be created, and pause\n\t\t\tif tuning.Pods.Stepping.StepSize != 0 && (i+1)%tuning.Pods.Stepping.StepSize == 0 {\n\t\t\t\tverifyRunning := f.NewClusterVerification(\n\t\t\t\t\t&v1.Namespace{\n\t\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\t\tName: ns,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tStatus: v1.NamespaceStatus{},\n\t\t\t\t\t},\n\t\t\t\t\tframework.PodStateVerification{\n\t\t\t\t\t\tSelectors: labels,\n\t\t\t\t\t\tValidPhases: []v1.PodPhase{v1.PodRunning},\n\t\t\t\t\t},\n\t\t\t\t)\n\n\t\t\t\tpods, err := verifyRunning.WaitFor(i+1, tuning.Pods.Stepping.Timeout*time.Second)\n\t\t\t\tif err != nil {\n\t\t\t\t\tframework.Failf(\"Error in wait... %v\", err)\n\t\t\t\t} else if len(pods) < i+1 {\n\t\t\t\t\tframework.Failf(\"Only got %v out of %v\", len(pods), i+1)\n\t\t\t\t}\n\n\t\t\t\tframework.Logf(\"We have created %d pods and are now sleeping for %d seconds\", i+1, tuning.Pods.Stepping.Pause)\n\t\t\t\ttime.Sleep(tuning.Pods.Stepping.Pause * time.Second)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestCoilSetup() {\n\tIt(\"should be deployed successfully\", func() {\n\t\tBy(\"preparing etcd user and certificates\")\n\t\texecSafeAt(boot0, \"ckecli\", \"etcd\", \"user-add\", \"coil\", \"/coil/\")\n\n\t\t_, stderr, err := execAt(boot0, \"ckecli\", \"etcd\", \"issue\", \"coil\", \"--output\", \"file\")\n\t\tExpect(err).ShouldNot(HaveOccurred(), \"stderr=%s\", stderr)\n\n\t\t_, stderr, err = execAt(boot0, \"kubectl\", \"--namespace=kube-system\", \"create\", \"secret\",\n\t\t\t\"generic\", \"coil-etcd-secrets\",\n\t\t\t\"--from-file=etcd-ca.crt\",\n\t\t\t\"--from-file=etcd-coil.crt\",\n\t\t\t\"--from-file=etcd-coil.key\")\n\t\tExpect(err).ShouldNot(HaveOccurred(), \"stderr=%s\", stderr)\n\n\t\tBy(\"waiting for coil-node DaemonSet and coil-controllers Deployment\")\n\t\tcheckCoilNodeDaemonSet()\n\t\tcheckCoilControllersDeployment()\n\n\t\tEventually(func() error {\n\t\t\tstdout, _, err := execAt(boot0, \"kubectl\", \"get\", \"nodes\", \"-o\", \"json\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tvar nl corev1.NodeList\n\t\t\terr = json.Unmarshal(stdout, &nl)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tOUTER:\n\t\t\tfor _, n := range nl.Items {\n\t\t\t\tfor _, cond := range n.Status.Conditions {\n\t\t\t\t\tif cond.Type != corev1.NodeReady {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif cond.Status != corev1.ConditionTrue {\n\t\t\t\t\t\treturn fmt.Errorf(\"node %s is not ready\", n.Name)\n\t\t\t\t\t}\n\t\t\t\t\tcontinue OUTER\n\t\t\t\t}\n\n\t\t\t\treturn fmt.Errorf(\"node %s has no readiness status\", n.Name)\n\t\t\t}\n\t\t\treturn nil\n\t\t}).Should(Succeed())\n\n\t\tBy(\"waiting for kube-system/cke-etcd getting created\")\n\t\tEventually(func() error {\n\t\t\t_, _, err := execAt(boot0, \"kubectl\", \"--namespace=kube-system\", \"get\", \"endpoints/cke-etcd\")\n\t\t\treturn err\n\t\t}).Should(Succeed())\n\n\t\tBy(\"creating IP address pool\")\n\t\tstdout, stderr, err := execAt(boot0, \"kubectl\", \"--namespace=kube-system\", \"get\", \"pods\", \"--selector=app.kubernetes.io/name=coil-controllers\", \"-o=json\")\n\t\tExpect(err).NotTo(HaveOccurred(), \"stdout=%s, stderr=%s\", stdout, stderr)\n\n\t\tpodList := new(corev1.PodList)\n\t\terr = json.Unmarshal(stdout, podList)\n\t\tExpect(err).NotTo(HaveOccurred())\n\t\tExpect(len(podList.Items)).To(Equal(1))\n\t\tpodName := podList.Items[0].Name\n\n\t\t// create non-default pools first to prevent misuse of default pool\n\t\t_, stderr, err = execAt(boot0, \"kubectl\", \"--namespace=kube-system\", \"exec\", podName, \"/coilctl\", \"pool\", \"create\", \"internet-egress\", \"172.19.0.0/28\", \"0\")\n\t\tExpect(err).NotTo(HaveOccurred(), \"stderr=%s\", stderr)\n\t\t_, stderr, err = execAt(boot0, \"kubectl\", \"--namespace=kube-system\", \"exec\", podName, \"/coilctl\", \"pool\", \"create\", \"default\", \"10.64.0.0/14\", \"5\")\n\t\tExpect(err).NotTo(HaveOccurred(), \"stderr=%s\", stderr)\n\t})\n}", "func startServerAndControllers(t *testing.T) (\n\t*kubefake.Clientset,\n\twatch.Interface,\n\tclustopclientset.Interface,\n\tcapiclientset.Interface,\n\t*capifakeclientset.Clientset,\n\tfunc()) {\n\n\t// create a fake kube client\n\tfakePtr := clientgotesting.Fake{}\n\tscheme := runtime.NewScheme()\n\tcodecs := serializer.NewCodecFactory(scheme)\n\tmetav1.AddToGroupVersion(scheme, schema.GroupVersion{Version: \"v1\"})\n\tkubefake.AddToScheme(scheme)\n\tobjectTracker := clientgotesting.NewObjectTracker(scheme, codecs.UniversalDecoder())\n\tkubeWatch := watch.NewRaceFreeFake()\n\t// Add a reactor for sending watch events when a job is modified\n\tobjectReaction := clientgotesting.ObjectReaction(objectTracker)\n\tfakePtr.AddReactor(\"*\", \"jobs\", func(action clientgotesting.Action) (bool, runtime.Object, error) {\n\t\tvar deletedObj runtime.Object\n\t\tif action, ok := action.(clientgotesting.DeleteActionImpl); ok {\n\t\t\tdeletedObj, _ = objectTracker.Get(action.GetResource(), action.GetNamespace(), action.GetName())\n\t\t}\n\t\thandled, obj, err := objectReaction(action)\n\t\tswitch action.(type) {\n\t\tcase clientgotesting.CreateActionImpl:\n\t\t\tkubeWatch.Add(obj)\n\t\tcase clientgotesting.UpdateActionImpl:\n\t\t\tkubeWatch.Modify(obj)\n\t\tcase clientgotesting.DeleteActionImpl:\n\t\t\tif deletedObj != nil {\n\t\t\t\tkubeWatch.Delete(deletedObj)\n\t\t\t}\n\t\t}\n\t\treturn handled, obj, err\n\t})\n\tfakePtr.AddWatchReactor(\"*\", clientgotesting.DefaultWatchReactor(kubeWatch, nil))\n\t// Create actual fake kube client\n\tfakeKubeClient := &kubefake.Clientset{Fake: fakePtr}\n\n\t// start the cluster-operator api server\n\tapiServerClientConfig, shutdownServer := servertesting.StartTestServerOrDie(t)\n\n\t// create a cluster-operator client\n\tclustopClient, err := clustopclientset.NewForConfig(apiServerClientConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\t// create a cluster-api client\n\tcapiClient, err := capiclientset.NewForConfig(apiServerClientConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\tfakeCAPIClient := &capifakeclientset.Clientset{}\n\n\t// create informers\n\tkubeInformerFactory := kubeinformers.NewSharedInformerFactory(fakeKubeClient, 10*time.Second)\n\tbatchSharedInformers := kubeInformerFactory.Batch().V1()\n\tclustopInformerFactory := clustopinformers.NewSharedInformerFactory(clustopClient, 10*time.Second)\n\tcapiInformerFactory := capiinformers.NewSharedInformerFactory(capiClient, 10*time.Second)\n\tcapiSharedInformers := capiInformerFactory.Cluster().V1alpha1()\n\n\t// create controllers\n\tstopCh := make(chan struct{})\n\tt.Log(\"controller start\")\n\t// Note that controllers must be created prior to starting the informers.\n\t// Otherwise, the controllers will not get the initial sync from the\n\t// informer and will time out waiting to sync.\n\trunControllers := []func(){\n\t\t// infra\n\t\tfunc() func() {\n\t\t\tcontroller := infracontroller.NewController(\n\t\t\t\tcapiSharedInformers.Clusters(),\n\t\t\t\tbatchSharedInformers.Jobs(),\n\t\t\t\tfakeKubeClient,\n\t\t\t\tclustopClient,\n\t\t\t\tcapiClient,\n\t\t\t)\n\t\t\treturn func() { controller.Run(1, stopCh) }\n\t\t}(),\n\t\t// master\n\t\tfunc() func() {\n\t\t\tcontroller := mastercontroller.NewController(\n\t\t\t\tcapiSharedInformers.Clusters(),\n\t\t\t\tcapiSharedInformers.MachineSets(),\n\t\t\t\tbatchSharedInformers.Jobs(),\n\t\t\t\tfakeKubeClient,\n\t\t\t\tclustopClient,\n\t\t\t\tcapiClient,\n\t\t\t)\n\t\t\treturn func() { controller.Run(1, stopCh) }\n\t\t}(),\n\t\t// components\n\t\tfunc() func() {\n\t\t\tcontroller := componentscontroller.NewController(\n\t\t\t\tcapiSharedInformers.Clusters(),\n\t\t\t\tcapiSharedInformers.MachineSets(),\n\t\t\t\tbatchSharedInformers.Jobs(),\n\t\t\t\tfakeKubeClient,\n\t\t\t\tclustopClient,\n\t\t\t\tcapiClient,\n\t\t\t)\n\t\t\treturn func() { controller.Run(1, stopCh) }\n\t\t}(),\n\t\t// nodeconfig\n\t\tfunc() func() {\n\t\t\tcontroller := nodeconfigcontroller.NewController(\n\t\t\t\tcapiSharedInformers.Clusters(),\n\t\t\t\tcapiSharedInformers.MachineSets(),\n\t\t\t\tbatchSharedInformers.Jobs(),\n\t\t\t\tfakeKubeClient,\n\t\t\t\tclustopClient,\n\t\t\t\tcapiClient,\n\t\t\t)\n\t\t\treturn func() { controller.Run(1, stopCh) }\n\t\t}(),\n\t\t// deployclusterapi\n\t\tfunc() func() {\n\t\t\tcontroller := deployclusterapicontroller.NewController(\n\t\t\t\tcapiSharedInformers.Clusters(),\n\t\t\t\tcapiSharedInformers.MachineSets(),\n\t\t\t\tbatchSharedInformers.Jobs(),\n\t\t\t\tfakeKubeClient,\n\t\t\t\tclustopClient,\n\t\t\t\tcapiClient,\n\t\t\t)\n\t\t\treturn func() { controller.Run(1, stopCh) }\n\t\t}(),\n\t\t// awselb\n\t\tfunc() func() {\n\t\t\tcontroller := awselb.NewController(\n\t\t\t\tcapiSharedInformers.Machines(),\n\t\t\t\tfakeKubeClient,\n\t\t\t\tclustopClient,\n\t\t\t\tcapiClient,\n\t\t\t)\n\t\t\treturn func() { controller.Run(1, stopCh) }\n\t\t}(),\n\t}\n\tvar wg sync.WaitGroup\n\twg.Add(len(runControllers))\n\tfor _, run := range runControllers {\n\t\tgo func(r func()) {\n\t\t\tdefer wg.Done()\n\t\t\tr()\n\t\t}(run)\n\t}\n\n\tt.Log(\"informers start\")\n\tkubeInformerFactory.Start(stopCh)\n\tclustopInformerFactory.Start(stopCh)\n\tcapiInformerFactory.Start(stopCh)\n\n\tshutdown := func() {\n\t\t// Shut down controller\n\t\tclose(stopCh)\n\t\t// Wait for all controller to stop\n\t\twg.Wait()\n\t\t// Shut down api server\n\t\tshutdownServer()\n\t}\n\n\treturn fakeKubeClient, kubeWatch, clustopClient, capiClient, fakeCAPIClient, shutdown\n}", "func (m *MockMeshServiceControllerFactory) Build(mgr mc_manager.AsyncManager, clusterName string) (controller.MeshServiceController, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", mgr, clusterName)\n\tret0, _ := ret[0].(controller.MeshServiceController)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestCommitLogActiveLogsConcurrency(t *testing.T) {\n\tvar (\n\t\topts, _ = newTestOptions(t, overrides{\n\t\t\tstrategy: StrategyWriteBehind,\n\t\t})\n\t\tnumFilesRequired = 10\n\t)\n\n\tdefer cleanup(t, opts)\n\n\tvar (\n\t\tdoneCh = make(chan struct{})\n\t\tcommitLog = newTestCommitLog(t, opts)\n\t)\n\n\t// One goroutine continuously writing.\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-doneCh:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\ttime.Sleep(time.Millisecond)\n\t\t\t\terr := commitLog.Write(\n\t\t\t\t\tcontext.NewBackground(),\n\t\t\t\t\ttestSeries(t, opts, 0, \"foo.bar\", testTags1, 127),\n\t\t\t\t\tts.Datapoint{},\n\t\t\t\t\txtime.Second,\n\t\t\t\t\tnil)\n\t\t\t\tif err == errCommitLogClosed {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err == ErrCommitLogQueueFull {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\t// One goroutine continuously rotating the logs.\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-doneCh:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\ttime.Sleep(time.Millisecond)\n\t\t\t\t_, err := commitLog.RotateLogs()\n\t\t\t\tif err == errCommitLogClosed {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\t// One goroutine continuously checking active logs.\n\tgo func() {\n\t\tvar (\n\t\t\tlastSeenFile string\n\t\t\tnumFilesSeen int\n\t\t)\n\t\tfor numFilesSeen < numFilesRequired {\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\tlogs, err := commitLog.ActiveLogs()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trequire.Equal(t, 2, len(logs))\n\t\t\tif logs[0].FilePath != lastSeenFile {\n\t\t\t\tlastSeenFile = logs[0].FilePath\n\t\t\t\tnumFilesSeen++\n\t\t\t}\n\t\t}\n\t\tclose(doneCh)\n\t}()\n\n\t<-doneCh\n\n\trequire.NoError(t, commitLog.Close())\n}", "func ecsPodTests() map[string]func(ctx context.Context, t *testing.T, pc cocoa.ECSPodCreator, c *ECSClient, smc *SecretsManagerClient) {\n\tmakeSecretEnvVar := func(t *testing.T) *cocoa.EnvironmentVariable {\n\t\treturn cocoa.NewEnvironmentVariable().\n\t\t\tSetName(t.Name()).\n\t\t\tSetSecretOptions(*cocoa.NewSecretOptions().\n\t\t\t\tSetName(t.Name()).\n\t\t\t\tSetValue(utility.RandomString()).\n\t\t\t\tSetOwned(true))\n\t}\n\tmakeContainerDef := func(t *testing.T) *cocoa.ECSContainerDefinition {\n\t\treturn cocoa.NewECSContainerDefinition().\n\t\t\tSetImage(\"image\").\n\t\t\tSetMemoryMB(128).\n\t\t\tSetCPU(128).\n\t\t\tSetName(\"container\")\n\t}\n\n\tmakePodCreationOpts := func(t *testing.T) *cocoa.ECSPodCreationOptions {\n\t\treturn cocoa.NewECSPodCreationOptions().\n\t\t\tSetName(testutil.NewTaskDefinitionFamily(t.Name())).\n\t\t\tSetMemoryMB(128).\n\t\t\tSetCPU(128).\n\t\t\tSetTaskRole(testutil.TaskRole()).\n\t\t\tSetExecutionRole(testutil.ExecutionRole()).\n\t\t\tSetExecutionOptions(*cocoa.NewECSPodExecutionOptions().\n\t\t\t\tSetCluster(testutil.ECSClusterName()))\n\t}\n\n\tcheckPodDeleted := func(ctx context.Context, t *testing.T, p cocoa.ECSPod, c cocoa.ECSClient, smc cocoa.SecretsManagerClient, opts cocoa.ECSPodCreationOptions) {\n\t\tstat := p.StatusInfo()\n\t\tassert.Equal(t, cocoa.StatusDeleted, stat.Status)\n\n\t\tres := p.Resources()\n\n\t\tdescribeTaskDef, err := c.DescribeTaskDefinition(ctx, &awsECS.DescribeTaskDefinitionInput{\n\t\t\tTaskDefinition: res.TaskDefinition.ID,\n\t\t})\n\t\trequire.NoError(t, err)\n\t\trequire.NotZero(t, describeTaskDef.TaskDefinition)\n\t\tassert.Equal(t, utility.FromStringPtr(opts.Name), utility.FromStringPtr(describeTaskDef.TaskDefinition.Family))\n\n\t\tdescribeTasks, err := c.DescribeTasks(ctx, &awsECS.DescribeTasksInput{\n\t\t\tCluster: res.Cluster,\n\t\t\tTasks: []*string{res.TaskID},\n\t\t})\n\t\trequire.NoError(t, err)\n\t\tassert.Empty(t, describeTasks.Failures)\n\t\trequire.Len(t, describeTasks.Tasks, 1)\n\t\tassert.Equal(t, awsECS.DesiredStatusStopped, utility.FromStringPtr(describeTasks.Tasks[0].LastStatus))\n\n\t\tfor _, containerRes := range res.Containers {\n\t\t\tfor _, s := range containerRes.Secrets {\n\t\t\t\t_, err := smc.DescribeSecret(ctx, &secretsmanager.DescribeSecretInput{\n\t\t\t\t\tSecretId: s.Name,\n\t\t\t\t})\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\t_, err = smc.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{\n\t\t\t\t\tSecretId: s.Name,\n\t\t\t\t})\n\t\t\t\tassert.Error(t, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn map[string]func(ctx context.Context, t *testing.T, pc cocoa.ECSPodCreator, c *ECSClient, smc *SecretsManagerClient){\n\t\t\"StopIsIdempotentWhenItFails\": func(ctx context.Context, t *testing.T, pc cocoa.ECSPodCreator, c *ECSClient, smc *SecretsManagerClient) {\n\t\t\topts := makePodCreationOpts(t).AddContainerDefinitions(*makeContainerDef(t))\n\t\t\tp, err := pc.CreatePod(ctx, opts)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tc.StopTaskError = errors.New(\"fake error\")\n\n\t\t\trequire.Error(t, p.Stop(ctx))\n\n\t\t\tstat := p.StatusInfo()\n\t\t\tassert.Equal(t, cocoa.StatusStarting, stat.Status)\n\n\t\t\tc.StopTaskError = nil\n\n\t\t\trequire.NoError(t, p.Stop(ctx))\n\t\t\tstat = p.StatusInfo()\n\t\t\tassert.Equal(t, cocoa.StatusStopped, stat.Status)\n\t\t},\n\t\t\"DeleteIsIdempotentWhenStoppingTaskFails\": func(ctx context.Context, t *testing.T, pc cocoa.ECSPodCreator, c *ECSClient, smc *SecretsManagerClient) {\n\t\t\topts := makePodCreationOpts(t).AddContainerDefinitions(\n\t\t\t\t*makeContainerDef(t).AddEnvironmentVariables(\n\t\t\t\t\t*makeSecretEnvVar(t),\n\t\t\t\t),\n\t\t\t)\n\t\t\tp, err := pc.CreatePod(ctx, opts)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tc.StopTaskError = errors.New(\"fake error\")\n\n\t\t\trequire.Error(t, p.Delete(ctx))\n\n\t\t\tstat := p.StatusInfo()\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, cocoa.StatusStarting, stat.Status)\n\n\t\t\tc.StopTaskError = nil\n\n\t\t\trequire.NoError(t, p.Delete(ctx))\n\n\t\t\tcheckPodDeleted(ctx, t, p, c, smc, *opts)\n\t\t},\n\t\t\"DeleteIsIdempotentWhenDeregisteringTaskDefinitionFails\": func(ctx context.Context, t *testing.T, pc cocoa.ECSPodCreator, c *ECSClient, smc *SecretsManagerClient) {\n\t\t\topts := makePodCreationOpts(t).AddContainerDefinitions(\n\t\t\t\t*makeContainerDef(t).AddEnvironmentVariables(\n\t\t\t\t\t*makeSecretEnvVar(t),\n\t\t\t\t),\n\t\t\t)\n\t\t\tp, err := pc.CreatePod(ctx, opts)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tc.DeregisterTaskDefinitionError = errors.New(\"fake error\")\n\n\t\t\trequire.Error(t, p.Delete(ctx))\n\n\t\t\tstat := p.StatusInfo()\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, cocoa.StatusStopped, stat.Status)\n\n\t\t\tc.DeregisterTaskDefinitionError = nil\n\n\t\t\trequire.NoError(t, p.Delete(ctx))\n\n\t\t\tcheckPodDeleted(ctx, t, p, c, smc, *opts)\n\t\t},\n\t\t\"DeleteIsIdempotentWhenDeletingSecretsFails\": func(ctx context.Context, t *testing.T, pc cocoa.ECSPodCreator, c *ECSClient, smc *SecretsManagerClient) {\n\t\t\topts := makePodCreationOpts(t).AddContainerDefinitions(\n\t\t\t\t*makeContainerDef(t).AddEnvironmentVariables(\n\t\t\t\t\t*makeSecretEnvVar(t),\n\t\t\t\t),\n\t\t\t)\n\t\t\tp, err := pc.CreatePod(ctx, opts)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tsmc.DeleteSecretError = errors.New(\"fake error\")\n\n\t\t\trequire.Error(t, p.Delete(ctx))\n\n\t\t\tstat := p.StatusInfo()\n\t\t\tassert.Equal(t, cocoa.StatusStopped, stat.Status)\n\n\t\t\tsmc.DeleteSecretError = nil\n\n\t\t\trequire.NoError(t, p.Delete(ctx))\n\n\t\t\tcheckPodDeleted(ctx, t, p, c, smc, *opts)\n\t\t},\n\t}\n}", "func TestHandleStoppedToSteadyStateTransition(t *testing.T) {\n\ttaskEngine := &DockerTaskEngine{}\n\tfirstContainerName := \"container1\"\n\tfirstContainer := &apicontainer.Container{\n\t\tKnownStatusUnsafe: apicontainerstatus.ContainerStopped,\n\t\tName: firstContainerName,\n\t}\n\tsecondContainerName := \"container2\"\n\tsecondContainer := &apicontainer.Container{\n\t\tKnownStatusUnsafe: apicontainerstatus.ContainerRunning,\n\t\tDesiredStatusUnsafe: apicontainerstatus.ContainerRunning,\n\t\tName: secondContainerName,\n\t}\n\n\tctx, cancel := context.WithCancel(context.TODO())\n\tdefer cancel()\n\n\tmTask := &managedTask{\n\t\tTask: &apitask.Task{\n\t\t\tContainers: []*apicontainer.Container{\n\t\t\t\tfirstContainer,\n\t\t\t\tsecondContainer,\n\t\t\t},\n\t\t\tArn: \"task1\",\n\t\t},\n\t\tengine: taskEngine,\n\t\tacsMessages: make(chan acsTransition),\n\t\tdockerMessages: make(chan dockerContainerChange),\n\t\tctx: ctx,\n\t}\n\ttaskEngine.managedTasks = make(map[string]*managedTask)\n\ttaskEngine.managedTasks[\"task1\"] = mTask\n\n\tvar waitForTransitionFunctionInvocation sync.WaitGroup\n\twaitForTransitionFunctionInvocation.Add(1)\n\ttransitionFunction := func(task *apitask.Task, container *apicontainer.Container) dockerapi.DockerContainerMetadata {\n\t\tassert.Equal(t, firstContainerName, container.Name,\n\t\t\t\"Mismatch in container reference in transition function\")\n\t\twaitForTransitionFunctionInvocation.Done()\n\t\treturn dockerapi.DockerContainerMetadata{}\n\t}\n\n\ttaskEngine.containerStatusToTransitionFunction = map[apicontainerstatus.ContainerStatus]transitionApplyFunc{\n\t\tapicontainerstatus.ContainerStopped: transitionFunction,\n\t}\n\n\t// Received RUNNING event, known status is not STOPPED, expect this to\n\t// be a noop. Assertions in transitionFunction asserts that as well\n\tmTask.handleStoppedToRunningContainerTransition(\n\t\tapicontainerstatus.ContainerRunning, secondContainer)\n\n\t// Start building preconditions and assertions for STOPPED -> RUNNING\n\t// transition that will be triggered by next invocation of\n\t// handleStoppedToRunningContainerTransition\n\n\t// This wait group ensures that a docker message is generated as a\n\t// result of the transition function\n\tvar waitForDockerMessageAssertions sync.WaitGroup\n\twaitForDockerMessageAssertions.Add(1)\n\tgo func() {\n\t\tdockerMessage := <-mTask.dockerMessages\n\t\tassert.Equal(t, apicontainerstatus.ContainerStopped, dockerMessage.event.Status,\n\t\t\t\"Mismatch in event status\")\n\t\tassert.Equal(t, firstContainerName, dockerMessage.container.Name,\n\t\t\t\"Mismatch in container reference in event\")\n\t\twaitForDockerMessageAssertions.Done()\n\t}()\n\t// Received RUNNING, known status is STOPPED, expect this to invoke\n\t// transition function once\n\tmTask.handleStoppedToRunningContainerTransition(\n\t\tapicontainerstatus.ContainerRunning, firstContainer)\n\n\t// Wait for wait groups to be done\n\twaitForTransitionFunctionInvocation.Wait()\n\twaitForDockerMessageAssertions.Wait()\n\n\t// We now have an empty transition function map. Any further transitions\n\t// should be noops\n\tdelete(taskEngine.containerStatusToTransitionFunction, apicontainerstatus.ContainerStopped)\n\t// Simulate getting RUNNING event for a STOPPED container 10 times.\n\t// All of these should be noops. 10 is chosen arbitrarily. Any number > 0\n\t// should be fine here\n\tfor i := 0; i < 10; i++ {\n\t\tmTask.handleStoppedToRunningContainerTransition(\n\t\t\tapicontainerstatus.ContainerRunning, firstContainer)\n\t}\n}", "func TestNewAutoscalingPolicyController(t *testing.T) {\n\tapc := initalizeFakeAutoscalingPolicyController()\n\n\t// test to make sure new creating a autoscaling controller is being\n\t// created and returned\n\tassert.Equal(t, autoscalingPolicySyncControllerName, apc.syncController.name)\n}", "func (m *MockMeshWorkloadControllerFactory) Build(mgr mc_manager.AsyncManager, clusterName string) (controller.MeshWorkloadController, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", mgr, clusterName)\n\tret0, _ := ret[0].(controller.MeshWorkloadController)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestCancelJobSomeWorkersOccupied(t *testing.T) {\n\ts := newTestingServer()\n\tmux := SetupRoutes(s)\n\n\tjobs := []fuq.JobDescription{\n\t\t{\n\t\t\tName: \"job1\",\n\t\t\tNumTasks: 6,\n\t\t\tWorkingDir: \"/foo/bar\",\n\t\t\tLoggingDir: \"/foo/bar/logs\",\n\t\t\tCommand: \"/foo/foo_it.sh\",\n\t\t},\n\t}\n\n\tfor i, j := range jobs {\n\t\tjobs[i].JobId = addJob(t, s.Foreman, j)\n\t\tjobs[i].Status = fuq.Waiting\n\t}\n\n\torigJobs := make([]fuq.JobDescription, len(jobs))\n\tcopy(origJobs, jobs)\n\n\twsConn, client := newTestClient(t, s)\n\tdefer wsConn.Close()\n\tdefer client.Close()\n\n\tni := client.NodeInfo\n\t_ = ni\n\n\tmsgCh := make(chan proto.Message)\n\ttaskCh := make(chan []fuq.Task)\n\n\tvar nproc, nrun uint16 = 8, 0\n\tvar running []fuq.Task\n\tvar toCancel []int\n\n\tclient.OnMessageFunc(proto.MTypeJob, func(msg proto.Message) proto.Message {\n\t\ttasks := msg.Data.([]fuq.Task)\n\n\t\tif len(tasks) > int(nproc) {\n\t\t\tpanic(\"invalid number of tasks\")\n\t\t}\n\n\t\tt.Logf(\"onJob received %d tasks: %v\", len(tasks), tasks)\n\t\tnproc -= uint16(len(tasks))\n\t\tnrun += uint16(len(tasks))\n\n\t\trepl := proto.OkayMessage(nproc, nrun, msg.Seq)\n\n\t\trunning = append(running, tasks...)\n\n\t\ttaskCh <- tasks\n\t\treturn repl\n\t})\n\n\tclient.OnMessageFunc(proto.MTypeCancel, func(msg proto.Message) proto.Message {\n\t\tpairs := msg.Data.([]fuq.TaskPair)\n\n\t\tncancel := 0\n\t\tfor i, t := range running {\n\t\t\tfor _, p := range pairs {\n\t\t\t\tif t.JobId != p.JobId {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif p.Task >= 0 && t.Task != p.Task {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\ttoCancel = append(toCancel, i)\n\t\t\t\tncancel++\n\t\t\t}\n\t\t}\n\t\tmsgCh <- msg\n\n\t\trepl := proto.OkayMessage(uint16(ncancel), 0, msg.Seq)\n\t\treturn repl\n\t})\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tfuqtest.GoPanicOnError(ctx, client.runConversationLoop)\n\n\tmsg, err := client.SendHello(ctx, proto.HelloData{\n\t\tNumProcs: 8,\n\t\tRunning: nil,\n\t})\n\n\tif err != nil {\n\t\tt.Fatalf(\"error in HELLO: %v\", err)\n\t}\n\n\tnp, nr := msg.AsOkay()\n\tif np != 8 || nr != 0 {\n\t\tt.Fatalf(\"expected OK(8|0), but received OK(%d|%d)\", nproc, nrun)\n\t}\n\n\ttasks := <-taskCh\n\t// JOB message received\n\tif len(tasks) != 6 {\n\t\tt.Fatalf(\"expected 8 task, but received %d tasks\", len(tasks))\n\t}\n\n\t/** Cancel job **/\n\tenv := ClientRequestEnvelope{\n\t\tAuth: fuq.Client{Password: testingPass, Client: \"testing\"},\n\t\tMsg: fuq.ClientStateChangeReq{\n\t\t\tJobIds: []fuq.JobId{jobs[0].JobId},\n\t\t\tAction: \"cancel\",\n\t\t},\n\t}\n\n\trepl := []fuq.JobStateChangeResponse{}\n\n\troundTrip{\n\t\tT: t,\n\t\tMsg: env,\n\t\tDst: &repl,\n\t\tTarget: \"/\" + ClientJobStatePath,\n\t}.ExpectOK(mux.ServeHTTP)\n\tt.Logf(\"response is %v\", repl)\n\n\texpectedRepl := []fuq.JobStateChangeResponse{\n\t\t{jobs[0].JobId, fuq.Running, fuq.Cancelled},\n\t}\n\n\tif !reflect.DeepEqual(repl, expectedRepl) {\n\t\tt.Fatalf(\"expected response '%v' but found '%v'\",\n\t\t\texpectedRepl, repl)\n\t}\n\n\t/** Receive CANCEL message **/\n\tmsg = <-msgCh\n\t// expect CANCEL message\n\n\texpected := proto.Message{\n\t\tType: proto.MTypeCancel,\n\t\tSeq: msg.Seq,\n\t\tData: []fuq.TaskPair{{jobs[0].JobId, -1}},\n\t}\n\n\tif !reflect.DeepEqual(msg, expected) {\n\t\tt.Fatalf(\"expected '%v', but found '%v'\", expected, msg)\n\t}\n}", "func validateBuildRunToSucceed(testBuild *utils.TestBuild, testBuildRun *buildv1alpha1.BuildRun) {\n\ttrueCondition := corev1.ConditionTrue\n\tfalseCondition := corev1.ConditionFalse\n\n\t// Ensure the BuildRun has been created\n\terr := testBuild.CreateBR(testBuildRun)\n\tExpect(err).ToNot(HaveOccurred(), \"Failed to create BuildRun\")\n\n\t// Ensure a BuildRun eventually moves to a succeeded TRUE status\n\tnextStatusLog := time.Now().Add(60 * time.Second)\n\tEventually(func() corev1.ConditionStatus {\n\t\ttestBuildRun, err = testBuild.LookupBuildRun(types.NamespacedName{Name: testBuildRun.Name, Namespace: testBuild.Namespace})\n\t\tExpect(err).ToNot(HaveOccurred(), \"Error retrieving a buildRun\")\n\n\t\tif testBuildRun.Status.GetCondition(buildv1alpha1.Succeeded) == nil {\n\t\t\treturn corev1.ConditionUnknown\n\t\t}\n\n\t\tExpect(testBuildRun.Status.GetCondition(buildv1alpha1.Succeeded).Status).ToNot(Equal(falseCondition), \"BuildRun status doesn't move to Succeeded\")\n\n\t\tnow := time.Now()\n\t\tif now.After(nextStatusLog) {\n\t\t\tLogf(\"Still waiting for build run '%s' to succeed.\", testBuildRun.Name)\n\t\t\tnextStatusLog = time.Now().Add(60 * time.Second)\n\t\t}\n\n\t\treturn testBuildRun.Status.GetCondition(buildv1alpha1.Succeeded).Status\n\n\t}, time.Duration(1100*getTimeoutMultiplier())*time.Second, 5*time.Second).Should(Equal(trueCondition), \"BuildRun did not succeed\")\n\n\t// Verify that the BuildSpec is still available in the status\n\tExpect(testBuildRun.Status.BuildSpec).ToNot(BeNil(), \"BuildSpec is not available in the status\")\n\n\tLogf(\"Test build '%s' is completed after %v !\", testBuildRun.GetName(), testBuildRun.Status.CompletionTime.Time.Sub(testBuildRun.Status.StartTime.Time))\n}", "func TestDeviceController(t *testing.T) {\n\n\t// Set the logger to development mode for verbose logs.\n\tlogf.SetLogger(zap.New(zap.UseDevMode(true)))\n\n\t// Create a fake client to mock API calls.\n\tcl, s := CreateFakeClient(t)\n\n\t// Create a ReconcileBlockDevice object with the scheme and fake client.\n\tr := &BlockDeviceReconciler{Client: cl, Scheme: s, Recorder: fakeRecorder}\n\n\t// Mock request to simulate Reconcile() being called on an event for a\n\t// watched resource .\n\treq := reconcile.Request{\n\t\tNamespacedName: types.NamespacedName{\n\t\t\tName: deviceName,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\n\tres, err := r.Reconcile(context.TODO(), req)\n\tif err != nil {\n\t\tt.Fatalf(\"reconcile: (%v)\", err)\n\t}\n\n\t// Check the result of reconciliation to make sure it has the desired state.\n\tif !res.Requeue {\n\t\tt.Log(\"reconcile did not requeue request as expected\")\n\t}\n\n\tdeviceInstance := &openebsv1alpha1.BlockDevice{}\n\terr = r.Client.Get(context.TODO(), req.NamespacedName, deviceInstance)\n\tif err != nil {\n\t\tt.Errorf(\"get deviceInstance : (%v)\", err)\n\t}\n\n\t// Disk Status state should be Active as expected.\n\tif deviceInstance.Status.State == ndm.NDMActive {\n\t\tt.Logf(\"BlockDevice Object state:%v match expected state:%v\", deviceInstance.Status.State, ndm.NDMActive)\n\t} else {\n\t\tt.Fatalf(\"BlockDevice Object state:%v did not match expected state:%v\", deviceInstance.Status.State, ndm.NDMActive)\n\t}\n}", "func (r *TestWorkloadReconciler) reconcilePending(ctx context.Context, workload *naglfarv1.TestWorkload) (ctrl.Result, error) {\n\tclusterTopologies := make(map[types.NamespacedName]struct{})\n\tfor _, item := range workload.Spec.ClusterTopologiesRefs {\n\t\tclusterTopologies[types.NamespacedName{\n\t\t\tNamespace: workload.Namespace,\n\t\t\tName: item.Name,\n\t\t}] = struct{}{}\n\t}\n\ttopologies, allReady, err := r.checkTopologiesReady(ctx, clusterTopologies)\n\tif err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\tif !allReady {\n\t\tr.Recorder.Event(workload, \"Warning\", \"Precondition\", \"not all clusters are ready\")\n\t\treturn ctrl.Result{RequeueAfter: 5 * time.Second}, nil\n\t}\n\tvar resourceList naglfarv1.TestResourceList\n\tif err := r.List(ctx, &resourceList, client.InNamespace(workload.Namespace)); err != nil {\n\t\treturn ctrl.Result{}, err\n\t}\n\tvar installedCount = 0\n\tfor _, item := range workload.Spec.Workloads {\n\t\tworkloadNode, err := r.getWorkloadRequestNode(ctx, workload.Namespace, item.DockerContainer)\n\t\tif err != nil {\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\tif workloadNode == nil {\n\t\t\terr := fmt.Errorf(\"cannot find the resource %s\", item.DockerContainer.ResourceRequest.Name)\n\t\t\tr.Recorder.Event(workload, \"Warning\", \"Precondition\", err.Error())\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\tif workloadNode.Status.ClaimRef != nil && *workloadNode.Status.ClaimRef != ref.CreateRef(&workload.ObjectMeta) {\n\t\t\tr.Recorder.Eventf(workload, \"Warning\", \"Precondition\", \"node %s is occupied by %s\",\n\t\t\t\tref.CreateRef(&workloadNode.ObjectMeta).Key(),\n\t\t\t\tworkloadNode.Status.ClaimRef.Key())\n\t\t\treturn ctrl.Result{RequeueAfter: 5 * time.Second}, nil\n\t\t}\n\t\tswitch workloadNode.Status.State {\n\t\tcase naglfarv1.ResourceDestroy:\n\t\t\treturn ctrl.Result{RequeueAfter: time.Second}, nil\n\t\tcase naglfarv1.ResourcePending:\n\t\t\tpanic(fmt.Sprintf(\"there's a bug, it shouldn't see the `%s` state\", workloadNode.Status.State))\n\t\tcase naglfarv1.ResourceUninitialized:\n\t\t\tif workloadNode.Status.Image == \"\" {\n\t\t\t\tself := ref.CreateRef(&workload.ObjectMeta)\n\t\t\t\t// claim occupy\n\t\t\t\tworkloadNode.Status.ClaimRef = &self\n\n\t\t\t\tr.setContainerSpec(&workloadNode.Status, workload, &item)\n\t\t\t\ttopologyEnvs, err := r.buildTopologyEnvs(&workload.Spec, topologies, resourceList)\n\t\t\t\tif err != nil {\n\t\t\t\t\tr.Recorder.Event(workload, \"Warning\", \"Precondition\", err.Error())\n\t\t\t\t\treturn ctrl.Result{}, err\n\t\t\t\t}\n\t\t\t\tworkloadNode.Status.Envs = append(workloadNode.Status.Envs, topologyEnvs...)\n\t\t\t\tif err := r.Status().Update(ctx, workloadNode); err != nil {\n\t\t\t\t\treturn ctrl.Result{}, err\n\t\t\t\t}\n\t\t\t\tr.Recorder.Event(workload, \"Normal\", \"Install\", fmt.Sprintf(\"preparing the workload: %s\", item.Name))\n\t\t\t} else if workloadNode.Status.Image != item.DockerContainer.Image {\n\t\t\t\terr := fmt.Errorf(\"resource %s has installed a conflict image\", workloadNode.Name)\n\t\t\t\tr.Recorder.Event(workload, \"Warning\", \"Precondition\", err.Error())\n\t\t\t\treturn ctrl.Result{}, err\n\t\t\t}\n\t\tcase naglfarv1.ResourceReady, naglfarv1.ResourceFinish:\n\t\t\tself := ref.CreateRef(&workload.ObjectMeta)\n\t\t\t// check if the workload node resource is used by a tct(ClaimRef == nil)\n\t\t\t// or has occupied by another workload (Claim != self)\n\t\t\tif workloadNode.Status.ClaimRef == nil || *workloadNode.Status.ClaimRef != self {\n\t\t\t\terr := fmt.Errorf(\"resource %s is used by others now, wait\", workloadNode.Name)\n\t\t\t\tr.Recorder.Eventf(workload, \"Warning\", \"Precondition\", err.Error())\n\t\t\t\treturn ctrl.Result{}, err\n\t\t\t}\n\t\t\tinstalledCount += 1\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"there's a bug, forget to process the `%s` state\", workloadNode.Status.State))\n\t\t}\n\t}\n\t// TODO: we can record installed workloads on the `status` field\n\tif installedCount == len(workload.Spec.Workloads) {\n\t\tworkload.Status.State = naglfarv1.TestWorkloadStateRunning\n\t\tif err := r.Status().Update(ctx, workload); err != nil {\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\tr.Recorder.Event(workload, \"Normal\", \"Install\", \"all workload has been installed\")\n\t\treturn ctrl.Result{}, nil\n\t}\n\t// otherwise, we are still pending\n\treturn ctrl.Result{RequeueAfter: 5 * time.Second}, nil\n}", "func TestAdmissionLifecycle(t *testing.T) {\n\tnamespaceObj := &kapi.Namespace{\n\t\tObjectMeta: kapi.ObjectMeta{\n\t\t\tName: \"test\",\n\t\t\tNamespace: \"\",\n\t\t},\n\t\tStatus: kapi.NamespaceStatus{\n\t\t\tPhase: kapi.NamespaceActive,\n\t\t},\n\t}\n\tstore := cache.NewStore(cache.IndexFuncToKeyFuncAdapter(cache.MetaNamespaceIndexFunc))\n\tstore.Add(namespaceObj)\n\tmockClient := &testclient.Fake{}\n\tprojectcache.FakeProjectCache(mockClient, store, \"\")\n\thandler := &lifecycle{client: mockClient}\n\tbuild := &buildapi.Build{\n\t\tObjectMeta: kapi.ObjectMeta{Name: \"buildid\", Namespace: \"other\"},\n\t\tSpec: buildapi.BuildSpec{\n\t\t\tSource: buildapi.BuildSource{\n\t\t\t\tGit: &buildapi.GitBuildSource{\n\t\t\t\t\tURI: \"http://github.com/my/repository\",\n\t\t\t\t},\n\t\t\t\tContextDir: \"context\",\n\t\t\t},\n\t\t\tStrategy: buildapi.BuildStrategy{\n\t\t\t\tDockerStrategy: &buildapi.DockerBuildStrategy{},\n\t\t\t},\n\t\t\tOutput: buildapi.BuildOutput{\n\t\t\t\tTo: &kapi.ObjectReference{\n\t\t\t\t\tKind: \"DockerImage\",\n\t\t\t\t\tName: \"repository/data\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tStatus: buildapi.BuildStatus{\n\t\t\tPhase: buildapi.BuildPhaseNew,\n\t\t},\n\t}\n\terr := handler.Admit(admission.NewAttributesRecord(build, \"Build\", build.Namespace, \"name\", \"builds\", \"\", \"CREATE\", nil))\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error returned from admission handler: %v\", err)\n\t}\n\n\t// change namespace state to terminating\n\tnamespaceObj.Status.Phase = kapi.NamespaceTerminating\n\tstore.Add(namespaceObj)\n\n\t// verify create operations in the namespace cause an error\n\terr = handler.Admit(admission.NewAttributesRecord(build, \"Build\", build.Namespace, \"name\", \"builds\", \"\", \"CREATE\", nil))\n\tif err == nil {\n\t\tt.Errorf(\"Expected error rejecting creates in a namespace when it is terminating\")\n\t}\n\n\t// verify update operations in the namespace can proceed\n\terr = handler.Admit(admission.NewAttributesRecord(build, \"Build\", build.Namespace, \"name\", \"builds\", \"\", \"UPDATE\", nil))\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error returned from admission handler: %v\", err)\n\t}\n\n\t// verify delete operations in the namespace can proceed\n\terr = handler.Admit(admission.NewAttributesRecord(nil, \"Build\", build.Namespace, \"name\", \"builds\", \"\", \"DELETE\", nil))\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error returned from admission handler: %v\", err)\n\t}\n\n}", "func Test_Pod_Checker(t *testing.T) {\n\tworkflow := func(name string) string {\n\t\treturn workflowPath(\"pod\", name)\n\t}\n\tconst (\n\t\tadded = \"added\"\n\t\tcontainerTerminatedError = \"containerTerminatedError\"\n\t\tcontainerTerminatedSuccess = \"containerTerminatedSuccess\"\n\t\tcontainerTerminatedSuccessRestartNever = \"containerTerminatedSuccessRestartNever\"\n\t\tcreateSuccess = \"createSuccess\"\n\t\timagePullError = \"imagePullError\"\n\t\timagePullErrorResolved = \"imagePullErrorResolved\"\n\t\tscheduled = \"scheduled\"\n\t\tunready = \"unready\"\n\t\tunscheduled = \"unscheduled\"\n\t)\n\n\ttests := []struct {\n\t\tname string\n\t\trecordingPaths []string\n\t\t// TODO: optional message validator function to check returned messages\n\t\texpectReady bool\n\t}{\n\t\t{\n\t\t\tname: \"Pod added but not ready\",\n\t\t\trecordingPaths: []string{workflow(added)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod scheduled but not ready\",\n\t\t\trecordingPaths: []string{workflow(scheduled)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod create success\",\n\t\t\trecordingPaths: []string{workflow(createSuccess)},\n\t\t\texpectReady: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod image pull error\",\n\t\t\trecordingPaths: []string{workflow(imagePullError)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod create success after image pull failure resolved\",\n\t\t\trecordingPaths: []string{workflow(imagePullError), workflow(imagePullErrorResolved)},\n\t\t\texpectReady: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod unscheduled\",\n\t\t\trecordingPaths: []string{workflow(unscheduled)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod unready\",\n\t\t\trecordingPaths: []string{workflow(unready)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod container terminated with error\",\n\t\t\trecordingPaths: []string{workflow(containerTerminatedError)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod container terminated successfully\",\n\t\t\trecordingPaths: []string{workflow(containerTerminatedSuccess)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod container terminated successfully with restartPolicy: Never\",\n\t\t\trecordingPaths: []string{workflow(containerTerminatedSuccessRestartNever)},\n\t\t\texpectReady: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tchecker := NewPodChecker()\n\n\t\t\tready, messages := mustCheckIfRecordingsReady(tt.recordingPaths, checker)\n\t\t\tif ready != tt.expectReady {\n\t\t\t\tt.Errorf(\"Ready() = %t, want %t\\nMessages: %s\", ready, tt.expectReady, messages)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestCancelJob(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping integration tests in short mode\")\n\t}\n\n\tt.Parallel()\n\tc, _ := minikubetestenv.AcquireCluster(t)\n\n\t// Create an input repo\n\trepo := tu.UniqueString(\"TestCancelJob\")\n\trequire.NoError(t, c.CreateRepo(pfs.DefaultProjectName, repo))\n\n\t// Create an input commit\n\tcommit, err := c.StartCommit(pfs.DefaultProjectName, repo, \"master\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, c.PutFile(commit, \"/time\", strings.NewReader(\"600\"), client.WithAppendPutFile()))\n\trequire.NoError(t, c.PutFile(commit, \"/data\", strings.NewReader(\"commit data\"), client.WithAppendPutFile()))\n\trequire.NoError(t, c.FinishCommit(pfs.DefaultProjectName, repo, commit.Branch.Name, commit.Id))\n\n\t// Create sleep + copy pipeline\n\tpipeline := tu.UniqueString(\"pipeline\")\n\trequire.NoError(t, c.CreatePipeline(pfs.DefaultProjectName,\n\t\tpipeline,\n\t\t\"\",\n\t\t[]string{\"bash\"},\n\t\t[]string{\n\t\t\t\"sleep `cat /pfs/*/time`\",\n\t\t\t\"cp /pfs/*/data /pfs/out/\",\n\t\t},\n\t\t&pps.ParallelismSpec{\n\t\t\tConstant: 1,\n\t\t},\n\t\tclient.NewPFSInput(pfs.DefaultProjectName, repo, \"/\"),\n\t\t\"\",\n\t\tfalse,\n\t))\n\n\t// Wait until PPS has started processing commit\n\tvar jobInfo *pps.JobInfo\n\trequire.NoErrorWithinT(t, 30*time.Second, func() error {\n\t\treturn backoff.Retry(func() error {\n\t\t\tjobInfos, err := c.ListJob(pfs.DefaultProjectName, pipeline, nil, -1, true)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif len(jobInfos) != 1 {\n\t\t\t\treturn errors.Errorf(\"Expected one job, but got %d: %v\", len(jobInfos), jobInfos)\n\t\t\t}\n\t\t\tjobInfo = jobInfos[0]\n\t\t\treturn nil\n\t\t}, backoff.NewTestingBackOff())\n\t})\n\n\t// stop the job\n\trequire.NoError(t, c.StopJob(pfs.DefaultProjectName, jobInfo.Job.Pipeline.Name, jobInfo.Job.Id))\n\n\t// Wait until the job is cancelled\n\trequire.NoErrorWithinT(t, 30*time.Second, func() error {\n\t\treturn backoff.Retry(func() error {\n\t\t\tupdatedJobInfo, err := c.InspectJob(pfs.DefaultProjectName, jobInfo.Job.Pipeline.Name, jobInfo.Job.Id, false)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif updatedJobInfo.State != pps.JobState_JOB_KILLED {\n\t\t\t\treturn errors.Errorf(\"job %s is still running, but should be KILLED\", jobInfo.Job.Id)\n\t\t\t}\n\t\t\treturn nil\n\t\t}, backoff.NewTestingBackOff())\n\t})\n\n\t// Create one more commit to make sure the pipeline can still process input\n\t// commits\n\tcommit2, err := c.StartCommit(pfs.DefaultProjectName, repo, \"master\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, c.DeleteFile(commit2, \"/time\"))\n\trequire.NoError(t, c.PutFile(commit2, \"/time\", strings.NewReader(\"1\"), client.WithAppendPutFile()))\n\trequire.NoError(t, c.DeleteFile(commit2, \"/data\"))\n\trequire.NoError(t, c.PutFile(commit2, \"/data\", strings.NewReader(\"commit 2 data\"), client.WithAppendPutFile()))\n\trequire.NoError(t, c.FinishCommit(pfs.DefaultProjectName, repo, commit2.Branch.Name, commit2.Id))\n\n\t// Flush commit2, and make sure the output is as expected\n\tcommitInfo, err := c.WaitCommit(pfs.DefaultProjectName, pipeline, \"master\", commit2.Id)\n\trequire.NoError(t, err)\n\n\tbuf := bytes.Buffer{}\n\terr = c.GetFile(commitInfo.Commit, \"/data\", &buf)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"commit 2 data\", buf.String())\n}", "func add(ctx context.Context, mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"buildrun-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpredBuildRun := predicate.Funcs{\n\t\tCreateFunc: func(e event.CreateEvent) bool {\n\t\t\to := e.Object.(*buildv1alpha1.BuildRun)\n\n\t\t\t// The CreateFunc is also called when the controller is started and iterates over all objects. For those BuildRuns that have a TaskRun referenced already,\n\t\t\t// we do not need to do a further reconciliation. BuildRun updates then only happen from the TaskRun.\n\t\t\treturn o.Status.LatestTaskRunRef == nil\n\t\t},\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\t// Ignore updates to CR status in which case metadata.Generation does not change\n\t\t\to := e.ObjectOld.(*buildv1alpha1.BuildRun)\n\n\t\t\t// Avoid reconciling when for updates on the BuildRun, the build.build.dev/name\n\t\t\t// label is set, and when a BuildRun already have a referenced TaskRun.\n\t\t\tif o.GetLabels()[buildv1alpha1.LabelBuild] == \"\" || o.Status.LatestTaskRunRef != nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\treturn e.MetaOld.GetGeneration() != e.MetaNew.GetGeneration()\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\t// Evaluates to false if the object has been confirmed deleted.\n\t\t\treturn !e.DeleteStateUnknown\n\t\t},\n\t}\n\n\tpredTaskRun := predicate.Funcs{\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\to := e.ObjectOld.(*v1beta1.TaskRun)\n\t\t\tn := e.ObjectNew.(*v1beta1.TaskRun)\n\n\t\t\t// Process an update event when the old TR resource is not yet started and the new TR resource got a\n\t\t\t// condition of the type Succeeded\n\t\t\tif o.Status.StartTime.IsZero() && n.Status.GetCondition(apis.ConditionSucceeded) != nil {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\t// Process an update event for every change in the condition.Reason between the old and new TR resource\n\t\t\tif o.Status.GetCondition(apis.ConditionSucceeded) != nil && n.Status.GetCondition(apis.ConditionSucceeded) != nil {\n\t\t\t\tif o.Status.GetCondition(apis.ConditionSucceeded).Reason != n.Status.GetCondition(apis.ConditionSucceeded).Reason {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\t// Evaluates to false if the object has been confirmed deleted.\n\t\t\treturn !e.DeleteStateUnknown\n\t\t},\n\t}\n\n\t// Watch for changes to primary resource BuildRun\n\terr = c.Watch(&source.Kind{Type: &buildv1alpha1.BuildRun{}}, &handler.EnqueueRequestForObject{}, predBuildRun)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// enqueue Reconciles requests only for events where a TaskRun already exists and that is related\n\t// to a BuildRun\n\treturn c.Watch(&source.Kind{Type: &v1beta1.TaskRun{}}, &handler.EnqueueRequestsFromMapFunc{\n\t\tToRequests: handler.ToRequestsFunc(func(o handler.MapObject) []reconcile.Request {\n\n\t\t\ttaskRun := o.Object.(*v1beta1.TaskRun)\n\n\t\t\t// check if TaskRun is related to BuildRun\n\t\t\tif taskRun.GetLabels() == nil || taskRun.GetLabels()[buildv1alpha1.LabelBuildRun] == \"\" {\n\t\t\t\treturn []reconcile.Request{}\n\t\t\t}\n\n\t\t\treturn []reconcile.Request{\n\t\t\t\t{\n\t\t\t\t\tNamespacedName: types.NamespacedName{\n\t\t\t\t\t\tName: taskRun.Name,\n\t\t\t\t\t\tNamespace: taskRun.Namespace,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}),\n\t}, predTaskRun)\n}", "func (k *Kubernetes) Test(ctx context.Context) error {\n\tk.l.Lock()\n\tdefer k.l.Unlock()\n\n\treturn k.updatePods(ctx)\n}", "func controllerSubtest(name string, tc *sessionTestCase) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\t// This test uses the same controller to manage two sessions that are communicating with\n\t\t// each other (basically, both the \"local\" and \"remote\" session are on the same system).\n\t\t// This is possible because the local discriminators are chosen such that they are\n\t\t// different.\n\t\t//\n\t\t// While this is something that rarely (if ever) occurs in practice, it makes test setup\n\t\t// much simpler here. In the real world, BFD would configured between two systems and each\n\t\t// system would have its own controller which is in charge only of sessions on that system.\n\t\tcontroller := &bfd.Controller{\n\t\t\tSessions: []*bfd.Session{tc.sessionA, tc.sessionB},\n\t\t\tReceiveQueueSize: 10,\n\t\t}\n\n\t\t// both sessions send their messages through the same controller\n\t\tmessageQueue := &redirectSender{Destination: controller.Messages()}\n\t\ttc.sessionA.Sender = messageQueue\n\t\ttc.sessionB.Sender = messageQueue\n\t\ttc.sessionA.Logger = testlog.NewLogger(t).New(\"session\", \"a\")\n\t\ttc.sessionB.Logger = testlog.NewLogger(t).New(\"session\", \"b\")\n\n\t\t// the wait group is not used for synchronization, but rather to check that the controller\n\t\t// returns\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\n\t\tgo func() {\n\t\t\terr := controller.Run()\n\t\t\trequire.NoError(t, err)\n\t\t\twg.Done()\n\t\t}()\n\n\t\t// second argument is not used because we have a single queue\n\t\ttc.testBehavior(messageQueue, nil)\n\n\t\tassert.Equal(t, tc.expectedUpA, controller.IsUp(tc.sessionA.LocalDiscriminator))\n\t\tassert.Equal(t, tc.expectedUpB, controller.IsUp(tc.sessionB.LocalDiscriminator))\n\n\t\tmessageQueue.Close()\n\n\t\tfor i := 0; i < 2; i++ {\n\t\t\terr := <-controller.Errors()\n\t\t\tassert.NoError(t, err)\n\t\t}\n\t\twg.Wait()\n\t}\n}", "func TestReconcile(t *testing.T) {\n\n\t//\n\t// Define The KafkaChannel Reconciler Test Cases\n\t//\n\t// Note - Knative testing framework assumes ALL actions will be in the same Namespace\n\t// as the Key so we have to set SkipNamespaceValidation in all tests!\n\t//\n\t// Note - Knative reconciler framework expects Events (not errors) from ReconcileKind()\n\t// so WantErr is only for higher level failures in the injected Reconcile() function.\n\t//\n\tcommontesting.SetTestEnvironment(t)\n\ttableTest := TableTest{\n\n\t\t//\n\t\t// Top Level Use Cases\n\t\t//\n\n\t\t{\n\t\t\tName: \"Bad Secret Key\",\n\t\t\tKey: \"too/many/parts\",\n\t\t},\n\t\t{\n\t\t\tName: \"Secret Key Not Found\",\n\t\t\tKey: \"foo/not-found\",\n\t\t},\n\n\t\t//\n\t\t// Full Reconciliation\n\t\t//\n\n\t\t{\n\t\t\tName: \"Complete Reconciliation Without KafkaChannel\",\n\t\t\tKey: controllertesting.KafkaSecretKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaSecret(),\n\t\t\t},\n\t\t\tWantCreates: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t},\n\t\t\tWantPatches: []clientgotesting.PatchActionImpl{controllertesting.NewKafkaSecretFinalizerPatchActionImpl()},\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaSecretFinalizerUpdateEvent(),\n\t\t\t\tcontrollertesting.NewKafkaSecretSuccessfulReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Complete Reconciliation With KafkaChannel\",\n\t\t\tKey: controllertesting.KafkaSecretKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaSecret(),\n\t\t\t\tcontrollertesting.NewKafkaChannel(),\n\t\t\t},\n\t\t\tWantCreates: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\t{\n\t\t\t\t\tObject: controllertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWantPatches: []clientgotesting.PatchActionImpl{controllertesting.NewKafkaSecretFinalizerPatchActionImpl()},\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaSecretFinalizerUpdateEvent(),\n\t\t\t\tcontrollertesting.NewKafkaSecretSuccessfulReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Complete Reconciliation With KafkaChannel, No Receiver Resource Requests Or Limits\",\n\t\t\tKey: controllertesting.KafkaSecretKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaSecret(),\n\t\t\t\tcontrollertesting.NewKafkaChannel(),\n\t\t\t},\n\t\t\tWantCreates: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(controllertesting.WithoutResources),\n\t\t\t},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\t{\n\t\t\t\t\tObject: controllertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWantPatches: []clientgotesting.PatchActionImpl{controllertesting.NewKafkaSecretFinalizerPatchActionImpl()},\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaSecretFinalizerUpdateEvent(),\n\t\t\t\tcontrollertesting.NewKafkaSecretSuccessfulReconciliationEvent(),\n\t\t\t},\n\t\t\tOtherTestData: map[string]interface{}{\n\t\t\t\t\"configOptions\": []controllertesting.KafkaConfigOption{controllertesting.WithNoReceiverResources},\n\t\t\t},\n\t\t},\n\n\t\t//\n\t\t// KafkaChannel Secret Deletion (Finalizer)\n\t\t//\n\n\t\t{\n\t\t\tName: \"Finalize Deleted Secret\",\n\t\t\tKey: controllertesting.KafkaSecretKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaSecret(controllertesting.WithKafkaSecretDeleted),\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t),\n\t\t\t},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\t{\n\t\t\t\t\tObject: controllertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithReceiverServiceFinalized,\n\t\t\t\t\t\tcontrollertesting.WithReceiverDeploymentFinalized,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaSecretSuccessfulFinalizedEvent(),\n\t\t\t},\n\t\t},\n\n\t\t//\n\t\t// KafkaSecret Receiver Service\n\t\t//\n\n\t\t{\n\t\t\tName: \"Reconcile Missing Receiver Service Success\",\n\t\t\tKey: controllertesting.KafkaSecretKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaSecret(controllertesting.WithKafkaSecretFinalizer),\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t},\n\t\t\tWantCreates: []runtime.Object{controllertesting.NewKafkaChannelReceiverService()},\n\t\t\tWantEvents: []string{\n\t\t\t\tcontrollertesting.NewKafkaSecretSuccessfulReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Missing Receiver Service Error(Create)\",\n\t\t\tKey: controllertesting.KafkaSecretKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaSecret(controllertesting.WithKafkaSecretFinalizer),\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment(),\n\t\t\t},\n\t\t\tWithReactors: []clientgotesting.ReactionFunc{InduceFailure(\"create\", \"services\")},\n\t\t\tWantErr: true,\n\t\t\tWantCreates: []runtime.Object{controllertesting.NewKafkaChannelReceiverService()},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\t{\n\t\t\t\t\tObject: controllertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithReceiverServiceFailed,\n\t\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tEventf(corev1.EventTypeWarning, event.ReceiverServiceReconciliationFailed.String(), \"Failed To Reconcile Receiver Service: inducing failure for create services\"),\n\t\t\t\tcontrollertesting.NewKafkaSecretFailedReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Receiver Service With Deletion Timestamp\",\n\t\t\tKey: controllertesting.KafkaSecretKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaSecret(controllertesting.WithKafkaSecretFinalizer),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(controllertesting.WithDeletionTimestampService),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(),\n\t\t\t},\n\t\t\tWantErr: true,\n\t\t\tWantEvents: []string{\n\t\t\t\tEventf(corev1.EventTypeWarning, event.ReceiverServiceReconciliationFailed.String(), \"Failed To Reconcile Receiver Service: encountered Receiver Service with DeletionTimestamp \"+controllertesting.KafkaSecretNamespace+\"/kafkasecret-name-b9176d5f-receiver - potential race condition\"),\n\t\t\t\tcontrollertesting.NewKafkaSecretFailedReconciliationEvent(),\n\t\t\t},\n\t\t},\n\n\t\t//\n\t\t// KafkaSecret Receiver Deployment\n\t\t//\n\n\t\t{\n\t\t\tName: \"Reconcile Missing Receiver Deployment Success\",\n\t\t\tKey: controllertesting.KafkaSecretKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaSecret(controllertesting.WithKafkaSecretFinalizer),\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t},\n\t\t\tWantCreates: []runtime.Object{controllertesting.NewKafkaChannelReceiverDeployment()},\n\t\t\tWantEvents: []string{controllertesting.NewKafkaSecretSuccessfulReconciliationEvent()},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Missing Receiver Deployment Error(Create)\",\n\t\t\tKey: controllertesting.KafkaSecretKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaSecret(controllertesting.WithKafkaSecretFinalizer),\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t},\n\t\t\tWithReactors: []clientgotesting.ReactionFunc{InduceFailure(\"create\", \"deployments\")},\n\t\t\tWantErr: true,\n\t\t\tWantCreates: []runtime.Object{controllertesting.NewKafkaChannelReceiverDeployment()},\n\t\t\tWantStatusUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\t{\n\t\t\t\t\tObject: controllertesting.NewKafkaChannel(\n\t\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\t\tcontrollertesting.WithReceiverDeploymentFailed,\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t},\n\t\t\tWantEvents: []string{\n\t\t\t\tEventf(corev1.EventTypeWarning, event.ReceiverDeploymentReconciliationFailed.String(), \"Failed To Reconcile Receiver Deployment: inducing failure for create deployments\"),\n\t\t\t\tcontrollertesting.NewKafkaSecretFailedReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Receiver Deployment With Deletion Timestamp\",\n\t\t\tKey: controllertesting.KafkaSecretKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaSecret(controllertesting.WithKafkaSecretFinalizer),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(controllertesting.WithDeletionTimestampDeployment),\n\t\t\t},\n\t\t\tWantErr: true,\n\t\t\tWantEvents: []string{\n\t\t\t\tEventf(corev1.EventTypeWarning, event.ReceiverDeploymentReconciliationFailed.String(), \"Failed To Reconcile Receiver Deployment: encountered Receiver Deployment with DeletionTimestamp \"+controllertesting.KafkaSecretNamespace+\"/kafkasecret-name-b9176d5f-receiver - potential race condition\"),\n\t\t\t\tcontrollertesting.NewKafkaSecretFailedReconciliationEvent(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"Reconcile Receiver Deployment - Redeployment on ConfigMapHash change\",\n\t\t\tKey: controllertesting.KafkaSecretKey,\n\t\t\tObjects: []runtime.Object{\n\t\t\t\tcontrollertesting.NewKafkaSecret(controllertesting.WithKafkaSecretFinalizer),\n\t\t\t\tcontrollertesting.NewKafkaChannel(\n\t\t\t\t\tcontrollertesting.WithReceiverServiceReady,\n\t\t\t\t\tcontrollertesting.WithReceiverDeploymentReady,\n\t\t\t\t),\n\t\t\t\tcontrollertesting.NewKafkaChannelService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverService(),\n\t\t\t\tcontrollertesting.NewKafkaChannelReceiverDeployment(controllertesting.WithConfigMapHash(\"initial-hash-to-be-overridden-by-controller\")),\n\t\t\t},\n\t\t\tWantUpdates: []clientgotesting.UpdateActionImpl{\n\t\t\t\tcontrollertesting.NewDeploymentUpdateActionImpl(controllertesting.NewKafkaChannelReceiverDeployment()),\n\t\t\t},\n\t\t\tWantEvents: []string{controllertesting.NewKafkaSecretSuccessfulReconciliationEvent()},\n\t\t},\n\t}\n\n\t// Run The TableTest Using The KafkaChannel Reconciler Provided By The Factory\n\tlogger := logtesting.TestLogger(t)\n\ttableTest.Test(t, controllertesting.MakeFactory(func(ctx context.Context, listers *controllertesting.Listers, cmw configmap.Watcher, configOptions []controllertesting.KafkaConfigOption) controller.Reconciler {\n\t\tr := &Reconciler{\n\t\t\tkubeClientset: kubeclient.Get(ctx),\n\t\t\tenvironment: controllertesting.NewEnvironment(),\n\t\t\tconfig: controllertesting.NewConfig(configOptions...),\n\t\t\tkafkaChannelClient: fakekafkaclient.Get(ctx),\n\t\t\tkafkachannelLister: listers.GetKafkaChannelLister(),\n\t\t\tdeploymentLister: listers.GetDeploymentLister(),\n\t\t\tserviceLister: listers.GetServiceLister(),\n\t\t\tkafkaConfigMapHash: controllertesting.ConfigMapHash,\n\t\t}\n\t\treturn kafkasecretinjection.NewReconciler(ctx, r.kubeClientset.CoreV1(), listers.GetSecretLister(), controller.GetEventRecorder(ctx), r)\n\t}, logger.Desugar()))\n}", "func TestServicesAPIWrongControllerGWClass(t *testing.T) {\n\t// create gateway, nothing happens\n\t// create gatewayclass, VS created\n\t// update to bad gatewayclass (wrong controller), VS deleted\n\tg := gomega.NewGomegaWithT(t)\n\n\tgwClassName, gatewayName, ns := \"avi-lb\", \"my-gateway\", \"default\"\n\tmodelName := \"admin/cluster--default-my-gateway\"\n\n\tSetupGateway(t, gatewayName, ns, gwClassName)\n\tSetupSvcApiService(t, \"svc\", ns, gatewayName, ns, \"TCP\")\n\n\tSetupGatewayClass(t, gwClassName, lib.SvcApiAviGatewayController, \"\")\n\n\tg.Eventually(func() string {\n\t\tgw, _ := SvcAPIClient.NetworkingV1alpha1().Gateways(ns).Get(context.TODO(), gatewayName, metav1.GetOptions{})\n\t\tif len(gw.Status.Addresses) > 0 {\n\t\t\treturn gw.Status.Addresses[0].Value\n\t\t}\n\t\treturn \"\"\n\t}, 40*time.Second).Should(gomega.Equal(\"10.250.250.1\"))\n\n\tgwclassUpdate := FakeGWClass{\n\t\tName: gwClassName,\n\t\tController: \"xyz\",\n\t}.GatewayClass()\n\tgwclassUpdate.ResourceVersion = \"2\"\n\tif _, err := lib.AKOControlConfig().ServicesAPIClientset().NetworkingV1alpha1().GatewayClasses().Update(context.TODO(), gwclassUpdate, metav1.UpdateOptions{}); err != nil {\n\t\tt.Fatalf(\"error in updating GatewayClass: %v\", err)\n\t}\n\n\tg.Eventually(func() int {\n\t\tgw, _ := SvcAPIClient.NetworkingV1alpha1().Gateways(ns).Get(context.TODO(), gatewayName, metav1.GetOptions{})\n\t\treturn len(gw.Status.Addresses)\n\t}, 40*time.Second).Should(gomega.Equal(0))\n\tg.Eventually(func() int {\n\t\tsvc, _ := KubeClient.CoreV1().Services(ns).Get(context.TODO(), \"svc\", metav1.GetOptions{})\n\t\treturn len(svc.Status.LoadBalancer.Ingress)\n\t}, 40*time.Second).Should(gomega.Equal(0))\n\n\tTeardownAdvLBService(t, \"svc\", ns)\n\tTeardownGateway(t, gatewayName, ns)\n\tTeardownGatewayClass(t, gwClassName)\n\tVerifyGatewayVSNodeDeletion(g, modelName)\n}", "func TestLoad(t *testing.T) {\n\tclientset, err := k8sutils.MustGetClientset()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)\n\tdefer cancel()\n\n\t// Create namespace if it doesn't exist\n\tnamespaceExists, err := k8sutils.NamespaceExists(ctx, clientset, namespace)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif !namespaceExists {\n\t\terr = k8sutils.MustCreateNamespace(ctx, clientset, namespace)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\tdeployment, err := k8sutils.MustParseDeployment(noopDeploymentMap[*osType])\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdeploymentsClient := clientset.AppsV1().Deployments(namespace)\n\terr = k8sutils.MustCreateDeployment(ctx, deploymentsClient, deployment)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(\"Checking pods are running\")\n\terr = k8sutils.WaitForPodsRunning(ctx, clientset, namespace, podLabelSelector)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(\"Repeating the scale up/down cycle\")\n\tfor i := 0; i < *iterations; i++ {\n\t\tt.Log(\"Iteration \", i)\n\t\tt.Log(\"Scale down deployment\")\n\t\terr = k8sutils.MustScaleDeployment(ctx, deploymentsClient, deployment, clientset, namespace, podLabelSelector, *scaleDownReplicas, *skipWait)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tt.Log(\"Scale up deployment\")\n\t\terr = k8sutils.MustScaleDeployment(ctx, deploymentsClient, deployment, clientset, namespace, podLabelSelector, *scaleUpReplicas, *skipWait)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\tt.Log(\"Checking pods are running and IP assigned\")\n\terr = k8sutils.WaitForPodsRunning(ctx, clientset, \"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif *validateStateFile {\n\t\tt.Run(\"Validate state file\", TestValidateState)\n\t}\n\n\tif *validateDualStack {\n\t\tt.Run(\"Validate dualstack overlay\", TestDualStackProperties)\n\t}\n}", "func CreatePods(c kclientset.Interface, appName string, ns string, labels map[string]string, spec kapiv1.PodSpec, maxCount int, tuning *TuningSetType) {\n\tfor i := 0; i < maxCount; i++ {\n\t\tframework.Logf(\"%v/%v : Creating pod\", i+1, maxCount)\n\t\t// Retry on pod creation failure\n\t\tfor retryCount := 0; retryCount < maxRetries; retryCount++ {\n\t\t\t_, err := c.CoreV1().Pods(ns).Create(&kapiv1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: fmt.Sprintf(appName+\"-pod-%v\", i),\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: spec,\n\t\t\t})\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tframework.ExpectNoError(err)\n\t\t}\n\t\tif tuning != nil {\n\t\t\t// If a rate limit has been defined we wait for N ms between creation\n\t\t\tif tuning.Pods.RateLimit.Delay != 0 {\n\t\t\t\tframework.Logf(\"Sleeping %d ms between podcreation.\", tuning.Pods.RateLimit.Delay)\n\t\t\t\ttime.Sleep(tuning.Pods.RateLimit.Delay * time.Millisecond)\n\t\t\t}\n\t\t\t// If a stepping tuningset has been defined in the config, we wait for the step of pods to be created, and pause\n\t\t\tif tuning.Pods.Stepping.StepSize != 0 && (i+1)%tuning.Pods.Stepping.StepSize == 0 {\n\t\t\t\tframework.Logf(\"Waiting for pods created this step to be running\")\n\t\t\t\tpods, err := exutil.WaitForPods(c.CoreV1().Pods(ns), exutil.ParseLabelsOrDie(mapToString(labels)), exutil.CheckPodIsRunningFn, i+1, tuning.Pods.Stepping.Timeout*time.Second)\n\t\t\t\tif err != nil {\n\t\t\t\t\tframework.Failf(\"Error in wait... %v\", err)\n\t\t\t\t} else if len(pods) < i+1 {\n\t\t\t\t\tframework.Failf(\"Only got %v out of %v\", len(pods), i+1)\n\t\t\t\t}\n\n\t\t\t\tframework.Logf(\"We have created %d pods and are now sleeping for %d seconds\", i+1, tuning.Pods.Stepping.Pause)\n\t\t\t\ttime.Sleep(tuning.Pods.Stepping.Pause * time.Second)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestUpdateServiceBrokerCondition(t *testing.T) {\n\t// Anonymous struct fields:\n\t// name: short description of the test\n\t// input: broker object to test\n\t// status: new condition status\n\t// reason: condition reason\n\t// message: condition message\n\t// transitionTimeChanged: true if the test conditions should result in transition time change\n\tcases := []struct {\n\t\tname string\n\t\tinput *v1beta1.ClusterServiceBroker\n\t\tstatus v1beta1.ConditionStatus\n\t\treason string\n\t\tmessage string\n\t\ttransitionTimeChanged bool\n\t}{\n\n\t\t{\n\t\t\tname: \"initially unset\",\n\t\t\tinput: getTestClusterServiceBroker(),\n\t\t\tstatus: v1beta1.ConditionFalse,\n\t\t\ttransitionTimeChanged: true,\n\t\t},\n\t\t{\n\t\t\tname: \"not ready -> not ready\",\n\t\t\tinput: getTestClusterServiceBrokerWithStatus(v1beta1.ConditionFalse),\n\t\t\tstatus: v1beta1.ConditionFalse,\n\t\t\ttransitionTimeChanged: false,\n\t\t},\n\t\t{\n\t\t\tname: \"not ready -> not ready with reason and message change\",\n\t\t\tinput: getTestClusterServiceBrokerWithStatus(v1beta1.ConditionFalse),\n\t\t\tstatus: v1beta1.ConditionFalse,\n\t\t\treason: \"foo\",\n\t\t\tmessage: \"bar\",\n\t\t\ttransitionTimeChanged: false,\n\t\t},\n\t\t{\n\t\t\tname: \"not ready -> ready\",\n\t\t\tinput: getTestClusterServiceBrokerWithStatus(v1beta1.ConditionFalse),\n\t\t\tstatus: v1beta1.ConditionTrue,\n\t\t\ttransitionTimeChanged: true,\n\t\t},\n\t\t{\n\t\t\tname: \"ready -> ready\",\n\t\t\tinput: getTestClusterServiceBrokerWithStatus(v1beta1.ConditionTrue),\n\t\t\tstatus: v1beta1.ConditionTrue,\n\t\t\ttransitionTimeChanged: false,\n\t\t},\n\t\t{\n\t\t\tname: \"ready -> not ready\",\n\t\t\tinput: getTestClusterServiceBrokerWithStatus(v1beta1.ConditionTrue),\n\t\t\tstatus: v1beta1.ConditionFalse,\n\t\t\ttransitionTimeChanged: true,\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\t_, fakeCatalogClient, _, testController, _ := newTestController(t, getTestCatalogConfig())\n\n\t\tinputClone := tc.input.DeepCopy()\n\n\t\terr := testController.updateClusterServiceBrokerCondition(tc.input, v1beta1.ServiceBrokerConditionReady, tc.status, tc.reason, tc.message)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%v: error updating broker condition: %v\", tc.name, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !reflect.DeepEqual(tc.input, inputClone) {\n\t\t\tt.Errorf(\"%v: updating broker condition mutated input: %s\", tc.name, expectedGot(inputClone, tc.input))\n\t\t\tcontinue\n\t\t}\n\n\t\tactions := fakeCatalogClient.Actions()\n\t\tif ok := expectNumberOfActions(t, tc.name, actions, 1); !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tupdatedClusterServiceBroker, ok := expectUpdateStatus(t, tc.name, actions[0], tc.input)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tupdateActionObject, ok := updatedClusterServiceBroker.(*v1beta1.ClusterServiceBroker)\n\t\tif !ok {\n\t\t\tt.Errorf(\"%v: couldn't convert to broker\", tc.name)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar initialTs metav1.Time\n\t\tif len(inputClone.Status.Conditions) != 0 {\n\t\t\tinitialTs = inputClone.Status.Conditions[0].LastTransitionTime\n\t\t}\n\n\t\tif e, a := 1, len(updateActionObject.Status.Conditions); e != a {\n\t\t\tt.Errorf(\"%v: %s\", tc.name, expectedGot(e, a))\n\t\t}\n\n\t\toutputCondition := updateActionObject.Status.Conditions[0]\n\t\tnewTs := outputCondition.LastTransitionTime\n\n\t\tif tc.transitionTimeChanged && initialTs == newTs {\n\t\t\tt.Errorf(\"%v: transition time didn't change when it should have\", tc.name)\n\t\t\tcontinue\n\t\t} else if !tc.transitionTimeChanged && initialTs != newTs {\n\t\t\tt.Errorf(\"%v: transition time changed when it shouldn't have\", tc.name)\n\t\t\tcontinue\n\t\t}\n\t\tif e, a := tc.reason, outputCondition.Reason; e != \"\" && e != a {\n\t\t\tt.Errorf(\"%v: condition reasons didn't match; %s\", tc.name, expectedGot(e, a))\n\t\t\tcontinue\n\t\t}\n\t\tif e, a := tc.message, outputCondition.Message; e != \"\" && e != a {\n\t\t\tt.Errorf(\"%v: condition message didn't match; %s\", tc.name, expectedGot(e, a))\n\t\t}\n\t}\n}", "func TestIssue351MultipleJobRun(t *testing.T) {\n\tctx, err := NewContext(t)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ctx.Cleanup()\n\n\t// Create initial CR to generate an initial job and create the initial k8s resources\n\n\tgitops := &gitopsv1alpha1.GitOpsConfig{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"GitOpsConfig\",\n\t\t\tAPIVersion: \"eunomia.kohls.io/v1alpha1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"gitops-issue351\",\n\t\t\tNamespace: ctx.namespace,\n\t\t},\n\t\tSpec: gitopsv1alpha1.GitOpsConfigSpec{\n\t\t\tTemplateSource: gitopsv1alpha1.GitConfig{\n\t\t\t\tURI: ctx.eunomiaURI,\n\t\t\t\tRef: ctx.eunomiaRef,\n\t\t\t\tContextDir: \"test/e2e/testdata/hello-a\",\n\t\t\t},\n\t\t\tParameterSource: gitopsv1alpha1.GitConfig{\n\t\t\t\tURI: ctx.eunomiaURI,\n\t\t\t\tRef: ctx.eunomiaRef,\n\t\t\t\tContextDir: \"test/e2e/testdata/empty-yaml\",\n\t\t\t},\n\t\t\tTriggers: []gitopsv1alpha1.GitOpsTrigger{\n\t\t\t\t{Type: \"Change\"},\n\t\t\t},\n\t\t\tTemplateProcessorImage: \"quay.io/kohlstechnology/eunomia-base:dev\",\n\t\t\tResourceHandlingMode: \"Apply\",\n\t\t\tResourceDeletionMode: \"Delete\",\n\t\t\tServiceAccountRef: \"eunomia-operator\",\n\t\t},\n\t}\n\n\terr = framework.Global.Client.Create(ctx, gitops, &framework.CleanupOptions{TestContext: ctx.TestCtx, Timeout: timeout, RetryInterval: retryInterval})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// When the initial job is created, we will use it as a template to create two additional jobs at the same time\n\terr = WaitForJobCreation(ctx.namespace, \"gitopsconfig-gitops-issue351-\", framework.Global.KubeClient)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tgitopsJob, err := GetJob(ctx.namespace, \"gitopsconfig-gitops-issue351-\", framework.Global.KubeClient)\n\n\tfirstJob := &batchv1.Job{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"GitOpsConfig\",\n\t\t\tAPIVersion: \"eunomia.kohls.io/v1alpha1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"first-job\",\n\t\t\tNamespace: ctx.namespace,\n\t\t},\n\t\tSpec: gitopsJob.Spec,\n\t}\n\t// The deep copy of the job keeps the selector and selector label that has to be generated by k8s.\n\t// Trying to create a job with those set will fail.\n\tfirstJob.Spec.Template.SetLabels(map[string]string{})\n\tfirstJob.Spec.Selector.Reset()\n\n\terr = framework.Global.Client.Create(ctx, firstJob, &framework.CleanupOptions{TestContext: ctx.TestCtx, Timeout: timeout, RetryInterval: retryInterval})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tsecondJob := &batchv1.Job{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"GitOpsConfig\",\n\t\t\tAPIVersion: \"eunomia.kohls.io/v1alpha1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"second-job\",\n\t\t\tNamespace: ctx.namespace,\n\t\t},\n\t\tSpec: gitopsJob.Spec,\n\t}\n\tsecondJob.Spec.Template.SetLabels(map[string]string{})\n\tsecondJob.Spec.Selector.Reset()\n\n\terr = framework.Global.Client.Create(ctx, secondJob, &framework.CleanupOptions{TestContext: ctx.TestCtx, Timeout: timeout, RetryInterval: retryInterval})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// Wait to make sure both of the jobs finish running\n\terr = wait.Poll(retryInterval, 60*time.Second, func() (done bool, err error) {\n\t\tjobOne, _ := GetJob(ctx.namespace, \"first-job\", framework.Global.KubeClient)\n\t\tjobTwo, _ := GetJob(ctx.namespace, \"second-job\", framework.Global.KubeClient)\n\n\t\tswitch {\n\t\tcase jobOne.Status.Succeeded == 1 && jobTwo.Status.Succeeded == 1:\n\t\t\tt.Logf(\"Both jobs are done\")\n\t\t\treturn true, nil\n\t\tdefault:\n\t\t\tt.Logf(\"Both jobs are not done\")\n\t\t\treturn false, nil\n\t\t}\n\t})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tdeploymentList, err := framework.Global.KubeClient.AppsV1().Deployments(ctx.namespace).List(metav1.ListOptions{})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif len(deploymentList.Items) != 1 {\n\t\tt.Errorf(\"There was only %d deployments when we were expecting 1\", len(deploymentList.Items))\n\t}\n\tif deploymentList.Items[0].GetDeletionTimestamp() != nil {\n\t\tt.Errorf(\"The deployment has been marked for deletion\")\n\t}\n}", "func TestProject_CreateProject_ReportsErrorIfNoSuccessForLongTime(t *testing.T) {\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\n\tcoreClient := azdosdkmocks.NewMockCoreClient(ctrl)\n\toperationsClient := azdosdkmocks.NewMockOperationsClient(ctrl)\n\tclients := &client.AggregatedClient{\n\t\tCoreClient: coreClient,\n\t\tOperationsClient: operationsClient,\n\t\tCtx: context.Background(),\n\t}\n\n\texpectedProjectCreateArgs := core.QueueCreateProjectArgs{ProjectToCreate: &testProject}\n\tmockedOperationReference := operations.OperationReference{Id: &testID}\n\texpectedOperationArgs := operations.GetOperationArgs{OperationId: &testID}\n\n\tcoreClient.\n\t\tEXPECT().\n\t\tQueueCreateProject(clients.Ctx, expectedProjectCreateArgs).\n\t\tReturn(&mockedOperationReference, nil).\n\t\tTimes(1)\n\n\t// the operation will forever be \"in progress\"\n\tstatus := operationWithStatus(operations.OperationStatusValues.InProgress)\n\toperationsClient.\n\t\tEXPECT().\n\t\tGetOperation(clients.Ctx, expectedOperationArgs).\n\t\tReturn(&status, nil).\n\t\tMinTimes(1)\n\n\terr := createProject(clients, &testProject, 20*time.Second)\n\trequire.NotNil(t, err, \"Expected error indicating timeout\")\n}", "func TestConstructSlowGo(t *testing.T) {\n\tpathEnv := testComponentSlowPathEnv(t)\n\n\t// TODO[pulumi/pulumi#5455]: Dynamic providers fail to load when used from multi-lang components.\n\t// Until we've addressed this, set PULUMI_TEST_YARN_LINK_PULUMI, which tells the integration test\n\t// module to run `yarn install && yarn link @pulumi/pulumi` in the Go program's directory, allowing\n\t// the Node.js dynamic provider plugin to load.\n\t// When the underlying issue has been fixed, the use of this environment variable inside the integration\n\t// test module should be removed.\n\tconst testYarnLinkPulumiEnv = \"PULUMI_TEST_YARN_LINK_PULUMI=true\"\n\n\topts := &integration.ProgramTestOptions{\n\t\tEnv: []string{pathEnv, testYarnLinkPulumiEnv},\n\t\tDir: filepath.Join(\"construct_component_slow\", \"go\"),\n\t\tDependencies: []string{\n\t\t\t\"github.com/pulumi/pulumi/sdk/v3\",\n\t\t},\n\t\tQuick: true,\n\t\tExtraRuntimeValidation: func(t *testing.T, stackInfo integration.RuntimeValidationStackInfo) {\n\t\t\tassert.NotNil(t, stackInfo.Deployment)\n\t\t\tif assert.Equal(t, 5, len(stackInfo.Deployment.Resources)) {\n\t\t\t\tstackRes := stackInfo.Deployment.Resources[0]\n\t\t\t\tassert.NotNil(t, stackRes)\n\t\t\t\tassert.Equal(t, resource.RootStackType, stackRes.Type)\n\t\t\t\tassert.Equal(t, \"\", string(stackRes.Parent))\n\t\t\t}\n\t\t},\n\t}\n\tintegration.ProgramTest(t, opts)\n}", "func TestSetReadyConcurrent(t *testing.T) {\n\tvar ready readiness\n\twg := sync.WaitGroup{}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\t_ = ready.IsReady()\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tready.SetReady(true)\n\t}()\n\n\twg.Wait()\n\trequire.True(t, ready.IsReady())\n}", "func TestConcurrencyLimit(t *testing.T) {\n\tt.Parallel()\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tt.Cleanup(cancel)\n\n\tconfig := Config{MaxConcurrency: 4}\n\tcountdown := NewCountdown(config.MaxConcurrency * 2)\n\tprocess := NewMockEventsProcess(ctx, t, config, func(ctx context.Context, event types.Event) error {\n\t\tdefer countdown.Decrement()\n\t\ttime.Sleep(time.Second)\n\t\treturn trace.Wrap(ctx.Err())\n\t})\n\n\ttimeBefore := time.Now()\n\tfor i := 0; i < config.MaxConcurrency; i++ {\n\t\tresource, err := types.NewAccessRequest(fmt.Sprintf(\"REQ-%v\", i+1), \"foo\", \"admin\")\n\t\trequire.NoError(t, err)\n\n\t\tfor j := 0; j < 2; j++ {\n\t\t\tprocess.Events.Fire(types.Event{Type: types.OpPut, Resource: resource})\n\t\t}\n\t}\n\trequire.NoError(t, countdown.Wait(ctx))\n\n\ttimeAfter := time.Now()\n\tassert.InDelta(t, 4*time.Second, timeAfter.Sub(timeBefore), float64(750*time.Millisecond))\n}", "func TestProject_CreateProject_DoesNotSwallowErrorFromFailedAsyncStatusCheckCall(t *testing.T) {\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\n\tcoreClient := azdosdkmocks.NewMockCoreClient(ctrl)\n\toperationsClient := azdosdkmocks.NewMockOperationsClient(ctrl)\n\tclients := &client.AggregatedClient{\n\t\tCoreClient: coreClient,\n\t\tOperationsClient: operationsClient,\n\t\tCtx: context.Background(),\n\t}\n\n\texpectedProjectCreateArgs := core.QueueCreateProjectArgs{ProjectToCreate: &testProject}\n\tmockedOperationReference := operations.OperationReference{Id: &testID}\n\texpectedOperationArgs := operations.GetOperationArgs{OperationId: &testID}\n\n\tcoreClient.\n\t\tEXPECT().\n\t\tQueueCreateProject(clients.Ctx, expectedProjectCreateArgs).\n\t\tReturn(&mockedOperationReference, nil).\n\t\tTimes(1)\n\n\toperationsClient.\n\t\tEXPECT().\n\t\tGetOperation(clients.Ctx, expectedOperationArgs).\n\t\tReturn(nil, errors.New(\"GetOperation() failed\")).\n\t\tTimes(1)\n\n\terr := createProject(clients, &testProject, 10*time.Minute)\n\trequire.Equal(t, \" waiting for project ready. GetOperation() failed \", err.Error())\n}", "func TestNamespacePreExisting(t *testing.T) {\n\ttestName := \"TestNamespacePreExisting\"\n\tbeforeTest()\n\t// kinds to check for status\n\tvar kindsToCheckStatus = map[string]bool{\n\t\tAPPLICATION: true,\n\t\t\"Deployment\": true,\n\t\t\"Service\": true,\n\t}\n\n\t// starting resources to pre-populate\n\tvar files = []string{\n\t\t/* 0 */ KappnavConfigFile,\n\t\t/* 1 */ CrdApplication,\n\t\t/* 2 */ ns1Service,\n\t\t/* 3 */ ns1Deployment,\n\t\t/* 4 */ ns2Service,\n\t\t/* 5 */ ns2Deployment,\n\t}\n\titeration0IDs, err := readResourceIDs(files)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t/* Iteration 0: no applications. No resources should have status */\n\ttestActions := newTestActions(testName, kindsToCheckStatus)\n\tvar emptyIDs = []resourceID{}\n\n\t// status should not be checked when there are not applications\n\titeration0IDs[2].expectedStatus = NoStatus\n\titeration0IDs[3].expectedStatus = NoStatus\n\titeration0IDs[4].expectedStatus = NoStatus\n\titeration0IDs[5].expectedStatus = NoStatus\n\ttestActions.addIteration(iteration0IDs, emptyIDs)\n\n\t// iteration 1: add application to NS_1. All in NS_1 is normal.\n\t// All in NS_2 remains NoStatus\n\tres, err := readOneResourceID(ns1App)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tarrayLength := len(iteration0IDs)\n\tvar iteration1IDs = make([]resourceID, arrayLength, arrayLength)\n\tcopy(iteration1IDs, iteration0IDs)\n\titeration1IDs = append(iteration1IDs, res)\n\tarrayLength++\n\titeration1IDs[2].expectedStatus = Normal\n\titeration1IDs[3].expectedStatus = Normal\n\titeration1IDs[6].expectedStatus = Normal\n\ttestActions.addIteration(iteration1IDs, emptyIDs)\n\n\t/* iteration 4: clean up */\n\ttestActions.addIteration(emptyIDs, emptyIDs)\n\n\tclusterWatcher, err := createClusterWatcher(iteration0IDs, testActions, StatusFailureRate)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer clusterWatcher.shutDown()\n\n\t// make all trasition of testAction\n\terr = testActions.transitionAll()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (tc *testContext) testNodesBecomeReadyAndSchedulable(t *testing.T) {\n\tnodes := gc.allNodes()\n\tfor _, node := range nodes {\n\t\tt.Run(node.GetName(), func(t *testing.T) {\n\t\t\terr := wait.PollImmediate(retry.Interval, retry.ResourceChangeTimeout, func() (done bool, err error) {\n\t\t\t\tfoundNode, err := tc.client.K8s.CoreV1().Nodes().Get(context.TODO(), node.GetName(), meta.GetOptions{})\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\treturn tc.nodeReadyAndSchedulable(*foundNode), nil\n\t\t\t})\n\t\t\tassert.NoError(t, err)\n\t\t})\n\t}\n}", "func TestConcurrencyAndRaceConditions(t *testing.T) {\n\t//\tdefer profile.Start(profile.MemProfile).Stop()\n\tfmt.Println(\"Testing for concurrency and race conditions\")\n\tq := New()\n\tq.Sched()\n\tnotifyChannel := make(chan bool)\n\tfor i := 0; i < 1000; i++ {\n\t\tgo func(j int) {\n\t\t\tfor j := 0; j < 2000; j++ {\n\t\t\t\tjd := jobData{\n\t\t\t\t\tstatusChannel: notifyChannel,\n\t\t\t\t\tdata: int32(j),\n\t\t\t\t}\n\t\t\t\tjob := Job{\n\t\t\t\t\tJobData: jd,\n\t\t\t\t\tTaskCreator: taskHandler{},\n\t\t\t\t}\n\t\t\t\tq.PushChannel() <- job\n\t\t\t}\n\t\t}(i)\n\t}\n\tcounter := 0\n\tdone := false\n\tfor {\n\t\tselect {\n\t\tcase <-notifyChannel:\n\t\t\tcounter++\n\t\t\tif counter == 2000000 {\n\t\t\t\tdone = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif done {\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.Equal(t, 1999000000, int(sum))\n\tassert.Equal(t, 2000000, counter)\n}", "func containerGCTest(f *framework.Framework, test testRun) {\n\tvar runtime internalapi.RuntimeService\n\tginkgo.BeforeEach(func() {\n\t\tvar err error\n\t\truntime, _, err = getCRIClient()\n\t\tframework.ExpectNoError(err)\n\t})\n\tfor _, pod := range test.testPods {\n\t\t// Initialize the getContainerNames function to use CRI runtime client.\n\t\tpod.getContainerNames = func() ([]string, error) {\n\t\t\trelevantContainers := []string{}\n\t\t\tcontainers, err := runtime.ListContainers(context.Background(), &runtimeapi.ContainerFilter{\n\t\t\t\tLabelSelector: map[string]string{\n\t\t\t\t\ttypes.KubernetesPodNameLabel: pod.podName,\n\t\t\t\t\ttypes.KubernetesPodNamespaceLabel: f.Namespace.Name,\n\t\t\t\t},\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn relevantContainers, err\n\t\t\t}\n\t\t\tfor _, container := range containers {\n\t\t\t\trelevantContainers = append(relevantContainers, container.Labels[types.KubernetesContainerNameLabel])\n\t\t\t}\n\t\t\treturn relevantContainers, nil\n\t\t}\n\t}\n\n\tginkgo.Context(fmt.Sprintf(\"Garbage Collection Test: %s\", test.testName), func() {\n\t\tginkgo.BeforeEach(func(ctx context.Context) {\n\t\t\trealPods := getPods(test.testPods)\n\t\t\te2epod.NewPodClient(f).CreateBatch(ctx, realPods)\n\t\t\tginkgo.By(\"Making sure all containers restart the specified number of times\")\n\t\t\tgomega.Eventually(ctx, func(ctx context.Context) error {\n\t\t\t\tfor _, podSpec := range test.testPods {\n\t\t\t\t\terr := verifyPodRestartCount(ctx, f, podSpec.podName, podSpec.numContainers, podSpec.restartCount)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}, setupDuration, runtimePollInterval).Should(gomega.BeNil())\n\t\t})\n\n\t\tginkgo.It(\"Should eventually garbage collect containers when we exceed the number of dead containers per container\", func(ctx context.Context) {\n\t\t\ttotalContainers := 0\n\t\t\tfor _, pod := range test.testPods {\n\t\t\t\ttotalContainers += pod.numContainers*2 + 1\n\t\t\t}\n\t\t\tgomega.Eventually(ctx, func() error {\n\t\t\t\ttotal := 0\n\t\t\t\tfor _, pod := range test.testPods {\n\t\t\t\t\tcontainerNames, err := pod.getContainerNames()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\ttotal += len(containerNames)\n\t\t\t\t\t// Check maxPerPodContainer for each container in the pod\n\t\t\t\t\tfor i := 0; i < pod.numContainers; i++ {\n\t\t\t\t\t\tcontainerCount := 0\n\t\t\t\t\t\tfor _, containerName := range containerNames {\n\t\t\t\t\t\t\tif containerName == pod.getContainerName(i) {\n\t\t\t\t\t\t\t\tcontainerCount++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif containerCount > maxPerPodContainer+1 {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"expected number of copies of container: %s, to be <= maxPerPodContainer: %d; list of containers: %v\",\n\t\t\t\t\t\t\t\tpod.getContainerName(i), maxPerPodContainer, containerNames)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//Check maxTotalContainers. Currently, the default is -1, so this will never happen until we can configure maxTotalContainers\n\t\t\t\tif maxTotalContainers > 0 && totalContainers <= maxTotalContainers && total > maxTotalContainers {\n\t\t\t\t\treturn fmt.Errorf(\"expected total number of containers: %v, to be <= maxTotalContainers: %v\", total, maxTotalContainers)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}, garbageCollectDuration, runtimePollInterval).Should(gomega.BeNil())\n\n\t\t\tif maxPerPodContainer >= 2 && maxTotalContainers < 0 { // make sure constraints wouldn't make us gc old containers\n\t\t\t\tginkgo.By(\"Making sure the kubelet consistently keeps around an extra copy of each container.\")\n\t\t\t\tgomega.Consistently(ctx, func() error {\n\t\t\t\t\tfor _, pod := range test.testPods {\n\t\t\t\t\t\tcontainerNames, err := pod.getContainerNames()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor i := 0; i < pod.numContainers; i++ {\n\t\t\t\t\t\t\tcontainerCount := 0\n\t\t\t\t\t\t\tfor _, containerName := range containerNames {\n\t\t\t\t\t\t\t\tif containerName == pod.getContainerName(i) {\n\t\t\t\t\t\t\t\t\tcontainerCount++\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif pod.restartCount > 0 && containerCount < maxPerPodContainer+1 {\n\t\t\t\t\t\t\t\treturn fmt.Errorf(\"expected pod %v to have extra copies of old containers\", pod.podName)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}, garbageCollectDuration, runtimePollInterval).Should(gomega.BeNil())\n\t\t\t}\n\t\t})\n\n\t\tginkgo.AfterEach(func(ctx context.Context) {\n\t\t\tfor _, pod := range test.testPods {\n\t\t\t\tginkgo.By(fmt.Sprintf(\"Deleting Pod %v\", pod.podName))\n\t\t\t\te2epod.NewPodClient(f).DeleteSync(ctx, pod.podName, metav1.DeleteOptions{}, e2epod.DefaultPodDeletionTimeout)\n\t\t\t}\n\n\t\t\tginkgo.By(\"Making sure all containers get cleaned up\")\n\t\t\tgomega.Eventually(ctx, func() error {\n\t\t\t\tfor _, pod := range test.testPods {\n\t\t\t\t\tcontainerNames, err := pod.getContainerNames()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif len(containerNames) > 0 {\n\t\t\t\t\t\treturn fmt.Errorf(\"%v containers still remain\", containerNames)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}, garbageCollectDuration, runtimePollInterval).Should(gomega.BeNil())\n\n\t\t\tif ginkgo.CurrentSpecReport().Failed() && framework.TestContext.DumpLogsOnFailure {\n\t\t\t\tlogNodeEvents(ctx, f)\n\t\t\t\tlogPodEvents(ctx, f)\n\t\t\t}\n\t\t})\n\t})\n}", "func DeploymentStatusCheck(experimentsDetails *experimentTypes.ExperimentDetails, clients clients.ClientSets, appsUnderTest []experimentTypes.ApplicationUnderTest, resultDetails *types.ResultDetails, eventsDetails *types.EventDetails, chaosDetails *types.ChaosDetails) error {\n\n\t//Record start timestamp\n\tChaosStartTimeStamp := time.Now().Unix()\n\tisFailed := false\n\n\terr = retry.\n\t\tTimes(uint(experimentsDetails.ChaosDuration / experimentsDetails.Delay)).\n\t\tWait(time.Duration(experimentsDetails.Delay) * time.Second).\n\t\tTry(func(attempt uint) error {\n\t\t\tfor _, app := range appsUnderTest {\n\t\t\t\tdeployment, err := appsv1DeploymentClient.Get(app.AppName, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Errorf(\"Unable to find the deployment with name %v, err: %v\", app.AppName, err)\n\t\t\t\t}\n\t\t\t\tlog.Infof(\"Deployment's Available Replica Count is %v\", deployment.Status.AvailableReplicas)\n\t\t\t\tif int(deployment.Status.AvailableReplicas) != app.ReplicaCount {\n\t\t\t\t\tisFailed = true\n\t\t\t\t\treturn errors.Errorf(\"Application %s is not scaled yet, err: %v\", app.AppName, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tisFailed = false\n\t\t\treturn nil\n\t\t})\n\n\tif isFailed {\n\t\terr = AutoscalerRecoveryInDeployment(experimentsDetails, clients, appsUnderTest)\n\t\tif err != nil {\n\t\t\treturn errors.Errorf(\"Unable to perform autoscaling, err: %v\", err)\n\t\t}\n\t\treturn errors.Errorf(\"Failed to scale the application\")\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// run the probes during chaos\n\tif len(resultDetails.ProbeDetails) != 0 {\n\t\tif err = probe.RunProbes(chaosDetails, clients, resultDetails, \"DuringChaos\", eventsDetails); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t//ChaosCurrentTimeStamp contains the current timestamp\n\tChaosCurrentTimeStamp := time.Now().Unix()\n\tif int(ChaosCurrentTimeStamp-ChaosStartTimeStamp) <= experimentsDetails.ChaosDuration {\n\t\tlog.Info(\"[Wait]: Waiting for completion of chaos duration\")\n\t\ttime.Sleep(time.Duration(experimentsDetails.ChaosDuration-int(ChaosCurrentTimeStamp-ChaosStartTimeStamp)) * time.Second)\n\t}\n\n\treturn nil\n}", "func TestCancelJobAllWorkersOccupied(t *testing.T) {\n\ts := newTestingServer()\n\tmux := SetupRoutes(s)\n\n\tjobs := []fuq.JobDescription{\n\t\t{\n\t\t\tName: \"job1\",\n\t\t\tNumTasks: 16,\n\t\t\tWorkingDir: \"/foo/bar\",\n\t\t\tLoggingDir: \"/foo/bar/logs\",\n\t\t\tCommand: \"/foo/foo_it.sh\",\n\t\t},\n\t\t{\n\t\t\tName: \"job2\",\n\t\t\tNumTasks: 27,\n\t\t\tWorkingDir: \"/foo/baz\",\n\t\t\tLoggingDir: \"/foo/baz/logs\",\n\t\t\tCommand: \"/foo/baz_it.sh\",\n\t\t},\n\t}\n\n\tfor i, j := range jobs {\n\t\tjobs[i].JobId = addJob(t, s.Foreman, j)\n\t\tjobs[i].Status = fuq.Waiting\n\t}\n\n\torigJobs := make([]fuq.JobDescription, len(jobs))\n\tcopy(origJobs, jobs)\n\n\twsConn, client := newTestClient(t, s)\n\tdefer wsConn.Close()\n\tdefer client.Close()\n\n\tni := client.NodeInfo\n\t_ = ni\n\n\tmsgCh := make(chan proto.Message)\n\ttaskCh := make(chan []fuq.Task)\n\n\tvar nproc, nrun uint16 = 8, 0\n\tvar running []fuq.Task\n\tvar toCancel []int\n\n\tclient.OnMessageFunc(proto.MTypeJob, func(msg proto.Message) proto.Message {\n\t\ttasks := msg.Data.([]fuq.Task)\n\n\t\tif len(tasks) > int(nproc) {\n\t\t\tpanic(\"invalid number of tasks\")\n\t\t}\n\n\t\tt.Logf(\"onJob received %d tasks: %v\", len(tasks), tasks)\n\t\tnproc -= uint16(len(tasks))\n\t\tnrun += uint16(len(tasks))\n\n\t\trepl := proto.OkayMessage(nproc, nrun, msg.Seq)\n\n\t\trunning = append(running, tasks...)\n\n\t\ttaskCh <- tasks\n\t\treturn repl\n\t})\n\n\tclient.OnMessageFunc(proto.MTypeCancel, func(msg proto.Message) proto.Message {\n\t\tpairs := msg.Data.([]fuq.TaskPair)\n\n\t\tncancel := 0\n\t\tfor i, t := range running {\n\t\t\tfor _, p := range pairs {\n\t\t\t\tif t.JobId != p.JobId {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif p.Task >= 0 && t.Task != p.Task {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\ttoCancel = append(toCancel, i)\n\t\t\t\tncancel++\n\t\t\t}\n\t\t}\n\t\tmsgCh <- msg\n\n\t\trepl := proto.OkayMessage(uint16(ncancel), 0, msg.Seq)\n\t\treturn repl\n\t})\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tfuqtest.GoPanicOnError(ctx, client.runConversationLoop)\n\n\tmsg, err := client.SendHello(ctx, proto.HelloData{\n\t\tNumProcs: 8,\n\t\tRunning: nil,\n\t})\n\n\tif err != nil {\n\t\tt.Fatalf(\"error in HELLO: %v\", err)\n\t}\n\n\tnp, nr := msg.AsOkay()\n\tif np != 8 || nr != 0 {\n\t\tt.Fatalf(\"expected OK(8|0), but received OK(%d|%d)\", nproc, nrun)\n\t}\n\n\ttasks := <-taskCh\n\t// JOB message received\n\tif len(tasks) != 8 {\n\t\tt.Fatalf(\"expected 8 task, but received %d tasks\", len(tasks))\n\t}\n\n\t/** Cancel job **/\n\tenv := ClientRequestEnvelope{\n\t\tAuth: fuq.Client{Password: testingPass, Client: \"testing\"},\n\t\tMsg: fuq.ClientStateChangeReq{\n\t\t\tJobIds: []fuq.JobId{jobs[0].JobId},\n\t\t\tAction: \"cancel\",\n\t\t},\n\t}\n\n\trepl := []fuq.JobStateChangeResponse{}\n\n\troundTrip{\n\t\tT: t,\n\t\tMsg: env,\n\t\tDst: &repl,\n\t\tTarget: \"/\" + ClientJobStatePath,\n\t}.ExpectOK(mux.ServeHTTP)\n\tt.Logf(\"response is %v\", repl)\n\n\texpectedRepl := []fuq.JobStateChangeResponse{\n\t\t{jobs[0].JobId, fuq.Running, fuq.Cancelled},\n\t}\n\n\tif !reflect.DeepEqual(repl, expectedRepl) {\n\t\tt.Fatalf(\"expected response '%v' but found '%v'\",\n\t\t\texpectedRepl, repl)\n\t}\n\n\t/** Receive CANCEL message **/\n\tmsg = <-msgCh\n\t// expect CANCEL message\n\n\texpected := proto.Message{\n\t\tType: proto.MTypeCancel,\n\t\tSeq: msg.Seq,\n\t\tData: []fuq.TaskPair{{jobs[0].JobId, -1}},\n\t}\n\n\tif !reflect.DeepEqual(msg, expected) {\n\t\tt.Fatalf(\"expected '%v', but found '%v'\", expected, msg)\n\t}\n}", "func TestUnitToContainerStatus(t *testing.T) {\n\ttestCases := []struct {\n\t\tunitState api.UnitState\n\t}{\n\t\t{\n\t\t\tunitState: api.UnitState{\n\t\t\t\tWaiting: &api.UnitStateWaiting{\n\t\t\t\t\tReason: \"waiting to start\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tunitState: api.UnitState{\n\t\t\t\tRunning: &api.UnitStateRunning{\n\t\t\t\t\tStartedAt: api.Now(),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tunitState: api.UnitState{\n\t\t\t\tTerminated: &api.UnitStateTerminated{\n\t\t\t\t\tExitCode: int32(rand.Intn(256)),\n\t\t\t\t\tFinishedAt: api.Now(),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tus := api.UnitStatus{\n\t\t\tName: \"myunit\",\n\t\t\tRestartCount: 0,\n\t\t\tImage: \"elotl/myimage\",\n\t\t\tState: tc.unitState,\n\t\t}\n\t\tcs := unitToContainerStatus(us)\n\t\tif us.State.Waiting != nil {\n\t\t\tassert.NotNil(t, cs.State.Waiting)\n\t\t\tassert.Nil(t, cs.State.Running)\n\t\t\tassert.Nil(t, cs.State.Terminated)\n\t\t\tassert.Equal(t, us.State.Waiting.Reason, cs.State.Waiting.Reason)\n\t\t}\n\t\tif us.State.Running != nil {\n\t\t\tassert.NotNil(t, cs.State.Running)\n\t\t\tassert.Nil(t, cs.State.Waiting)\n\t\t\tassert.Nil(t, cs.State.Terminated)\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\tus.State.Running.StartedAt.Time,\n\t\t\t\tcs.State.Running.StartedAt.Time)\n\t\t}\n\t\tif us.State.Terminated != nil {\n\t\t\tassert.NotNil(t, cs.State.Terminated)\n\t\t\tassert.Nil(t, cs.State.Running)\n\t\t\tassert.Nil(t, cs.State.Waiting)\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\tus.State.Terminated.ExitCode,\n\t\t\t\tcs.State.Terminated.ExitCode)\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\tus.State.Terminated.FinishedAt.Time,\n\t\t\t\tcs.State.Terminated.FinishedAt.Time)\n\t\t}\n\t}\n}", "func (d *deploymentTester) markUpdatedPodsReady(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tns := d.deployment.Namespace\n\terr := wait.PollImmediate(pollInterval, pollTimeout, func() (bool, error) {\n\t\t// We're done when the deployment is complete\n\t\tif completed, err := d.deploymentComplete(); err != nil {\n\t\t\treturn false, err\n\t\t} else if completed {\n\t\t\treturn true, nil\n\t\t}\n\t\t// Otherwise, mark remaining pods as ready\n\t\tpods, err := d.listUpdatedPods()\n\t\tif err != nil {\n\t\t\td.t.Log(err)\n\t\t\treturn false, nil\n\t\t}\n\t\td.t.Logf(\"%d/%d of deployment pods are created\", len(pods), *d.deployment.Spec.Replicas)\n\t\tfor i := range pods {\n\t\t\tpod := pods[i]\n\t\t\tif podutil.IsPodReady(&pod) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err = markPodReady(d.c, ns, &pod); err != nil {\n\t\t\t\td.t.Logf(\"failed to update Deployment pod %s, will retry later: %v\", pod.Name, err)\n\t\t\t}\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\td.t.Errorf(\"failed to mark updated Deployment pods to ready: %v\", err)\n\t}\n}", "func (s *DomainSuite) TestUpdateConfigConcurrently() {\n\tid := \"test\"\n\tuserMech := \"h2\"\n\tuserId := \"dave\"\n\tinitialData := `{ \"a\": 0, \"b\": 0 }`\n\n\ttestRepo := &memoryRepository{\n\t\tdata: map[string]*ChangeSet{\n\t\t\tid: &ChangeSet{\n\t\t\t\tId: id,\n\t\t\t\tBody: []byte(initialData),\n\t\t\t\tTimestamp: time.Now(),\n\t\t\t},\n\t\t},\n\t}\n\n\tDefaultRepository = testRepo\n\n\tlock := &mockLock{}\n\ts.zk.\n\t\tOn(\"NewLock\", lockPath(id), gozk.WorldACL(gozk.PermAll)).\n\t\tReturn(lock)\n\n\tpaths := []string{\"a\", \"b\"}\n\n\tfor i := 1; i <= 100; i++ {\n\t\twg := sync.WaitGroup{}\n\t\twg.Add(len(paths))\n\n\t\tfor _, path := range paths {\n\t\t\tgo func(path string) {\n\t\t\t\tmsg := fmt.Sprintf(\"Setting %s to %d\", path, i)\n\t\t\t\terr := CreateOrUpdateConfig(fmt.Sprintf(\"%s:%d\", path, i), id, path, userMech, userId, msg, []byte(fmt.Sprintf(\"%d\", i)))\n\t\t\t\ts.NoError(err)\n\n\t\t\t\twg.Done()\n\t\t\t}(path)\n\t\t}\n\n\t\twg.Wait()\n\t\tdata, _, err := ReadConfig(id, \"\")\n\t\ts.NoError(err, \"Failed to update config\")\n\n\t\tconfig := map[string]int{}\n\t\terr = json.Unmarshal(data, &config)\n\t\ts.NoError(err, \"Failed to unmarshal config\")\n\n\t\tfor _, path := range paths {\n\t\t\ts.Equal(config[path], i)\n\t\t}\n\t}\n}", "func testReconcileDeploymentReadyRestartRequired(t *testing.T) {\n\treaper := createReaper()\n\tdeployment := createReadyDeployment(reaper)\n\n\tobjs := []runtime.Object{reaper, deployment}\n\n\tSetConfigurationUpdatedCondition(&reaper.Status)\n\n\tr := createDeploymentReconciler(objs...)\n\tresult, err := r.ReconcileDeployment(context.TODO(), reaper)\n\n\tif result == nil {\n\t\tt.Errorf(\"expected non-nil result\")\n\t} else if !result.Requeue {\n\t\tt.Errorf(\"expected requeue\")\n\t}\n\n\tif err != nil {\n\t\tt.Errorf(\"expected err (nil), got (%s)\", err)\n\t}\n\n\tcond := GetCondition(&reaper.Status, v1alpha1.ConfigurationUpdated)\n\tif cond == nil {\n\t\tt.Errorf(\"expected to find condition (%s)\", v1alpha1.ConfigurationUpdated)\n\t} else if cond.Reason != RestartRequiredReason {\n\t\tt.Errorf(\"condition %s reason is wrong: expected (%s), got (%s)\", v1alpha1.ConfigurationUpdated, RestartRequiredReason, cond.Reason)\n\t}\n\n\tdeployment = &appsv1.Deployment{}\n\tif err := r.client.Get(context.TODO(), namespaceName, deployment); err != nil {\n\t\tt.Errorf(\"failed to get deployment: (%s)\", err)\n\t} else if _, found := deployment.Spec.Template.Annotations[reaperRestartedAt]; !found {\n\t\tt.Errorf(\"expected to find deployment annotation: (%s)\", reaperRestartedAt)\n\t}\n}", "func GetBuildMockClientToRun2Times() MockClient {\n\tmc := NewMockClient()\n\n\tmc.AddData(buildHead)\n\tmc.AddData(buildHead)\n\n\tmc.AddData(buildPost)\n\tmc.AddData(buildPost)\n\n\tmc.AddData(buildGet1)\n\tmc.AddData(buildGet2)\n\tmc.AddData(buildGet1)\n\tmc.AddData(buildGet2)\n\n\tmc.AddData(buildGetTasks)\n\tmc.AddData(buildGetTasks)\n\n\tmc.AddData(buildGetTask0Logs)\n\tmc.AddData(buildGetTask1Logs)\n\tmc.AddData(buildGetTask2Logs)\n\tmc.AddData(buildGetTask3Logs)\n\tmc.AddData(buildGetTask4Logs)\n\tmc.AddData(buildGetTask5Logs)\n\tmc.AddData(buildGetTask6Logs)\n\tmc.AddData(buildGetTask7Logs)\n\tmc.AddData(buildGetTask8Logs)\n\tmc.AddData(buildGetTask9Logs)\n\tmc.AddData(buildGetTask10Logs)\n\tmc.AddData(buildGetTask11Logs)\n\tmc.AddData(buildGetTask12Logs)\n\n\tmc.AddData(buildGetTask0Logs)\n\tmc.AddData(buildGetTask1Logs)\n\tmc.AddData(buildGetTask2Logs)\n\tmc.AddData(buildGetTask3Logs)\n\tmc.AddData(buildGetTask4Logs)\n\tmc.AddData(buildGetTask5Logs)\n\tmc.AddData(buildGetTask6Logs)\n\tmc.AddData(buildGetTask7Logs)\n\tmc.AddData(buildGetTask8Logs)\n\tmc.AddData(buildGetTask9Logs)\n\tmc.AddData(buildGetTask10Logs)\n\tmc.AddData(buildGetTask11Logs)\n\tmc.AddData(buildGetTask12Logs)\n\n\tmc.AddData(buildGetTask0Result)\n\tmc.AddData(buildGetTask1Result)\n\tmc.AddData(buildGetTask2Result)\n\tmc.AddData(buildGetTask3Result)\n\tmc.AddData(buildGetTask4Result)\n\tmc.AddData(buildGetTask5Result)\n\tmc.AddData(buildGetTask6Result)\n\tmc.AddData(buildGetTask7Result)\n\tmc.AddData(buildGetTask8Result)\n\tmc.AddData(buildGetTask9Result)\n\tmc.AddData(buildGetTask10Result)\n\tmc.AddData(buildGetTask11Result)\n\tmc.AddData(buildGetTask12Result)\n\n\tmc.AddData(buildGetTask0Result)\n\tmc.AddData(buildGetTask1Result)\n\tmc.AddData(buildGetTask2Result)\n\tmc.AddData(buildGetTask3Result)\n\tmc.AddData(buildGetTask4Result)\n\tmc.AddData(buildGetTask5Result)\n\tmc.AddData(buildGetTask6Result)\n\tmc.AddData(buildGetTask7Result)\n\tmc.AddData(buildGetTask8Result)\n\tmc.AddData(buildGetTask9Result)\n\tmc.AddData(buildGetTask10Result)\n\tmc.AddData(buildGetTask11Result)\n\tmc.AddData(buildGetTask12Result)\n\n\tmc.AddData(buildGetTask11ResultMedia)\n\tmc.AddData(buildGetTask11ResultMedia)\n\n\tmc.AddData(buildGetValues)\n\tmc.AddData(buildGetValues)\n\n\treturn mc\n}", "func checkPods(podClient v1.CoreV1Interface, logger *log.Logger, filters ...PodPredicate) ([]kubev1.Pod, error) {\n\tlogger = logging.CreateNewStdLoggerOrUseExistingLogger(logger)\n\n\tlogger.Print(\"Checking that all Pods are running or completed...\")\n\n\tlist, err := podClient.Pods(metav1.NamespaceAll).List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting pod list: %v\", err)\n\t}\n\n\tif len(list.Items) == 0 {\n\t\treturn nil, fmt.Errorf(\"pod list is empty. this should NOT happen\")\n\t}\n\n\tpods := filterPods(list, filters...)\n\n\t// Keep track of all pending pods that are not associated with a job\n\t// and store all pods associated with a job for further analysis\n\tpendingPods := []kubev1.Pod{}\n\tjobPods := []kubev1.Pod{}\n\tfor _, pod := range pods.Items {\n\t\tif IsNotControlledByJob(pod) {\n\t\t\t// Completed pod not associated with a job, e.g. a standalone pod\n\t\t\tif pod.Status.Phase == kubev1.PodSucceeded {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif pod.Status.Phase != kubev1.PodPending {\n\t\t\t\treturn nil, fmt.Errorf(\"pod %s/%s in unexpected phase %s: reason: %s message: %s\", pod.Namespace, pod.Name, pod.Status.Phase, pod.Status.Reason, pod.Status.Message)\n\t\t\t}\n\t\t\tlogger.Printf(\"pod %s/%s is not ready. Phase: %s, Reason: %s, Message: %s\", pod.Namespace, pod.Name, pod.Status.Phase, pod.Status.Reason, pod.Status.Message)\n\t\t\tpendingPods = append(pendingPods, pod)\n\t\t} else {\n\t\t\tjobPods = append(jobPods, pod)\n\t\t}\n\t}\n\n\tpendingJobPods, err := checkJobPods(jobPods, logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogger.Printf(\"%v pods are currently not running or complete:\", len(pendingPods)+len(pendingJobPods))\n\n\treturn append(pendingPods, pendingJobPods...), nil\n}", "func TestConcurrent2(t *testing.T) {\n\tfmt.Printf(\"Test: more concurrent puts and configuration changes...\\n\")\n\n\tcfg := makeConfig(t, 3, false, -1)\n\tdefer cfg.cleanup()\n\n\tck := cfg.makeClient()\n\n\tcfg.join(1)\n\tcfg.join(0)\n\tcfg.join(2)\n\n\tn := 10\n\tka := make([]string, n)\n\tva := make([]string, n)\n\tfor i := 0; i < n; i++ {\n\t\tka[i] = strconv.Itoa(i) // ensure multiple shards\n\t\tva[i] = randstring(1)\n\t\tck.Put(ka[i], va[i])\n\t}\n\n\tvar done int32\n\tch := make(chan bool)\n\n\tff := func(i int, ck1 *Clerk) {\n\t\tdefer func() { ch <- true }()\n\t\tfor atomic.LoadInt32(&done) == 0 {\n\t\t\tx := randstring(1)\n\t\t\tck1.Append(ka[i], x)\n\t\t\tva[i] += x\n\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t}\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\tck1 := cfg.makeClient()\n\t\tgo ff(i, ck1)\n\t}\n\n\tcfg.leave(0)\n\tcfg.leave(2)\n\ttime.Sleep(3000 * time.Millisecond)\n\tcfg.join(0)\n\tcfg.join(2)\n\tcfg.leave(1)\n\ttime.Sleep(3000 * time.Millisecond)\n\tcfg.join(1)\n\tcfg.leave(0)\n\tcfg.leave(2)\n\ttime.Sleep(3000 * time.Millisecond)\n\n\tcfg.ShutdownGroup(1)\n\tcfg.ShutdownGroup(2)\n\ttime.Sleep(1000 * time.Millisecond)\n\tcfg.StartGroup(1)\n\tcfg.StartGroup(2)\n\n\ttime.Sleep(2 * time.Second)\n\n\tatomic.StoreInt32(&done, 1)\n\tfor i := 0; i < n; i++ {\n\t\t<-ch\n\t}\n\n\tfor i := 0; i < n; i++ {\n\t\tcheck(t, ck, ka[i], va[i])\n\t}\n\n\tfmt.Printf(\" ... Passed\\n\")\n}", "func TestMaintenanceCodecov(t *testing.T) {\n\t// For Codecov - this does not test anything\n\tf := NewFactory()\n\tv, command := config.Viperize(f.AddFlags)\n\t// Lets speed up the maintenance ticker..\n\tcommand.ParseFlags([]string{\n\t\t\"--badger.maintenance-interval=10ms\",\n\t})\n\tf.InitFromViper(v, zap.NewNop())\n\tmFactory := metricstest.NewFactory(0)\n\tf.Initialize(mFactory, zap.NewNop())\n\tdefer f.Close()\n\n\twaiter := func() {\n\t\tfor sleeps := 0; sleeps < 8; sleeps++ {\n\t\t\t// Wait for the scheduler\n\t\t\ttime.Sleep(time.Duration(50) * time.Millisecond)\n\t\t}\n\t}\n\n\terr := f.store.Close()\n\tassert.NoError(t, err)\n\twaiter() // This should trigger the logging of error\n}", "func (t *TestSpec) RunTest(kub *helpers.Kubectl) {\n\tdefer func() { go t.Destroy(destroyDelay, kub.BasePath()) }()\n\n\tt.Kub = kub\n\terr := t.CreateManifests()\n\tgomega.Expect(err).To(gomega.BeNil(), \"cannot create pods manifest for %s\", t.Prefix)\n\n\tmanifest, err := t.ApplyManifest(kub.BasePath())\n\tgomega.Expect(err).To(gomega.BeNil(), \"cannot apply pods manifest for %s\", t.Prefix)\n\tlog.WithField(\"prefix\", t.Prefix).Infof(\"Manifest '%s' is created correctly\", manifest)\n\n\terr = t.Destination.CreateApplyManifest(t, kub.BasePath())\n\tgomega.Expect(err).To(gomega.BeNil(), \"cannot apply destination for %s\", t.Prefix)\n\n\tif t.IsPolicyInvalid() {\n\t\t// Some policies cannot be applied correctly because of different\n\t\t// rules. This code makes sure that the status of the policy has a error\n\t\t// in the status.\n\t\tcnp, err := t.InvalidNetworkPolicyApply(kub.BasePath())\n\t\tkub.Exec(fmt.Sprintf(\"%s delete cnp %s\", helpers.KubectlCmd, t.Prefix))\n\t\tgomega.Expect(err).To(gomega.BeNil(), \"Cannot apply network policy\")\n\t\tgomega.Expect(cnp).NotTo(gomega.BeNil(), \"CNP is not a valid struct\")\n\t\tgomega.Expect(cnp.Status.Nodes).NotTo(gomega.BeEmpty(), \"CNP Status is empty\")\n\n\t\tfor node, status := range cnp.Status.Nodes {\n\t\t\tgomega.Expect(status.Error).NotTo(gomega.BeEmpty(),\n\t\t\t\t\"Node %q applied invalid policy and do not raise an error\", node)\n\t\t}\n\t\treturn\n\t}\n\n\terr = t.NetworkPolicyApply(kub.BasePath())\n\tgomega.Expect(err).To(gomega.BeNil(), \"cannot apply network policy for %s\", t.Prefix)\n\n\terr = kub.CiliumEndpointWaitReady()\n\tgomega.Expect(err).To(gomega.BeNil(), \"Endpoints are not ready after timeout\")\n\n\terr = t.ExecTest()\n\tgomega.Expect(err).To(gomega.BeNil(), \"cannot execute test for %s\", t.Prefix)\n}", "func TestGetConcurrentAPIEndpoints(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tname string\n\t\tddURL, eventsDDURL, apiKey string\n\t\tadditionalEndpoints map[string][]string\n\t\tadditionalEventsEndpoints map[string][]string\n\t\texpectedEndpoints []apicfg.Endpoint\n\t\texpectedEventsEndpoints []apicfg.Endpoint\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\tapiKey: \"test\",\n\t\t\texpectedEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEndpoint),\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEventsEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEventsEndpoint),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set only process endpoint\",\n\t\t\tddURL: \"https://process.datadoghq.eu\",\n\t\t\tapiKey: \"test\",\n\t\t\texpectedEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(\"https://process.datadoghq.eu\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEventsEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEventsEndpoint),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set only process-events endpoint\",\n\t\t\teventsDDURL: \"https://process-events.datadoghq.eu\",\n\t\t\tapiKey: \"test\",\n\t\t\texpectedEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEndpoint),\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEventsEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(\"https://process-events.datadoghq.eu\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple eps\",\n\t\t\tapiKey: \"test\",\n\t\t\tadditionalEndpoints: map[string][]string{\n\t\t\t\t\"https://mock.datadoghq.com\": {\n\t\t\t\t\t\"key1\",\n\t\t\t\t\t\"key2\",\n\t\t\t\t},\n\t\t\t\t\"https://mock2.datadoghq.com\": {\n\t\t\t\t\t\"key3\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tadditionalEventsEndpoints: map[string][]string{\n\t\t\t\t\"https://mock-events.datadoghq.com\": {\n\t\t\t\t\t\"key2\",\n\t\t\t\t},\n\t\t\t\t\"https://mock2-events.datadoghq.com\": {\n\t\t\t\t\t\"key3\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEndpoint),\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key1\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key2\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock2.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key3\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEventsEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEventsEndpoint),\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock-events.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key2\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock2-events.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key3\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tcfg := config.Mock(t)\n\t\t\tcfg.Set(\"api_key\", tc.apiKey)\n\t\t\tif tc.ddURL != \"\" {\n\t\t\t\tcfg.Set(\"process_config.process_dd_url\", tc.ddURL)\n\t\t\t}\n\n\t\t\tif tc.eventsDDURL != \"\" {\n\t\t\t\tcfg.Set(\"process_config.events_dd_url\", tc.eventsDDURL)\n\t\t\t}\n\n\t\t\tif tc.additionalEndpoints != nil {\n\t\t\t\tcfg.Set(\"process_config.additional_endpoints\", tc.additionalEndpoints)\n\t\t\t}\n\n\t\t\tif tc.additionalEventsEndpoints != nil {\n\t\t\t\tcfg.Set(\"process_config.events_additional_endpoints\", tc.additionalEventsEndpoints)\n\t\t\t}\n\n\t\t\teps, err := endpoint.GetAPIEndpoints(cfg)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.ElementsMatch(t, tc.expectedEndpoints, eps)\n\n\t\t\teventsEps, err := endpoint.GetEventsAPIEndpoints(cfg)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.ElementsMatch(t, tc.expectedEventsEndpoints, eventsEps)\n\t\t})\n\t}\n}", "func (rm *ReplicationManager) watchControllers(resourceVersion *string) {\n\twatching, err := rm.kubeClient.ReplicationControllers(api.NamespaceAll).Watch(\n\t\tlabels.Everything(),\n\t\tlabels.Everything(),\n\t\t*resourceVersion,\n\t)\n\tif err != nil {\n\t\tutil.HandleError(fmt.Errorf(\"unable to watch: %v\", err))\n\t\ttime.Sleep(5 * time.Second)\n\t\treturn\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-rm.syncTime:\n\t\t\trm.synchronize()\n\t\tcase event, open := <-watching.ResultChan():\n\t\t\tif !open {\n\t\t\t\t// watchChannel has been closed, or something else went\n\t\t\t\t// wrong with our etcd watch call. Let the util.Forever()\n\t\t\t\t// that called us call us again.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif event.Type == watch.Error {\n\t\t\t\tutil.HandleError(fmt.Errorf(\"error from watch during sync: %v\", errors.FromObject(event.Object)))\n\t\t\t\t// Clear the resource version, this may cause us to skip some elements on the watch,\n\t\t\t\t// but we'll catch them on the synchronize() call, so it works out.\n\t\t\t\t*resourceVersion = \"\"\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tglog.V(4).Infof(\"Got watch: %#v\", event)\n\t\t\trc, ok := event.Object.(*api.ReplicationController)\n\t\t\tif !ok {\n\t\t\t\tif status, ok := event.Object.(*api.Status); ok {\n\t\t\t\t\tif status.Status == api.StatusFailure {\n\t\t\t\t\t\tglog.Errorf(\"failed to watch: %v\", status)\n\t\t\t\t\t\t// Clear resource version here, as above, this won't hurt consistency, but we\n\t\t\t\t\t\t// should consider introspecting more carefully here. (or make the apiserver smarter)\n\t\t\t\t\t\t// \"why not both?\"\n\t\t\t\t\t\t*resourceVersion = \"\"\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tutil.HandleError(fmt.Errorf(\"unexpected object: %#v\", event.Object))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// If we get disconnected, start where we left off.\n\t\t\t*resourceVersion = rc.ResourceVersion\n\t\t\t// Sync even if this is a deletion event, to ensure that we leave\n\t\t\t// it in the desired state.\n\t\t\tglog.V(4).Infof(\"About to sync from watch: %v\", rc.Name)\n\t\t\tif err := rm.syncHandler(*rc); err != nil {\n\t\t\t\tutil.HandleError(fmt.Errorf(\"unexpected sync error: %v\", err))\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *InstallerController) manageInstallationPods(ctx context.Context, operatorSpec *operatorv1.StaticPodOperatorSpec, originalOperatorStatus *operatorv1.StaticPodOperatorStatus) (bool, time.Duration, error) {\n\toperatorStatus := originalOperatorStatus.DeepCopy()\n\n\tif len(operatorStatus.NodeStatuses) == 0 {\n\t\treturn false, 0, nil\n\t}\n\n\t// start with node which is in worst state (instead of terminating healthy pods first)\n\tstartNode, nodeChoiceReason, err := nodeToStartRevisionWith(ctx, c.getStaticPodState, operatorStatus.NodeStatuses)\n\tif err != nil {\n\t\treturn true, 0, err\n\t}\n\n\t// determine the amount of time to delay before creating the next installer pod. We delay to avoid an LB outage (see godoc on minReadySeconds)\n\trequeueAfter := c.timeToWaitBeforeInstallingNextPod(ctx, operatorStatus.NodeStatuses)\n\tif requeueAfter > 0 {\n\t\treturn true, requeueAfter, nil\n\t}\n\n\tfor l := 0; l < len(operatorStatus.NodeStatuses); l++ {\n\t\ti := (startNode + l) % len(operatorStatus.NodeStatuses)\n\n\t\tvar currNodeState *operatorv1.NodeStatus\n\t\tvar prevNodeState *operatorv1.NodeStatus\n\t\tcurrNodeState = &operatorStatus.NodeStatuses[i]\n\t\tif l > 0 {\n\t\t\tprev := (startNode + l - 1) % len(operatorStatus.NodeStatuses)\n\t\t\tprevNodeState = &operatorStatus.NodeStatuses[prev]\n\t\t\tnodeChoiceReason = fmt.Sprintf(\"node %s is the next node in the line\", currNodeState.NodeName)\n\t\t}\n\n\t\t// if we are in a transition, check to see whether our installer pod completed\n\t\tif currNodeState.TargetRevision > currNodeState.CurrentRevision {\n\t\t\tif operatorStatus.LatestAvailableRevision > currNodeState.TargetRevision {\n\t\t\t\t// no backoff if new revision is pending\n\t\t\t} else {\n\t\t\t\tif currNodeState.LastFailedRevision == currNodeState.TargetRevision && currNodeState.LastFailedTime != nil && !currNodeState.LastFailedTime.IsZero() {\n\t\t\t\t\tvar delay time.Duration\n\t\t\t\t\tif currNodeState.LastFailedReason == nodeStatusOperandFailedFallbackReason {\n\t\t\t\t\t\tdelay = c.fallbackBackOff(currNodeState.LastFallbackCount)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdelay = c.installerBackOff(currNodeState.LastFailedCount)\n\t\t\t\t\t}\n\t\t\t\t\tearliestRetry := currNodeState.LastFailedTime.Add(delay)\n\t\t\t\t\tif !c.now().After(earliestRetry) {\n\t\t\t\t\t\tklog.V(4).Infof(\"Backing off node %s installer retry %d until %v\", currNodeState.NodeName, currNodeState.LastFailedCount+1, earliestRetry)\n\t\t\t\t\t\treturn true, earliestRetry.Sub(c.now()), nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err := c.ensureInstallerPod(ctx, operatorSpec, currNodeState); err != nil {\n\t\t\t\t\tc.eventRecorder.Warningf(\"InstallerPodFailed\", \"Failed to create installer pod for revision %d count %d on node %q: %v\",\n\t\t\t\t\t\tcurrNodeState.TargetRevision, currNodeState.LastFailedCount, currNodeState.NodeName, err)\n\t\t\t\t\t// if a newer revision is pending, continue, so we retry later with the latest available revision\n\t\t\t\t\tif !(operatorStatus.LatestAvailableRevision > currNodeState.TargetRevision) {\n\t\t\t\t\t\treturn true, 0, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnewCurrNodeState, _, reason, err := c.newNodeStateForInstallInProgress(ctx, currNodeState, operatorStatus.LatestAvailableRevision)\n\t\t\tif err != nil {\n\t\t\t\treturn true, 0, err\n\t\t\t}\n\t\t\tif newCurrNodeState.LastFailedReason == nodeStatusInstalledFailedReason && newCurrNodeState.LastFailedCount != currNodeState.LastFailedCount {\n\t\t\t\tklog.Infof(\"Will retry %q for revision %d for the %s time because %s\", currNodeState.NodeName, currNodeState.TargetRevision, nthTimeOr1st(newCurrNodeState.LastFailedCount), reason)\n\t\t\t}\n\t\t\tif newCurrNodeState.LastFailedReason == nodeStatusOperandFailedFallbackReason && newCurrNodeState.LastFallbackCount != currNodeState.LastFallbackCount {\n\t\t\t\tklog.Infof(\"Will fallback %q for revision %d to last-known-good revision for the %s time because %s\", currNodeState.NodeName, currNodeState.TargetRevision, nthTimeOr1st(newCurrNodeState.LastFallbackCount), reason)\n\t\t\t}\n\n\t\t\t// if we make a change to this status, we want to write it out to the API before we commence work on the next node.\n\t\t\t// it's an extra write/read, but it makes the state debuggable from outside this process\n\t\t\tif !equality.Semantic.DeepEqual(newCurrNodeState, currNodeState) {\n\t\t\t\tklog.Infof(\"%q moving to %v because %s\", currNodeState.NodeName, spew.Sdump(*newCurrNodeState), reason)\n\t\t\t\t_, updated, updateError := v1helpers.UpdateStaticPodStatus(ctx, c.operatorClient, setNodeStatusFn(newCurrNodeState), setAvailableProgressingNodeInstallerFailingConditions)\n\t\t\t\tif updateError != nil {\n\t\t\t\t\treturn false, 0, updateError\n\t\t\t\t} else if updated && currNodeState.CurrentRevision != newCurrNodeState.CurrentRevision {\n\t\t\t\t\tc.eventRecorder.Eventf(\"NodeCurrentRevisionChanged\", \"Updated node %q from revision %d to %d because %s\", currNodeState.NodeName,\n\t\t\t\t\t\tcurrNodeState.CurrentRevision, newCurrNodeState.CurrentRevision, reason)\n\t\t\t\t}\n\n\t\t\t\treturn false, 0, nil // no requeue because UpdateStaticPodStatus triggers an external event anyway\n\t\t\t}\n\n\t\t\tklog.V(2).Infof(\"%q is in transition to %d, but has not made progress because %s\", currNodeState.NodeName, currNodeState.TargetRevision, reasonWithBlame(reason))\n\t\t\treturn false, 0, nil\n\t\t}\n\n\t\t// here we are not in transition, i.e. there is no install pod running\n\n\t\trevisionToStart := c.getRevisionToStart(currNodeState, prevNodeState, operatorStatus)\n\t\tif revisionToStart == 0 {\n\t\t\tklog.V(4).Infof(\"%s, but node %s does not need update\", nodeChoiceReason, currNodeState.NodeName)\n\t\t\tcontinue\n\t\t}\n\n\t\tklog.Infof(\"%s and needs new revision %d\", nodeChoiceReason, revisionToStart)\n\n\t\tnewCurrNodeState := currNodeState.DeepCopy()\n\t\tnewCurrNodeState.TargetRevision = revisionToStart\n\n\t\t// if we make a change to this status, we want to write it out to the API before we commence work on the next node.\n\t\t// it's an extra write/read, but it makes the state debuggable from outside this process\n\t\tif !equality.Semantic.DeepEqual(newCurrNodeState, currNodeState) {\n\t\t\tklog.Infof(\"%q moving to %v\", currNodeState.NodeName, spew.Sdump(*newCurrNodeState))\n\t\t\tif _, updated, updateError := v1helpers.UpdateStaticPodStatus(ctx, c.operatorClient, setNodeStatusFn(newCurrNodeState), setAvailableProgressingNodeInstallerFailingConditions); updateError != nil {\n\t\t\t\treturn false, 0, updateError\n\t\t\t} else if updated && currNodeState.TargetRevision != newCurrNodeState.TargetRevision && newCurrNodeState.TargetRevision != 0 {\n\t\t\t\tc.eventRecorder.Eventf(\"NodeTargetRevisionChanged\", \"Updating node %q from revision %d to %d because %s\", currNodeState.NodeName,\n\t\t\t\t\tcurrNodeState.CurrentRevision, newCurrNodeState.TargetRevision, nodeChoiceReason)\n\t\t\t}\n\n\t\t\treturn false, 0, nil // no requeue because UpdateStaticPodStatus triggers an external event anyway\n\t\t}\n\t\tbreak\n\t}\n\n\treturn false, 0, nil\n}", "func SetupAddExtraControllerVersions(k kubernetes.Interface, namespace string) kubernetes.Interface {\n\tp := MockPod()\n\n\tdv1b1 := appsv1beta1.Deployment{\n\t\tSpec: appsv1beta1.DeploymentSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n\tif _, err := k.AppsV1beta1().Deployments(namespace).Create(&dv1b1); err != nil {\n\t\tpanic(err)\n\t}\n\n\tdv1b2 := appsv1beta2.Deployment{\n\t\tSpec: appsv1beta2.DeploymentSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n\tif _, err := k.AppsV1beta2().Deployments(namespace).Create(&dv1b2); err != nil {\n\t\tpanic(err)\n\t}\n\n\tssv1b1 := appsv1beta1.StatefulSet{\n\t\tSpec: appsv1beta1.StatefulSetSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n\tif _, err := k.AppsV1beta1().StatefulSets(namespace).Create(&ssv1b1); err != nil {\n\t\tpanic(err)\n\t}\n\n\tssv1b2 := appsv1beta2.StatefulSet{\n\t\tSpec: appsv1beta2.StatefulSetSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n\tif _, err := k.AppsV1beta2().StatefulSets(namespace).Create(&ssv1b2); err != nil {\n\t\tpanic(err)\n\t}\n\n\tdsv1b2 := appsv1beta2.DaemonSet{\n\t\tSpec: appsv1beta2.DaemonSetSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n\tif _, err := k.AppsV1beta2().DaemonSets(namespace).Create(&dsv1b2); err != nil {\n\t\tpanic(err)\n\t}\n\treturn k\n}", "func TestFrameworkFlagMetaReady(t *testing.T) {\n\tappName := \"framework_test_flagmetaready\"\n\t// launch testing etcd server\n\tm := etcdutil.MustNewMember(t, appName)\n\tm.Launch()\n\tdefer m.Terminate(t)\n\turl := fmt.Sprintf(\"http://%s\", m.ClientListeners[0].Addr().String())\n\n\t// launch controller to setup etcd layout\n\tctl := controller.New(appName, etcd.NewClient([]string{url}), 2)\n\tif err := ctl.InitEtcdLayout(); err != nil {\n\t\tt.Fatalf(\"initEtcdLayout failed: %v\", err)\n\t}\n\tdefer ctl.DestroyEtcdLayout()\n\n\tpDataChan := make(chan *tDataBundle, 1)\n\tcDataChan := make(chan *tDataBundle, 1)\n\n\t// simulate two tasks on two nodes -- 0 and 1\n\t// 0 is parent, 1 is child\n\tf0 := &framework{\n\t\tname: appName,\n\t\tetcdURLs: []string{url},\n\t\tln: createListener(t),\n\t}\n\tf1 := &framework{\n\t\tname: appName,\n\t\tetcdURLs: []string{url},\n\t\tln: createListener(t),\n\t}\n\n\tvar wg sync.WaitGroup\n\ttaskBuilder := &testableTaskBuilder{\n\t\tdataMap: nil,\n\t\tcDataChan: cDataChan,\n\t\tpDataChan: pDataChan,\n\t\tsetupLatch: &wg,\n\t}\n\tf0.SetTaskBuilder(taskBuilder)\n\tf0.SetTopology(example.NewTreeTopology(2, 2))\n\tf1.SetTaskBuilder(taskBuilder)\n\tf1.SetTopology(example.NewTreeTopology(2, 2))\n\n\ttaskBuilder.setupLatch.Add(2)\n\tgo f0.Start()\n\tgo f1.Start()\n\ttaskBuilder.setupLatch.Wait()\n\tif f0.GetTaskID() != 0 {\n\t\tf0, f1 = f1, f0\n\t}\n\n\tdefer f0.ShutdownJob()\n\n\ttests := []struct {\n\t\tcMeta string\n\t\tpMeta string\n\t}{\n\t\t{\"parent\", \"child\"},\n\t\t{\"ParamReady\", \"GradientReady\"},\n\t}\n\n\tfor i, tt := range tests {\n\t\t// 0: F#FlagChildMetaReady -> 1: T#ParentMetaReady\n\t\tf0.flagMetaToChild(tt.cMeta, 0)\n\t\t// from child(1)'s view\n\t\tdata := <-pDataChan\n\t\texpected := &tDataBundle{0, tt.cMeta, \"\", nil}\n\t\tif !reflect.DeepEqual(data, expected) {\n\t\t\tt.Errorf(\"#%d: data bundle want = %v, get = %v\", i, expected, data)\n\t\t}\n\n\t\t// 1: F#FlagParentMetaReady -> 0: T#ChildMetaReady\n\t\tf1.flagMetaToParent(tt.pMeta, 0)\n\t\t// from parent(0)'s view\n\t\tdata = <-cDataChan\n\t\texpected = &tDataBundle{1, tt.pMeta, \"\", nil}\n\t\tif !reflect.DeepEqual(data, expected) {\n\t\t\tt.Errorf(\"#%d: data bundle want = %v, get = %v\", i, expected, data)\n\t\t}\n\t}\n}", "func runMultisyncTests(t *testing.T, ctx context.Context, tests []controllerTest, storageClasses []*storage.StorageClass, defaultStorageClass string) {\n\tlogger := klog.FromContext(ctx)\n\trun := func(t *testing.T, test controllerTest) {\n\t\tlogger.V(4).Info(\"Starting multisync test\", \"testName\", test.name)\n\n\t\t// Initialize the controller\n\t\tclient := &fake.Clientset{}\n\t\tctrl, err := newTestController(ctx, client, nil, true)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %q construct persistent volume failed: %v\", test.name, err)\n\t\t}\n\n\t\t// Inject classes into controller via a custom lister.\n\t\tindexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})\n\t\tfor _, class := range storageClasses {\n\t\t\tindexer.Add(class)\n\t\t}\n\t\tctrl.classLister = storagelisters.NewStorageClassLister(indexer)\n\n\t\treactor := newVolumeReactor(ctx, client, ctrl, nil, nil, test.errors)\n\t\tfor _, claim := range test.initialClaims {\n\t\t\tctrl.claims.Add(claim)\n\t\t}\n\t\tfor _, volume := range test.initialVolumes {\n\t\t\tctrl.volumes.store.Add(volume)\n\t\t}\n\t\treactor.AddClaims(test.initialClaims)\n\t\treactor.AddVolumes(test.initialVolumes)\n\n\t\t// Run the tested function\n\t\terr = test.test(ctrl, reactor.VolumeReactor, test)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test %q failed: %v\", test.name, err)\n\t\t}\n\n\t\t// Simulate any \"changed\" events and \"periodical sync\" until we reach a\n\t\t// stable state.\n\t\tfirstSync := true\n\t\tcounter := 0\n\t\tfor {\n\t\t\tcounter++\n\t\t\tlogger.V(4).Info(\"Test\", \"testName\", test.name, \"iteration\", counter)\n\n\t\t\tif counter > 100 {\n\t\t\t\tt.Errorf(\"Test %q failed: too many iterations\", test.name)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Wait for all goroutines to finish\n\t\t\treactor.waitForIdle()\n\n\t\t\tobj := reactor.PopChange(ctx)\n\t\t\tif obj == nil {\n\t\t\t\t// Nothing was changed, should we exit?\n\t\t\t\tif firstSync || reactor.GetChangeCount() > 0 {\n\t\t\t\t\t// There were some changes after the last \"periodic sync\".\n\t\t\t\t\t// Simulate \"periodic sync\" of everything (until it produces\n\t\t\t\t\t// no changes).\n\t\t\t\t\tfirstSync = false\n\t\t\t\t\tlogger.V(4).Info(\"Test simulating periodical sync of all claims and volumes\", \"testName\", test.name)\n\t\t\t\t\treactor.SyncAll()\n\t\t\t\t} else {\n\t\t\t\t\t// Last sync did not produce any updates, the test reached\n\t\t\t\t\t// stable state -> finish.\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\t// waiting here cools down exponential backoff\n\t\t\ttime.Sleep(600 * time.Millisecond)\n\n\t\t\t// There were some changes, process them\n\t\t\tswitch obj.(type) {\n\t\t\tcase *v1.PersistentVolumeClaim:\n\t\t\t\tclaim := obj.(*v1.PersistentVolumeClaim)\n\t\t\t\t// Simulate \"claim updated\" event\n\t\t\t\tctrl.claims.Update(claim)\n\t\t\t\terr = ctrl.syncClaim(context.TODO(), claim)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == pvtesting.ErrVersionConflict {\n\t\t\t\t\t\t// Ignore version errors\n\t\t\t\t\t\tlogger.V(4).Info(\"Test intentionally ignores version error\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\tt.Errorf(\"Error calling syncClaim: %v\", err)\n\t\t\t\t\t\t// Finish the loop on the first error\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Process generated changes\n\t\t\t\tcontinue\n\t\t\tcase *v1.PersistentVolume:\n\t\t\t\tvolume := obj.(*v1.PersistentVolume)\n\t\t\t\t// Simulate \"volume updated\" event\n\t\t\t\tctrl.volumes.store.Update(volume)\n\t\t\t\terr = ctrl.syncVolume(context.TODO(), volume)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == pvtesting.ErrVersionConflict {\n\t\t\t\t\t\t// Ignore version errors\n\t\t\t\t\t\tlogger.V(4).Info(\"Test intentionally ignores version error\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\tt.Errorf(\"Error calling syncVolume: %v\", err)\n\t\t\t\t\t\t// Finish the loop on the first error\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Process generated changes\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tevaluateTestResults(ctx, ctrl, reactor.VolumeReactor, test, t)\n\t\tlogger.V(4).Info(\"Test finished after iterations\", \"testName\", test.name, \"iterations\", counter)\n\t}\n\n\tfor _, test := range tests {\n\t\ttest := test\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\trun(t, test)\n\t\t})\n\t}\n}", "func TestDevPortForwardDeletePod(t *testing.T) {\n\tMarkIntegrationTest(t, CanRunWithoutGcp)\n\ttests := []struct {\n\t\tdir string\n\t}{\n\t\t{dir: \"examples/microservices\"},\n\t\t{dir: \"examples/multi-config-microservices\"},\n\t}\n\tfor _, test := range tests {\n\t\t// pre-build images to avoid tripping the 1-minute timeout in getLocalPortFromPortForwardEvent()\n\t\tskaffold.Build().InDir(test.dir).RunOrFail(t)\n\n\t\tns, client := SetupNamespace(t)\n\n\t\trpcAddr := randomPort()\n\t\tskaffold.Dev(\"--port-forward\", \"--rpc-port\", rpcAddr).InDir(test.dir).InNs(ns.Name).RunBackground(t)\n\t\tclient.WaitForDeploymentsToStabilize(\"leeroy-app\")\n\n\t\t_, entries := apiEvents(t, rpcAddr)\n\n\t\taddress, localPort := getLocalPortFromPortForwardEvent(t, entries, \"leeroy-app\", \"service\", ns.Name)\n\t\tassertResponseFromPort(t, address, localPort, constants.LeeroyAppResponse)\n\n\t\t// now, delete all pods in this namespace.\n\t\tRun(t, \".\", \"kubectl\", \"delete\", \"pods\", \"--all\", \"-n\", ns.Name)\n\n\t\tassertResponseFromPort(t, address, localPort, constants.LeeroyAppResponse)\n\t}\n}", "func ChaosPodStatus(experimentsDetails *types.ExperimentDetails, clients environment.ClientSets) error {\n\n\tfor count := 0; count < (experimentsDetails.Duration / experimentsDetails.Delay); count++ {\n\n\t\tchaosEngine, err := clients.LitmusClient.ChaosEngines(experimentsDetails.ChaosNamespace).Get(experimentsDetails.EngineName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn errors.Errorf(\"fail to get the chaosengine %v err: %v\", experimentsDetails.EngineName, err)\n\t\t}\n\t\tif len(chaosEngine.Status.Experiments) == 0 {\n\t\t\ttime.Sleep(time.Duration(experimentsDetails.Delay) * time.Second)\n\t\t\tlog.Info(\"[Status]: Experiment initializing\")\n\t\t\tif count == ((experimentsDetails.Duration / experimentsDetails.Delay) - 1) {\n\t\t\t\treturn errors.Errorf(\"Experiment pod fail to initialise, due to %v\", err)\n\t\t\t}\n\n\t\t} else if len(chaosEngine.Status.Experiments[0].ExpPod) == 0 {\n\t\t\ttime.Sleep(time.Duration(experimentsDetails.Delay) * time.Second)\n\t\t\tif count == ((experimentsDetails.Duration / experimentsDetails.Delay) - 1) {\n\t\t\t\treturn errors.Errorf(\"Experiment pod fails to create, due to %v\", err)\n\t\t\t}\n\t\t} else if chaosEngine.Status.Experiments[0].Status != \"Running\" {\n\t\t\ttime.Sleep(time.Duration(experimentsDetails.Delay) * time.Second)\n\t\t\tlog.Infof(\"[Status]: Currently, the Chaos Pod is in %v state, Please Wait...\", chaosEngine.Status.Experiments[0].Status)\n\t\t\tif count == ((experimentsDetails.Duration / experimentsDetails.Delay) - 1) {\n\t\t\t\treturn errors.Errorf(\"Experiment pod fails to get in running state, due to %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tlog.Info(\"[Status]: Chaos pod initiated successfully\")\n\treturn nil\n}", "func TestServiceCreateWithMultipleContainers(t *testing.T) {\n\tif test.ServingFlags.DisableOptionalAPI {\n\t\tt.Skip(\"Multiple containers support is not required by Knative Serving API Specification\")\n\t}\n\tif !test.ServingFlags.EnableBetaFeatures {\n\t\tt.Skip()\n\t}\n\tt.Parallel()\n\tclients := test.Setup(t)\n\n\tnames := test.ResourceNames{\n\t\tService: test.ObjectNameForTest(t),\n\t\tImage: test.ServingContainer,\n\t\tSidecars: []string{\n\t\t\ttest.SidecarContainer,\n\t\t},\n\t}\n\n\t// Clean up on test failure or interrupt\n\ttest.EnsureTearDown(t, clients, &names)\n\tcontainers := []corev1.Container{{\n\t\tImage: pkgtest.ImagePath(names.Image),\n\t\tPorts: []corev1.ContainerPort{{\n\t\t\tContainerPort: 8881,\n\t\t}},\n\t}, {\n\t\tImage: pkgtest.ImagePath(names.Sidecars[0]),\n\t}}\n\n\t// Setup initial Service\n\tif _, err := v1test.CreateServiceReady(t, clients, &names, func(svc *v1.Service) {\n\t\tsvc.Spec.Template.Spec.Containers = containers\n\t}); err != nil {\n\t\tt.Fatalf(\"Failed to create initial Service %v: %v\", names.Service, err)\n\t}\n\n\t// Validate State after Creation\n\tif err := validateControlPlane(t, clients, names, \"1\" /*1 is the expected generation value*/); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif err := validateDataPlane(t, clients, names, test.MultiContainerResponse); err != nil {\n\t\tt.Error(err)\n\t}\n}" ]
[ "0.8165727", "0.80359614", "0.79608786", "0.5846746", "0.5815157", "0.5800607", "0.5719953", "0.55622447", "0.55490845", "0.55087394", "0.55010694", "0.5484525", "0.5433796", "0.5399612", "0.53902775", "0.53603613", "0.5314078", "0.53021586", "0.52998984", "0.52553374", "0.5234496", "0.52341104", "0.51682353", "0.514461", "0.51414704", "0.51267165", "0.5114701", "0.50759375", "0.5050211", "0.50471246", "0.50381887", "0.50329536", "0.500362", "0.4990736", "0.4979914", "0.49641868", "0.49480525", "0.4946543", "0.49372634", "0.49074292", "0.490263", "0.4901867", "0.4898448", "0.48831004", "0.48828962", "0.488163", "0.4876671", "0.48685402", "0.48486874", "0.48321512", "0.48219407", "0.4820718", "0.48184946", "0.48110706", "0.480729", "0.48004287", "0.47969425", "0.47917008", "0.47881517", "0.47854638", "0.47851896", "0.47836116", "0.4780199", "0.47764817", "0.4765915", "0.47632578", "0.47583282", "0.47495988", "0.47403494", "0.47396177", "0.47374162", "0.47293258", "0.4723519", "0.47147277", "0.47114336", "0.47090712", "0.4706003", "0.47010234", "0.46962607", "0.4691396", "0.46893394", "0.46865094", "0.46864063", "0.46858487", "0.46815282", "0.46812484", "0.4677864", "0.46731976", "0.4658944", "0.46509907", "0.46443397", "0.46411046", "0.4633852", "0.46325597", "0.46298867", "0.4623521", "0.46234474", "0.46212965", "0.46029004", "0.4602257" ]
0.8077532
1
TestConcurrentBuildPodControllers tests the lifecycle of a build pod when running multiple controllers.
func TestConcurrentBuildPodControllers(t *testing.T) { defer testutil.DumpEtcdOnFailure(t) // Start a master with multiple BuildPodControllers osClient, kClient := setupBuildControllerTest(controllerCount{BuildPodControllers: 5}, t) build.RunBuildPodControllerTest(t, osClient, kClient) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestConcurrentBuildControllersPodSync(t *testing.T) {\n\t// Start a master with multiple BuildControllers\n\tbuildClient, _, kClient, fn := setupBuildControllerTest(controllerCount{BuildControllers: 5}, t)\n\tdefer fn()\n\tbuild.RunBuildControllerPodSyncTest(t, buildClient, kClient)\n}", "func TestConcurrentBuildControllers(t *testing.T) {\n\tdefer testutil.DumpEtcdOnFailure(t)\n\t// Start a master with multiple BuildControllers\n\tosClient, kClient := setupBuildControllerTest(controllerCount{BuildControllers: 5}, t)\n\tbuild.RunBuildControllerTest(t, osClient, kClient)\n}", "func TestConcurrentBuildControllers(t *testing.T) {\n\t// Start a master with multiple BuildControllers\n\tbuildClient, _, kClient, fn := setupBuildControllerTest(controllerCount{BuildControllers: 5}, t)\n\tdefer fn()\n\tbuild.RunBuildControllerTest(t, buildClient, kClient)\n}", "func validateController(ctx context.Context, c clientset.Interface, containerImage string, replicas int, containername string, testname string, validator validatorFn, ns string) {\n\tcontainerImage = trimDockerRegistry(containerImage)\n\tgetPodsTemplate := \"--template={{range.items}}{{.metadata.name}} {{end}}\"\n\n\tgetContainerStateTemplate := fmt.Sprintf(`--template={{if (exists . \"status\" \"containerStatuses\")}}{{range .status.containerStatuses}}{{if (and (eq .name \"%s\") (exists . \"state\" \"running\"))}}true{{end}}{{end}}{{end}}`, containername)\n\n\tgetImageTemplate := fmt.Sprintf(`--template={{if (exists . \"spec\" \"containers\")}}{{range .spec.containers}}{{if eq .name \"%s\"}}{{.image}}{{end}}{{end}}{{end}}`, containername)\n\n\tginkgo.By(fmt.Sprintf(\"waiting for all containers in %s pods to come up.\", testname)) //testname should be selector\nwaitLoop:\n\tfor start := time.Now(); time.Since(start) < framework.PodStartTimeout && ctx.Err() == nil; time.Sleep(5 * time.Second) {\n\t\tgetPodsOutput := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"pods\", \"-o\", \"template\", getPodsTemplate, \"-l\", testname)\n\t\tpods := strings.Fields(getPodsOutput)\n\t\tif numPods := len(pods); numPods != replicas {\n\t\t\tginkgo.By(fmt.Sprintf(\"Replicas for %s: expected=%d actual=%d\", testname, replicas, numPods))\n\t\t\tcontinue\n\t\t}\n\t\tvar runningPods []string\n\t\tfor _, podID := range pods {\n\t\t\trunning := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"pods\", podID, \"-o\", \"template\", getContainerStateTemplate)\n\t\t\tif running != \"true\" {\n\t\t\t\tframework.Logf(\"%s is created but not running\", podID)\n\t\t\t\tcontinue waitLoop\n\t\t\t}\n\n\t\t\tcurrentImage := e2ekubectl.RunKubectlOrDie(ns, \"get\", \"pods\", podID, \"-o\", \"template\", getImageTemplate)\n\t\t\tcurrentImage = trimDockerRegistry(currentImage)\n\t\t\tif currentImage != containerImage {\n\t\t\t\tframework.Logf(\"%s is created but running wrong image; expected: %s, actual: %s\", podID, containerImage, currentImage)\n\t\t\t\tcontinue waitLoop\n\t\t\t}\n\n\t\t\t// Call the generic validator function here.\n\t\t\t// This might validate for example, that (1) getting a url works and (2) url is serving correct content.\n\t\t\tif err := validator(ctx, c, podID); err != nil {\n\t\t\t\tframework.Logf(\"%s is running right image but validator function failed: %v\", podID, err)\n\t\t\t\tcontinue waitLoop\n\t\t\t}\n\n\t\t\tframework.Logf(\"%s is verified up and running\", podID)\n\t\t\trunningPods = append(runningPods, podID)\n\t\t}\n\t\t// If we reach here, then all our checks passed.\n\t\tif len(runningPods) == replicas {\n\t\t\treturn\n\t\t}\n\t}\n\t// Reaching here means that one of more checks failed multiple times. Assuming its not a race condition, something is broken.\n\tframework.Failf(\"Timed out after %v seconds waiting for %s pods to reach valid state\", framework.PodStartTimeout.Seconds(), testname)\n}", "func TestController(t *testing.T) {\n\tctx, _ := rtesting.SetupFakeContext(t)\n\tctx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\n\t// Create reconcilers, start controller.\n\tresults := test.NewResultsClient(t)\n\n\ttrctrl := taskrun.NewController(ctx, results)\n\tprctrl := pipelinerun.NewController(ctx, results)\n\tgo controller.StartAll(ctx, trctrl, prctrl)\n\n\t// Start informers - this notifies the controller of new events.\n\tgo taskruninformer.Get(ctx).Informer().Run(ctx.Done())\n\tgo pipelineruninformer.Get(ctx).Informer().Run(ctx.Done())\n\n\tpipeline := fakepipelineclient.Get(ctx)\n\tt.Run(\"taskrun\", func(t *testing.T) {\n\t\ttr := &v1beta1.TaskRun{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: \"tekton.dev/v1beta1\",\n\t\t\t\tKind: \"TaskRun\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"taskrun\",\n\t\t\t\tNamespace: \"ns\",\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\"demo\": \"demo\",\n\t\t\t\t\t// This TaskRun belongs to a PipelineRun, so the record should\n\t\t\t\t\t// be associated with the PipelineRun result.\n\t\t\t\t\t\"tekton.dev/pipelineRun\": \"pr\",\n\t\t\t\t},\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{{\n\t\t\t\t\tAPIVersion: \"tekton.dev/v1beta1\",\n\t\t\t\t\tKind: \"PipelineRun\",\n\t\t\t\t\tUID: \"pr-id\",\n\t\t\t\t}},\n\t\t\t\tUID: \"tr-id\",\n\t\t\t},\n\t\t}\n\n\t\t// The following is a hack to make the fake clients play nice with\n\t\t// each other. While the controller uses the typed informer that uses\n\t\t// the fake pipeline client to receive events, the controller uses the\n\t\t// fake dynamic client to fetch and update objects during reconcile.\n\t\t// These fake clients store objects independently, so we create the\n\t\t// object in each client to make sure the data is populated in both\n\t\t// places.\n\t\tif _, err := pipeline.TektonV1beta1().TaskRuns(tr.GetNamespace()).Create(tr); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdata, err := runtime.DefaultUnstructuredConverter.ToUnstructured(tr)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ToUnstructured: %v\", err)\n\t\t}\n\t\t_, err = dynamicinject.Get(ctx).Resource(apis.KindToResource(tr.GroupVersionKind())).Namespace(tr.GetNamespace()).Create(&unstructured.Unstructured{Object: data}, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Create: %v\", err)\n\t\t}\n\n\t\twait(ctx, t, tr, \"ns/results/pr-id\")\n\t})\n\n\tt.Run(\"pipelinerun\", func(t *testing.T) {\n\t\tpr := &v1beta1.PipelineRun{\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tAPIVersion: \"tekton.dev/v1beta1\",\n\t\t\t\tKind: \"PipelineRun\",\n\t\t\t},\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"pr\",\n\t\t\t\tNamespace: \"ns\",\n\t\t\t\tAnnotations: map[string]string{\"demo\": \"demo\"},\n\t\t\t\tUID: \"pr-id\",\n\t\t\t},\n\t\t}\n\n\t\t// Same create hack as taskrun (see above).\n\t\tif _, err := pipeline.TektonV1beta1().PipelineRuns(pr.GetNamespace()).Create(pr); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdata, err := runtime.DefaultUnstructuredConverter.ToUnstructured(pr)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ToUnstructured: %v\", err)\n\t\t}\n\t\t_, err = dynamicinject.Get(ctx).Resource(apis.KindToResource(pr.GroupVersionKind())).Namespace(pr.GetNamespace()).Create(&unstructured.Unstructured{Object: data}, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Create: %v\", err)\n\t\t}\n\n\t\twait(ctx, t, pr, \"ns/results/pr-id\")\n\t})\n}", "func TestBuildControllerNoBuildManifestsFirst(t *testing.T) {\n\tf := newTestFixture(t)\n\tdefer f.TearDown()\n\n\tmanifests := make([]model.Manifest, 10)\n\tfor i := 0; i < 10; i++ {\n\t\tsync := model.Sync{LocalPath: f.Path(), ContainerPath: \"/go\"}\n\t\tmanifests[i] = f.newManifest(fmt.Sprintf(\"built%d\", i+1), []model.Sync{sync})\n\t}\n\n\tfor _, i := range []int{3, 7, 8} {\n\t\tmanifests[i] = assembleK8sManifest(\n\t\t\tmodel.Manifest{\n\t\t\t\tName: model.ManifestName(fmt.Sprintf(\"unbuilt%d\", i+1))},\n\t\t\tmodel.K8sTarget{YAML: \"fake-yaml\"})\n\t}\n\tf.Start(manifests, true)\n\n\tvar observedBuildOrder []string\n\tfor i := 0; i < len(manifests); i++ {\n\t\tcall := f.nextCall()\n\t\tobservedBuildOrder = append(observedBuildOrder, call.k8s().Name.String())\n\t}\n\n\t// throwing a bunch of elements at it to increase confidence we maintain order between built and unbuilt\n\t// this might miss bugs since we might just get these elements back in the right order via luck\n\texpectedBuildOrder := []string{\n\t\t\"unbuilt4\",\n\t\t\"unbuilt8\",\n\t\t\"unbuilt9\",\n\t\t\"built1\",\n\t\t\"built2\",\n\t\t\"built3\",\n\t\t\"built5\",\n\t\t\"built6\",\n\t\t\"built7\",\n\t\t\"built10\",\n\t}\n\tassert.Equal(t, expectedBuildOrder, observedBuildOrder)\n}", "func (m *MockPodControllerFactory) Build(mgr mc_manager.AsyncManager, clusterName string) (controller1.PodController, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", mgr, clusterName)\n\tret0, _ := ret[0].(controller1.PodController)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func SetupAddControllers(k kubernetes.Interface, namespace string) kubernetes.Interface {\n\td1 := MockDeploy()\n\tif _, err := k.AppsV1().Deployments(namespace).Create(&d1); err != nil {\n\t\tpanic(err)\n\t}\n\n\ts1 := MockStatefulSet()\n\tif _, err := k.AppsV1().StatefulSets(namespace).Create(&s1); err != nil {\n\t\tpanic(err)\n\t}\n\n\tds1 := MockDaemonSet()\n\tif _, err := k.AppsV1().DaemonSets(namespace).Create(&ds1); err != nil {\n\t\tpanic(err)\n\t}\n\n\tj1 := MockJob()\n\tif _, err := k.BatchV1().Jobs(namespace).Create(&j1); err != nil {\n\t\tpanic(err)\n\t}\n\n\tcj1 := MockCronJob()\n\tif _, err := k.BatchV1beta1().CronJobs(namespace).Create(&cj1); err != nil {\n\t\tpanic(err)\n\t}\n\n\trc1 := MockReplicationController()\n\tif _, err := k.CoreV1().ReplicationControllers(namespace).Create(&rc1); err != nil {\n\t\tpanic(err)\n\t}\n\n\tp1 := MockNakedPod()\n\tif _, err := k.CoreV1().Pods(namespace).Create(&p1); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn k\n}", "func runSyncTests(t *testing.T, ctx context.Context, tests []controllerTest, storageClasses []*storage.StorageClass, pods []*v1.Pod) {\n\tdoit := func(t *testing.T, test controllerTest) {\n\t\t// Initialize the controller\n\t\tclient := &fake.Clientset{}\n\t\tctrl, err := newTestController(ctx, client, nil, true)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %q construct persistent volume failed: %v\", test.name, err)\n\t\t}\n\t\treactor := newVolumeReactor(ctx, client, ctrl, nil, nil, test.errors)\n\t\tfor _, claim := range test.initialClaims {\n\t\t\tif metav1.HasAnnotation(claim.ObjectMeta, annSkipLocalStore) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tctrl.claims.Add(claim)\n\t\t}\n\t\tfor _, volume := range test.initialVolumes {\n\t\t\tif metav1.HasAnnotation(volume.ObjectMeta, annSkipLocalStore) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tctrl.volumes.store.Add(volume)\n\t\t}\n\t\treactor.AddClaims(test.initialClaims)\n\t\treactor.AddVolumes(test.initialVolumes)\n\n\t\t// Inject classes into controller via a custom lister.\n\t\tindexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})\n\t\tfor _, class := range storageClasses {\n\t\t\tindexer.Add(class)\n\t\t}\n\t\tctrl.classLister = storagelisters.NewStorageClassLister(indexer)\n\n\t\tpodIndexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})\n\t\tfor _, pod := range pods {\n\t\t\tpodIndexer.Add(pod)\n\t\t\tctrl.podIndexer.Add(pod)\n\t\t}\n\t\tctrl.podLister = corelisters.NewPodLister(podIndexer)\n\n\t\t// Run the tested functions\n\t\terr = test.test(ctrl, reactor.VolumeReactor, test)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test %q failed: %v\", test.name, err)\n\t\t}\n\n\t\t// Wait for the target state\n\t\terr = reactor.waitTest(test)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test %q failed: %v\", test.name, err)\n\t\t}\n\n\t\tevaluateTestResults(ctx, ctrl, reactor.VolumeReactor, test, t)\n\t}\n\n\tfor _, test := range tests {\n\t\ttest := test\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tdoit(t, test)\n\t\t})\n\t}\n}", "func TestControllerInitPrepare_Parallel(t *testing.T) {\n\t_ = testlib.IntegrationEnv(t)\n\n\tt.Run(\"with parent context that is never canceled\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\t// the nil params should never be used in this case\n\t\tbuildControllers := controllerinit.Prepare(nil, nil, buildBrokenInformer(t))\n\n\t\tstart := time.Now()\n\t\trunControllers, err := buildControllers(context.Background()) // we expect this to not block forever even with a context.Background()\n\t\tdelta := time.Since(start)\n\n\t\trequire.EqualError(t, err,\n\t\t\t\"failed to sync informers of k8s.io/client-go/informers.sharedInformerFactory: \"+\n\t\t\t\t\"[k8s.io/api/core/v1.Namespace k8s.io/api/core/v1.Node]\")\n\t\trequire.Nil(t, runControllers)\n\n\t\trequire.InDelta(t, time.Minute, delta, float64(30*time.Second))\n\t})\n\n\tt.Run(\"with parent context that is canceled early\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\t// the nil params should never be used in this case\n\t\tbuildControllers := controllerinit.Prepare(nil, nil, buildBrokenInformer(t))\n\n\t\t// we expect this to exit sooner because the parent context is shorter\n\t\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\t\tt.Cleanup(cancel)\n\n\t\tstart := time.Now()\n\t\trunControllers, err := buildControllers(ctx)\n\t\tdelta := time.Since(start)\n\n\t\trequire.EqualError(t, err,\n\t\t\t\"failed to sync informers of k8s.io/client-go/informers.sharedInformerFactory: \"+\n\t\t\t\t\"[k8s.io/api/core/v1.Namespace k8s.io/api/core/v1.Node]\")\n\t\trequire.Nil(t, runControllers)\n\n\t\trequire.InDelta(t, 10*time.Second, delta, float64(15*time.Second))\n\t})\n}", "func OperatorRunningTest(bundle *apimanifests.Bundle) scapiv1alpha3.TestStatus {\n\tr := scapiv1alpha3.TestResult{}\n\tr.Name = OperatorRunningTestName\n\tr.State = scapiv1alpha3.PassState\n\tr.Errors = make([]string, 0)\n\tr.Suggestions = make([]string, 0)\n\n\t//\ttime.Sleep(20 * time.Second)\n\n\t//clientset, config, err := util.GetKubeClient()\n\tclientset, _, err := util.GetKubeClient()\n\tif err != nil {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, \"unable to connect to kube\")\n\t\treturn wrapResult(r)\n\t}\n\n\tns := \"tekton-pipelines\"\n\n\tnamespaces, err := clientset.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, fmt.Sprintf(\"error getting namespaces %s\", err.Error()))\n\t\treturn wrapResult(r)\n\t}\n\n\tfor i := 0; i < len(namespaces.Items); i++ {\n\t\tn := namespaces.Items[i]\n\t\tif n.Name == \"openshift-pipelines\" {\n\t\t\tns = \"openshift-pipelines\"\n\t\t\tbreak\n\t\t}\n\t\tif n.Name == \"tekton-pipelines\" {\n\t\t\tns = \"tekton-pipelines\"\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvar pods *corev1.PodList\n\tvar p corev1.Pod\n\n\t// look for a pod with this label\n\t//app=tekton-pipelines-controller\n\tselector := \"app=tekton-pipelines-controller\"\n\tlistOpts := metav1.ListOptions{LabelSelector: selector}\n\tpods, err = clientset.CoreV1().Pods(ns).List(context.TODO(), listOpts)\n\tif err != nil {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, fmt.Sprintf(\"error getting pods %s\", err.Error()))\n\t\treturn wrapResult(r)\n\t}\n\tif len(pods.Items) == 0 {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, \"tekton-pipelines-controller pod not found\")\n\t\treturn wrapResult(r)\n\t}\n\tp = pods.Items[0]\n\tif p.Status.Phase != corev1.PodRunning {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, \"tekton-pipelines-controller pod not running\")\n\t\treturn wrapResult(r)\n\t}\n\n\t// look for a pod with this label\n\t//app=tekton-pipelines-webhook\n\tselector = \"app=tekton-pipelines-webhook\"\n\tlistOpts = metav1.ListOptions{LabelSelector: selector}\n\tpods, err = clientset.CoreV1().Pods(ns).List(context.TODO(), listOpts)\n\tif err != nil {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, fmt.Sprintf(\"error getting pods %s\", err.Error()))\n\t\treturn wrapResult(r)\n\t}\n\tif len(pods.Items) == 0 {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, \"tekton-pipelines-webhook pod not found\")\n\t\treturn wrapResult(r)\n\t}\n\n\tp = pods.Items[0]\n\n\tif p.Status.Phase != corev1.PodRunning {\n\t\tr.State = scapiv1alpha3.FailState\n\t\tr.Errors = append(r.Errors, \"tekton-pipelines-webhook pod not running\")\n\t\treturn wrapResult(r)\n\t}\n\n\treturn wrapResult(r)\n}", "func updatePodTests() []*SerialTestCase {\n\tsequence1Tests := []*SerialTestCase{\n\t\t{\n\t\t\tDescription: \"Sequence 1: Pod A create --> Policy create --> Pod A cleanup --> Pod B create\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// old labels (not yet garbage collected)\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t\t// new labels\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tDescription: \"Sequence 1: Policy create --> Pod A create --> Pod A cleanup --> Pod B create\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// old labels (not yet garbage collected)\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t\t// new labels\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tDescription: \"Sequence 1: Policy create --> Pod A create --> Pod A cleanup --> Pod B create (skip first apply DP)\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// old labels (not yet garbage collected)\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t\t// new labels\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tDescription: \"Sequence 1: Policy create --> Pod A create --> Pod A cleanup --> Pod B create (skip first two apply DP)\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// old labels (not yet garbage collected)\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t\t// new labels\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tsequence2Tests := []*SerialTestCase{\n\t\t{\n\t\t\tDescription: \"Sequence 2 with Calico network\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: windowsCalicoDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// IP temporarily associated with IPSets of both pod A and pod B\n\t\t\t\t\t// Pod A sets\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set, ip1),\n\t\t\t\t\t// Pod B sets\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-baseazurewireserver\",\n\t\t\t\t\t\t\tAction: \"Block\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tPriority: 200,\n\t\t\t\t\t\t\tRemoteAddresses: \"168.63.129.16/32\",\n\t\t\t\t\t\t\tRemotePorts: \"80\",\n\t\t\t\t\t\t\tProtocols: \"6\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-baseallowinswitch\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tPriority: 65499,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-baseallowoutswitch\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tPriority: 65499,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-baseallowinhost\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tPriority: 0,\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\t// RuleType is unsupported in FakeEndpointPolicy\n\t\t\t\t\t\t\t// RuleType: \"Host\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-baseallowouthost\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tPriority: 0,\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\t// RuleType is unsupported in FakeEndpointPolicy\n\t\t\t\t\t\t\t// RuleType: \"Host\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tDescription: \"Sequence 2: Policy create --> Pod A Create --> Pod B create\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// IP temporarily associated with IPSets of both pod A and pod B\n\t\t\t\t\t// Pod A sets\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set, ip1),\n\t\t\t\t\t// Pod B sets\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tDescription: \"Sequence 2: Policy create --> Pod A Create --> Pod B create --> Pod A cleanup\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// old labels (not yet garbage collected)\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t\t// new labels\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// skipping this test. See PR #1856\n\t\t\tDescription: \"Sequence 2: Policy create --> Pod A Create --> Pod B create (skip first ApplyDP())\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// IP temporarily associated with IPSets of both pod A and pod B\n\t\t\t\t\t// Pod A sets\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set, ip1),\n\t\t\t\t\t// Pod B sets\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// skipping this test. See PR #1856\n\t\t\tDescription: \"Sequence 2: Policy create --> Pod A Create --> Pod B create --> Pod A cleanup (skip first two ApplyDP())\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tCreatePod(\"x\", \"b\", ip1, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\t// old labels (not yet garbage collected)\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t\t// new labels\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\totherTests := []*SerialTestCase{\n\t\t{\n\t\t\tDescription: \"ignore Pod update if added then deleted before ApplyDP()\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet),\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// doesn't really enforce behavior in DP, but one could look at logs to make sure we don't make a reset ACL SysCall into HNS\n\t\t\tDescription: \"ignore Pod delete for deleted endpoint\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t\tDeleteEndpoint(endpoint1),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet),\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: nil,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// doesn't really enforce behavior in DP, but one could look at logs to make sure we don't make a reset ACL SysCall into HNS\n\t\t\tDescription: \"ignore Pod delete for deleted endpoint (skip first ApplyDP())\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tDeleteEndpoint(endpoint1),\n\t\t\t\tDeletePod(\"x\", \"a\", ip1, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet),\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: nil,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t// doesn't really enforce behavior in DP, but one could look at logs to make sure we don't make an add ACL SysCall into HNS\"\n\t\t\tDescription: \"ignore Pod update when there's no corresponding endpoint\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBaseOnK1V1()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tDeleteEndpoint(endpoint1),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: nil,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tDescription: \"two endpoints, one with policy, one without\",\n\t\t\tActions: []*Action{\n\t\t\t\tFinishBootupPhase(),\n\t\t\t\tUpdatePolicy(policyXBase2OnK2V2()),\n\t\t\t\tCreatePod(\"x\", \"a\", ip1, thisNode, map[string]string{\"k1\": \"v1\"}),\n\t\t\t\tCreateEndpoint(endpoint2, ip2),\n\t\t\t\tCreatePod(\"x\", \"b\", ip2, thisNode, map[string]string{\"k2\": \"v2\"}),\n\t\t\t\tApplyDP(),\n\t\t\t},\n\t\t\tTestCaseMetadata: &TestCaseMetadata{\n\t\t\t\tTags: []Tag{\n\t\t\t\t\tpodCrudTag,\n\t\t\t\t\tnetpolCrudTag,\n\t\t\t\t},\n\t\t\t\tDpCfg: defaultWindowsDPCfg,\n\t\t\t\tInitialEndpoints: []*hcn.HostComputeEndpoint{\n\t\t\t\t\tdptestutils.Endpoint(endpoint1, ip1),\n\t\t\t\t},\n\t\t\t\tExpectedSetPolicies: []*hcn.SetPolicySetting{\n\t\t\t\t\tdptestutils.SetPolicy(emptySet),\n\t\t\t\t\tdptestutils.SetPolicy(allNamespaces, emptySet.GetHashedName(), nsXSet.GetHashedName()),\n\t\t\t\t\tdptestutils.SetPolicy(nsXSet, ip1, ip2),\n\t\t\t\t\tdptestutils.SetPolicy(podK1Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK1V1Set, ip1),\n\t\t\t\t\tdptestutils.SetPolicy(podK2Set, ip2),\n\t\t\t\t\tdptestutils.SetPolicy(podK2V2Set, ip2),\n\t\t\t\t},\n\t\t\t\tExpectedEnpdointACLs: map[string][]*hnswrapper.FakeEndpointPolicy{\n\t\t\t\t\tendpoint1: {},\n\t\t\t\t\tendpoint2: {\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tProtocols: \"\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"Out\",\n\t\t\t\t\t\t\tLocalAddresses: \"\",\n\t\t\t\t\t\t\tRemoteAddresses: \"\",\n\t\t\t\t\t\t\tLocalPorts: \"\",\n\t\t\t\t\t\t\tRemotePorts: \"\",\n\t\t\t\t\t\t\tPriority: 222,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tID: \"azure-acl-x-base2\",\n\t\t\t\t\t\t\tAction: \"Allow\",\n\t\t\t\t\t\t\tDirection: \"In\",\n\t\t\t\t\t\t\tRemoteAddresses: testNodeIP,\n\t\t\t\t\t\t\tPriority: 201,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tallTests := sequence1Tests\n\tallTests = append(allTests, sequence2Tests...)\n\t// allTests = append(allTests, podAssignmentSequence3Tests()...)\n\t// make golint happy\n\t_ = podAssignmentSequence3Tests()\n\tallTests = append(allTests, otherTests...)\n\treturn allTests\n}", "func TestDevPortForwardDeletePod(t *testing.T) {\n\tMarkIntegrationTest(t, CanRunWithoutGcp)\n\ttests := []struct {\n\t\tdir string\n\t}{\n\t\t{dir: \"examples/microservices\"},\n\t\t{dir: \"examples/multi-config-microservices\"},\n\t}\n\tfor _, test := range tests {\n\t\t// pre-build images to avoid tripping the 1-minute timeout in getLocalPortFromPortForwardEvent()\n\t\tskaffold.Build().InDir(test.dir).RunOrFail(t)\n\n\t\tns, client := SetupNamespace(t)\n\n\t\trpcAddr := randomPort()\n\t\tskaffold.Dev(\"--port-forward\", \"--rpc-port\", rpcAddr).InDir(test.dir).InNs(ns.Name).RunBackground(t)\n\t\tclient.WaitForDeploymentsToStabilize(\"leeroy-app\")\n\n\t\t_, entries := apiEvents(t, rpcAddr)\n\n\t\taddress, localPort := getLocalPortFromPortForwardEvent(t, entries, \"leeroy-app\", \"service\", ns.Name)\n\t\tassertResponseFromPort(t, address, localPort, constants.LeeroyAppResponse)\n\n\t\t// now, delete all pods in this namespace.\n\t\tRun(t, \".\", \"kubectl\", \"delete\", \"pods\", \"--all\", \"-n\", ns.Name)\n\n\t\tassertResponseFromPort(t, address, localPort, constants.LeeroyAppResponse)\n\t}\n}", "func StartControllers(s *options.MCMServer,\n\tcontrolCoreKubeconfig *rest.Config,\n\ttargetCoreKubeconfig *rest.Config,\n\tcontrolMachineClientBuilder machinecontroller.ClientBuilder,\n\tcontrolCoreClientBuilder corecontroller.ClientBuilder,\n\ttargetCoreClientBuilder corecontroller.ClientBuilder,\n\trecorder record.EventRecorder,\n\tstop <-chan struct{}) error {\n\n\tklog.V(5).Info(\"Getting available resources\")\n\tavailableResources, err := getAvailableResources(controlCoreClientBuilder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontrolMachineClient := controlMachineClientBuilder.ClientOrDie(controllerManagerAgentName).MachineV1alpha1()\n\n\tcontrolCoreKubeconfig = rest.AddUserAgent(controlCoreKubeconfig, controllerManagerAgentName)\n\tcontrolCoreClient, err := kubernetes.NewForConfig(controlCoreKubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\n\ttargetCoreKubeconfig = rest.AddUserAgent(targetCoreKubeconfig, controllerManagerAgentName)\n\ttargetCoreClient, err := kubernetes.NewForConfig(targetCoreKubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\n\tif availableResources[machineGVR] || availableResources[machineSetGVR] || availableResources[machineDeploymentGVR] {\n\t\tklog.V(5).Infof(\"Creating shared informers; resync interval: %v\", s.MinResyncPeriod)\n\n\t\tcontrolMachineInformerFactory := machineinformers.NewFilteredSharedInformerFactory(\n\t\t\tcontrolMachineClientBuilder.ClientOrDie(\"control-machine-shared-informers\"),\n\t\t\ts.MinResyncPeriod.Duration,\n\t\t\ts.Namespace,\n\t\t\tnil,\n\t\t)\n\n\t\tcontrolCoreInformerFactory := coreinformers.NewFilteredSharedInformerFactory(\n\t\t\tcontrolCoreClientBuilder.ClientOrDie(\"control-core-shared-informers\"),\n\t\t\ts.MinResyncPeriod.Duration,\n\t\t\ts.Namespace,\n\t\t\tnil,\n\t\t)\n\n\t\ttargetCoreInformerFactory := coreinformers.NewSharedInformerFactory(\n\t\t\ttargetCoreClientBuilder.ClientOrDie(\"target-core-shared-informers\"),\n\t\t\ts.MinResyncPeriod.Duration,\n\t\t)\n\n\t\t// All shared informers are v1alpha1 API level\n\t\tmachineSharedInformers := controlMachineInformerFactory.Machine().V1alpha1()\n\n\t\tklog.V(5).Infof(\"Creating controllers...\")\n\t\tmcmcontroller, err := mcmcontroller.NewController(\n\t\t\ts.Namespace,\n\t\t\tcontrolMachineClient,\n\t\t\tcontrolCoreClient,\n\t\t\ttargetCoreClient,\n\t\t\ttargetCoreInformerFactory.Core().V1().PersistentVolumeClaims(),\n\t\t\ttargetCoreInformerFactory.Core().V1().PersistentVolumes(),\n\t\t\tcontrolCoreInformerFactory.Core().V1().Secrets(),\n\t\t\ttargetCoreInformerFactory.Core().V1().Nodes(),\n\t\t\tmachineSharedInformers.OpenStackMachineClasses(),\n\t\t\tmachineSharedInformers.AWSMachineClasses(),\n\t\t\tmachineSharedInformers.AzureMachineClasses(),\n\t\t\tmachineSharedInformers.GCPMachineClasses(),\n\t\t\tmachineSharedInformers.AlicloudMachineClasses(),\n\t\t\tmachineSharedInformers.PacketMachineClasses(),\n\t\t\tmachineSharedInformers.Machines(),\n\t\t\tmachineSharedInformers.MachineSets(),\n\t\t\tmachineSharedInformers.MachineDeployments(),\n\t\t\trecorder,\n\t\t\ts.SafetyOptions,\n\t\t\ts.NodeConditions,\n\t\t\ts.BootstrapTokenAuthExtraGroups,\n\t\t\ts.DeleteMigratedMachineClass,\n\t\t\ts.AutoscalerScaleDownAnnotationDuringRollout,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.V(1).Info(\"Starting shared informers\")\n\n\t\tcontrolMachineInformerFactory.Start(stop)\n\t\tcontrolCoreInformerFactory.Start(stop)\n\t\ttargetCoreInformerFactory.Start(stop)\n\n\t\tklog.V(5).Info(\"Running controller\")\n\t\tgo mcmcontroller.Run(int(s.ConcurrentNodeSyncs), stop)\n\n\t} else {\n\t\treturn fmt.Errorf(\"unable to start machine controller: API GroupVersion %q or %q or %q is not available; \\nFound: %#v\", machineGVR, machineSetGVR, machineDeploymentGVR, availableResources)\n\t}\n\n\tselect {}\n}", "func TestConcurrentAccessToRelatedVolumes(ctx context.Context, f *framework.Framework, cs clientset.Interface, ns string,\n\tnode e2epod.NodeSelection, pvcs []*v1.PersistentVolumeClaim, expectedContent string) {\n\n\tvar pods []*v1.Pod\n\n\t// Create each pod with pvc\n\tfor i := range pvcs {\n\t\tindex := i + 1\n\t\tginkgo.By(fmt.Sprintf(\"Creating pod%d with a volume on %+v\", index, node))\n\t\tpodConfig := e2epod.Config{\n\t\t\tNS: ns,\n\t\t\tPVCs: []*v1.PersistentVolumeClaim{pvcs[i]},\n\t\t\tSeLinuxLabel: e2epod.GetLinuxLabel(),\n\t\t\tNodeSelection: node,\n\t\t\tPVCsReadOnly: false,\n\t\t\tImageID: e2epod.GetTestImageID(imageutils.JessieDnsutils),\n\t\t}\n\t\tpod, err := e2epod.CreateSecPodWithNodeSelection(ctx, cs, &podConfig, f.Timeouts.PodStart)\n\t\tdefer func() {\n\t\t\tframework.ExpectNoError(e2epod.DeletePodWithWait(ctx, cs, pod))\n\t\t}()\n\t\tframework.ExpectNoError(err)\n\t\tpods = append(pods, pod)\n\t\tactualNodeName := pod.Spec.NodeName\n\n\t\t// Always run the subsequent pods on the same node.\n\t\te2epod.SetAffinity(&node, actualNodeName)\n\t}\n\n\tfor i, pvc := range pvcs {\n\t\tvar commands []string\n\n\t\tif *pvc.Spec.VolumeMode == v1.PersistentVolumeBlock {\n\t\t\tfileName := \"/mnt/volume1\"\n\t\t\tcommands = e2evolume.GenerateReadBlockCmd(fileName, len(expectedContent))\n\t\t\t// Check that all pods have the same content\n\t\t\tindex := i + 1\n\t\t\tginkgo.By(fmt.Sprintf(\"Checking if the volume in pod%d has expected initial content\", index))\n\t\t\t_, err := e2eoutput.LookForStringInPodExec(pods[i].Namespace, pods[i].Name, commands, expectedContent, time.Minute)\n\t\t\tframework.ExpectNoError(err, \"failed: finding the contents of the block volume %s.\", fileName)\n\t\t} else {\n\t\t\tfileName := \"/mnt/volume1/index.html\"\n\t\t\tcommands = e2evolume.GenerateReadFileCmd(fileName)\n\t\t\t// Check that all pods have the same content\n\t\t\tindex := i + 1\n\t\t\tginkgo.By(fmt.Sprintf(\"Checking if the volume in pod%d has expected initial content\", index))\n\t\t\t_, err := e2eoutput.LookForStringInPodExec(pods[i].Namespace, pods[i].Name, commands, expectedContent, time.Minute)\n\t\t\tframework.ExpectNoError(err, \"failed: finding the contents of the mounted file %s.\", fileName)\n\t\t}\n\t}\n}", "func TestControllerHandleEvents(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\taddServices []*corev1.Service\n\t\tupdateServices []string\n\t\tdelServices []string\n\t\texpAddedServices []string\n\t\texpDeletedServices []string\n\t}{\n\t\t{\n\t\t\tname: \"If a controller is watching services it should react to the service change events.\",\n\t\t\taddServices: []*corev1.Service{\n\t\t\t\t{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"svc1\"},\n\t\t\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\t\t\tType: \"ClusterIP\",\n\t\t\t\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t\t\t\tcorev1.ServicePort{Name: \"port1\", Port: 8080},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"svc2\"},\n\t\t\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\t\t\tType: \"ClusterIP\",\n\t\t\t\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t\t\t\tcorev1.ServicePort{Name: \"port1\", Port: 8080},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tupdateServices: []string{\"svc1\"},\n\t\t\tdelServices: []string{\"svc1\", \"svc2\"},\n\t\t\texpAddedServices: []string{\"svc1\", \"svc2\", \"svc1\"},\n\t\t\texpDeletedServices: []string{\"svc1\", \"svc2\"},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\trequire := require.New(t)\n\t\t\tassert := assert.New(t)\n\t\t\tresync := 30 * time.Second\n\t\t\tstopC := make(chan struct{})\n\t\t\tvar gotAddedServices []string\n\t\t\tvar gotDeletedServices []string\n\n\t\t\t// Create the kubernetes client.\n\t\t\tk8scli, _, _, err := cli.GetK8sClients(\"\")\n\n\t\t\trequire.NoError(err, \"kubernetes client is required\")\n\n\t\t\t// Prepare the environment on the cluster.\n\t\t\tprep := prepare.New(k8scli, t)\n\t\t\tprep.SetUp()\n\t\t\tdefer prep.TearDown()\n\n\t\t\t// Create the reitrever.\n\t\t\trt := &retrieve.Resource{\n\t\t\t\tListerWatcher: cache.NewListWatchFromClient(k8scli.CoreV1().RESTClient(), \"services\", prep.Namespace().Name, fields.Everything()),\n\t\t\t\tObject: &corev1.Service{},\n\t\t\t}\n\n\t\t\t// Call times are the number of times the handler should be called before sending the termination signal.\n\t\t\tstopCallTimes := len(test.addServices) + len(test.updateServices) + len(test.delServices)\n\t\t\tcalledTimes := 0\n\t\t\tvar mx sync.Mutex\n\n\t\t\t// Create the handler.\n\t\t\thl := &handler.HandlerFunc{\n\t\t\t\tAddFunc: func(_ context.Context, obj runtime.Object) error {\n\t\t\t\t\tmx.Lock()\n\t\t\t\t\tcalledTimes++\n\t\t\t\t\tmx.Unlock()\n\n\t\t\t\t\tsvc := obj.(*corev1.Service)\n\t\t\t\t\tgotAddedServices = append(gotAddedServices, svc.Name)\n\t\t\t\t\tif calledTimes >= stopCallTimes {\n\t\t\t\t\t\tclose(stopC)\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t},\n\t\t\t\tDeleteFunc: func(_ context.Context, id string) error {\n\t\t\t\t\tmx.Lock()\n\t\t\t\t\tcalledTimes++\n\t\t\t\t\tmx.Unlock()\n\n\t\t\t\t\t// Ignore namespace.\n\t\t\t\t\tid = strings.Split(id, \"/\")[1]\n\t\t\t\t\tgotDeletedServices = append(gotDeletedServices, id)\n\t\t\t\t\tif calledTimes >= stopCallTimes {\n\t\t\t\t\t\tclose(stopC)\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t},\n\t\t\t}\n\n\t\t\t// Create a Pod controller.\n\t\t\tctrl := controller.NewSequential(resync, hl, rt, nil, log.Dummy)\n\t\t\trequire.NotNil(ctrl, \"controller is required\")\n\t\t\tgo ctrl.Run(stopC)\n\n\t\t\t// Create the required services.\n\t\t\tfor _, svc := range test.addServices {\n\t\t\t\t_, err := k8scli.CoreV1().Services(prep.Namespace().Name).Create(svc)\n\t\t\t\tassert.NoError(err)\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t}\n\n\t\t\tfor _, svc := range test.updateServices {\n\t\t\t\torigSvc, err := k8scli.CoreV1().Services(prep.Namespace().Name).Get(svc, metav1.GetOptions{})\n\t\t\t\tif assert.NoError(err) {\n\t\t\t\t\t// Change something\n\t\t\t\t\torigSvc.Spec.Ports = append(origSvc.Spec.Ports, corev1.ServicePort{Name: \"updateport\", Port: 9876})\n\t\t\t\t\t_, err := k8scli.CoreV1().Services(prep.Namespace().Name).Update(origSvc)\n\t\t\t\t\tassert.NoError(err)\n\t\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Delete the required services.\n\t\t\tfor _, svc := range test.delServices {\n\t\t\t\terr := k8scli.CoreV1().Services(prep.Namespace().Name).Delete(svc, &metav1.DeleteOptions{})\n\t\t\t\tassert.NoError(err)\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t}\n\n\t\t\t// Wait until we have finished.\n\t\t\tselect {\n\t\t\t// Timeout.\n\t\t\tcase <-time.After(20 * time.Second):\n\t\t\t// Finished.\n\t\t\tcase <-stopC:\n\t\t\t}\n\n\t\t\t// Check.\n\t\t\tassert.Equal(test.expAddedServices, gotAddedServices)\n\t\t\tassert.Equal(test.expDeletedServices, gotDeletedServices)\n\t\t})\n\t}\n}", "func TestController(t *testing.T) {\n\tfakeKubeClient, catalogClient, fakeBrokerCatalog, _, _, testController, _, stopCh := newTestController(t)\n\tdefer close(stopCh)\n\n\tt.Log(fakeKubeClient, catalogClient, fakeBrokerCatalog, testController, stopCh)\n\n\tfakeBrokerCatalog.RetCatalog = &brokerapi.Catalog{\n\t\tServices: []*brokerapi.Service{\n\t\t\t{\n\t\t\t\tName: \"test-service\",\n\t\t\t\tID: \"12345\",\n\t\t\t\tDescription: \"a test service\",\n\t\t\t\tPlans: []brokerapi.ServicePlan{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"test-plan\",\n\t\t\t\t\t\tFree: true,\n\t\t\t\t\t\tID: \"34567\",\n\t\t\t\t\t\tDescription: \"a test plan\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tname := \"test-name\"\n\tbroker := &v1alpha1.Broker{\n\t\tObjectMeta: v1.ObjectMeta{Name: name},\n\t\tSpec: v1alpha1.BrokerSpec{\n\t\t\tURL: \"https://example.com\",\n\t\t},\n\t}\n\tbrokerClient := catalogClient.Servicecatalog().Brokers()\n\n\tbrokerServer, err := brokerClient.Create(broker)\n\tif nil != err {\n\t\tt.Fatalf(\"error creating the broker %q (%q)\", broker, err)\n\t}\n\n\tif err := wait.PollImmediate(500*time.Millisecond, wait.ForeverTestTimeout,\n\t\tfunc() (bool, error) {\n\t\t\tbrokerServer, err = brokerClient.Get(name)\n\t\t\tif nil != err {\n\t\t\t\treturn false,\n\t\t\t\t\tfmt.Errorf(\"error getting broker %s (%s)\",\n\t\t\t\t\t\tname, err)\n\t\t\t} else if len(brokerServer.Status.Conditions) > 0 {\n\t\t\t\tt.Log(brokerServer)\n\t\t\t\treturn true, nil\n\t\t\t} else {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t},\n\t); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// check\n\tserviceClassClient := catalogClient.Servicecatalog().ServiceClasses()\n\t_, err = serviceClassClient.Get(\"test-service\")\n\tif nil != err {\n\t\tt.Fatal(\"could not find the test service\", err)\n\t}\n\n\t// cleanup our broker\n\terr = brokerClient.Delete(name, &v1.DeleteOptions{})\n\tif nil != err {\n\t\tt.Fatalf(\"broker should be deleted (%s)\", err)\n\t}\n\n\t// uncomment if/when deleting a broker deletes the associated service\n\t// if class, err := serviceClassClient.Get(\"test-service\"); nil == err {\n\t// \tt.Fatal(\"found the test service that should have been deleted\", err, class)\n\t// }\n}", "func getControllerPods(clientSet kubernetes.Interface, namespace string) (*corev1.PodList, error) {\n\tlabelSelector := metav1.LabelSelector{MatchLabels: map[string]string{constants.AppLabel: constants.OSMControllerName}}\n\tpodClient := clientSet.CoreV1().Pods(namespace)\n\tlistOptions := metav1.ListOptions{\n\t\tLabelSelector: labels.Set(labelSelector.MatchLabels).String(),\n\t}\n\treturn podClient.List(context.TODO(), metav1.ListOptions{LabelSelector: listOptions.LabelSelector})\n}", "func startServerAndControllers(t *testing.T) (\n\t*kubefake.Clientset,\n\twatch.Interface,\n\tclustopclientset.Interface,\n\tcapiclientset.Interface,\n\t*capifakeclientset.Clientset,\n\tfunc()) {\n\n\t// create a fake kube client\n\tfakePtr := clientgotesting.Fake{}\n\tscheme := runtime.NewScheme()\n\tcodecs := serializer.NewCodecFactory(scheme)\n\tmetav1.AddToGroupVersion(scheme, schema.GroupVersion{Version: \"v1\"})\n\tkubefake.AddToScheme(scheme)\n\tobjectTracker := clientgotesting.NewObjectTracker(scheme, codecs.UniversalDecoder())\n\tkubeWatch := watch.NewRaceFreeFake()\n\t// Add a reactor for sending watch events when a job is modified\n\tobjectReaction := clientgotesting.ObjectReaction(objectTracker)\n\tfakePtr.AddReactor(\"*\", \"jobs\", func(action clientgotesting.Action) (bool, runtime.Object, error) {\n\t\tvar deletedObj runtime.Object\n\t\tif action, ok := action.(clientgotesting.DeleteActionImpl); ok {\n\t\t\tdeletedObj, _ = objectTracker.Get(action.GetResource(), action.GetNamespace(), action.GetName())\n\t\t}\n\t\thandled, obj, err := objectReaction(action)\n\t\tswitch action.(type) {\n\t\tcase clientgotesting.CreateActionImpl:\n\t\t\tkubeWatch.Add(obj)\n\t\tcase clientgotesting.UpdateActionImpl:\n\t\t\tkubeWatch.Modify(obj)\n\t\tcase clientgotesting.DeleteActionImpl:\n\t\t\tif deletedObj != nil {\n\t\t\t\tkubeWatch.Delete(deletedObj)\n\t\t\t}\n\t\t}\n\t\treturn handled, obj, err\n\t})\n\tfakePtr.AddWatchReactor(\"*\", clientgotesting.DefaultWatchReactor(kubeWatch, nil))\n\t// Create actual fake kube client\n\tfakeKubeClient := &kubefake.Clientset{Fake: fakePtr}\n\n\t// start the cluster-operator api server\n\tapiServerClientConfig, shutdownServer := servertesting.StartTestServerOrDie(t)\n\n\t// create a cluster-operator client\n\tclustopClient, err := clustopclientset.NewForConfig(apiServerClientConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\t// create a cluster-api client\n\tcapiClient, err := capiclientset.NewForConfig(apiServerClientConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\tfakeCAPIClient := &capifakeclientset.Clientset{}\n\n\t// create informers\n\tkubeInformerFactory := kubeinformers.NewSharedInformerFactory(fakeKubeClient, 10*time.Second)\n\tbatchSharedInformers := kubeInformerFactory.Batch().V1()\n\tclustopInformerFactory := clustopinformers.NewSharedInformerFactory(clustopClient, 10*time.Second)\n\tcapiInformerFactory := capiinformers.NewSharedInformerFactory(capiClient, 10*time.Second)\n\tcapiSharedInformers := capiInformerFactory.Cluster().V1alpha1()\n\n\t// create controllers\n\tstopCh := make(chan struct{})\n\tt.Log(\"controller start\")\n\t// Note that controllers must be created prior to starting the informers.\n\t// Otherwise, the controllers will not get the initial sync from the\n\t// informer and will time out waiting to sync.\n\trunControllers := []func(){\n\t\t// infra\n\t\tfunc() func() {\n\t\t\tcontroller := infracontroller.NewController(\n\t\t\t\tcapiSharedInformers.Clusters(),\n\t\t\t\tbatchSharedInformers.Jobs(),\n\t\t\t\tfakeKubeClient,\n\t\t\t\tclustopClient,\n\t\t\t\tcapiClient,\n\t\t\t)\n\t\t\treturn func() { controller.Run(1, stopCh) }\n\t\t}(),\n\t\t// master\n\t\tfunc() func() {\n\t\t\tcontroller := mastercontroller.NewController(\n\t\t\t\tcapiSharedInformers.Clusters(),\n\t\t\t\tcapiSharedInformers.MachineSets(),\n\t\t\t\tbatchSharedInformers.Jobs(),\n\t\t\t\tfakeKubeClient,\n\t\t\t\tclustopClient,\n\t\t\t\tcapiClient,\n\t\t\t)\n\t\t\treturn func() { controller.Run(1, stopCh) }\n\t\t}(),\n\t\t// components\n\t\tfunc() func() {\n\t\t\tcontroller := componentscontroller.NewController(\n\t\t\t\tcapiSharedInformers.Clusters(),\n\t\t\t\tcapiSharedInformers.MachineSets(),\n\t\t\t\tbatchSharedInformers.Jobs(),\n\t\t\t\tfakeKubeClient,\n\t\t\t\tclustopClient,\n\t\t\t\tcapiClient,\n\t\t\t)\n\t\t\treturn func() { controller.Run(1, stopCh) }\n\t\t}(),\n\t\t// nodeconfig\n\t\tfunc() func() {\n\t\t\tcontroller := nodeconfigcontroller.NewController(\n\t\t\t\tcapiSharedInformers.Clusters(),\n\t\t\t\tcapiSharedInformers.MachineSets(),\n\t\t\t\tbatchSharedInformers.Jobs(),\n\t\t\t\tfakeKubeClient,\n\t\t\t\tclustopClient,\n\t\t\t\tcapiClient,\n\t\t\t)\n\t\t\treturn func() { controller.Run(1, stopCh) }\n\t\t}(),\n\t\t// deployclusterapi\n\t\tfunc() func() {\n\t\t\tcontroller := deployclusterapicontroller.NewController(\n\t\t\t\tcapiSharedInformers.Clusters(),\n\t\t\t\tcapiSharedInformers.MachineSets(),\n\t\t\t\tbatchSharedInformers.Jobs(),\n\t\t\t\tfakeKubeClient,\n\t\t\t\tclustopClient,\n\t\t\t\tcapiClient,\n\t\t\t)\n\t\t\treturn func() { controller.Run(1, stopCh) }\n\t\t}(),\n\t\t// awselb\n\t\tfunc() func() {\n\t\t\tcontroller := awselb.NewController(\n\t\t\t\tcapiSharedInformers.Machines(),\n\t\t\t\tfakeKubeClient,\n\t\t\t\tclustopClient,\n\t\t\t\tcapiClient,\n\t\t\t)\n\t\t\treturn func() { controller.Run(1, stopCh) }\n\t\t}(),\n\t}\n\tvar wg sync.WaitGroup\n\twg.Add(len(runControllers))\n\tfor _, run := range runControllers {\n\t\tgo func(r func()) {\n\t\t\tdefer wg.Done()\n\t\t\tr()\n\t\t}(run)\n\t}\n\n\tt.Log(\"informers start\")\n\tkubeInformerFactory.Start(stopCh)\n\tclustopInformerFactory.Start(stopCh)\n\tcapiInformerFactory.Start(stopCh)\n\n\tshutdown := func() {\n\t\t// Shut down controller\n\t\tclose(stopCh)\n\t\t// Wait for all controller to stop\n\t\twg.Wait()\n\t\t// Shut down api server\n\t\tshutdownServer()\n\t}\n\n\treturn fakeKubeClient, kubeWatch, clustopClient, capiClient, fakeCAPIClient, shutdown\n}", "func runControllersAndInformers(t *testing.T, rm *replicaset.ReplicaSetController, dc *deployment.DeploymentController, informers informers.SharedInformerFactory) func() {\n\tctx, cancelFn := context.WithCancel(context.Background())\n\tinformers.Start(ctx.Done())\n\tgo rm.Run(ctx, 5)\n\tgo dc.Run(ctx, 5)\n\treturn cancelFn\n}", "func SetupAddExtraControllerVersions(k kubernetes.Interface, namespace string) kubernetes.Interface {\n\tp := MockPod()\n\n\tdv1b1 := appsv1beta1.Deployment{\n\t\tSpec: appsv1beta1.DeploymentSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n\tif _, err := k.AppsV1beta1().Deployments(namespace).Create(&dv1b1); err != nil {\n\t\tpanic(err)\n\t}\n\n\tdv1b2 := appsv1beta2.Deployment{\n\t\tSpec: appsv1beta2.DeploymentSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n\tif _, err := k.AppsV1beta2().Deployments(namespace).Create(&dv1b2); err != nil {\n\t\tpanic(err)\n\t}\n\n\tssv1b1 := appsv1beta1.StatefulSet{\n\t\tSpec: appsv1beta1.StatefulSetSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n\tif _, err := k.AppsV1beta1().StatefulSets(namespace).Create(&ssv1b1); err != nil {\n\t\tpanic(err)\n\t}\n\n\tssv1b2 := appsv1beta2.StatefulSet{\n\t\tSpec: appsv1beta2.StatefulSetSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n\tif _, err := k.AppsV1beta2().StatefulSets(namespace).Create(&ssv1b2); err != nil {\n\t\tpanic(err)\n\t}\n\n\tdsv1b2 := appsv1beta2.DaemonSet{\n\t\tSpec: appsv1beta2.DaemonSetSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{Spec: p.Spec},\n\t\t},\n\t}\n\tif _, err := k.AppsV1beta2().DaemonSets(namespace).Create(&dsv1b2); err != nil {\n\t\tpanic(err)\n\t}\n\treturn k\n}", "func ecsPodTests() map[string]func(ctx context.Context, t *testing.T, pc cocoa.ECSPodCreator, c *ECSClient, smc *SecretsManagerClient) {\n\tmakeSecretEnvVar := func(t *testing.T) *cocoa.EnvironmentVariable {\n\t\treturn cocoa.NewEnvironmentVariable().\n\t\t\tSetName(t.Name()).\n\t\t\tSetSecretOptions(*cocoa.NewSecretOptions().\n\t\t\t\tSetName(t.Name()).\n\t\t\t\tSetValue(utility.RandomString()).\n\t\t\t\tSetOwned(true))\n\t}\n\tmakeContainerDef := func(t *testing.T) *cocoa.ECSContainerDefinition {\n\t\treturn cocoa.NewECSContainerDefinition().\n\t\t\tSetImage(\"image\").\n\t\t\tSetMemoryMB(128).\n\t\t\tSetCPU(128).\n\t\t\tSetName(\"container\")\n\t}\n\n\tmakePodCreationOpts := func(t *testing.T) *cocoa.ECSPodCreationOptions {\n\t\treturn cocoa.NewECSPodCreationOptions().\n\t\t\tSetName(testutil.NewTaskDefinitionFamily(t.Name())).\n\t\t\tSetMemoryMB(128).\n\t\t\tSetCPU(128).\n\t\t\tSetTaskRole(testutil.TaskRole()).\n\t\t\tSetExecutionRole(testutil.ExecutionRole()).\n\t\t\tSetExecutionOptions(*cocoa.NewECSPodExecutionOptions().\n\t\t\t\tSetCluster(testutil.ECSClusterName()))\n\t}\n\n\tcheckPodDeleted := func(ctx context.Context, t *testing.T, p cocoa.ECSPod, c cocoa.ECSClient, smc cocoa.SecretsManagerClient, opts cocoa.ECSPodCreationOptions) {\n\t\tstat := p.StatusInfo()\n\t\tassert.Equal(t, cocoa.StatusDeleted, stat.Status)\n\n\t\tres := p.Resources()\n\n\t\tdescribeTaskDef, err := c.DescribeTaskDefinition(ctx, &awsECS.DescribeTaskDefinitionInput{\n\t\t\tTaskDefinition: res.TaskDefinition.ID,\n\t\t})\n\t\trequire.NoError(t, err)\n\t\trequire.NotZero(t, describeTaskDef.TaskDefinition)\n\t\tassert.Equal(t, utility.FromStringPtr(opts.Name), utility.FromStringPtr(describeTaskDef.TaskDefinition.Family))\n\n\t\tdescribeTasks, err := c.DescribeTasks(ctx, &awsECS.DescribeTasksInput{\n\t\t\tCluster: res.Cluster,\n\t\t\tTasks: []*string{res.TaskID},\n\t\t})\n\t\trequire.NoError(t, err)\n\t\tassert.Empty(t, describeTasks.Failures)\n\t\trequire.Len(t, describeTasks.Tasks, 1)\n\t\tassert.Equal(t, awsECS.DesiredStatusStopped, utility.FromStringPtr(describeTasks.Tasks[0].LastStatus))\n\n\t\tfor _, containerRes := range res.Containers {\n\t\t\tfor _, s := range containerRes.Secrets {\n\t\t\t\t_, err := smc.DescribeSecret(ctx, &secretsmanager.DescribeSecretInput{\n\t\t\t\t\tSecretId: s.Name,\n\t\t\t\t})\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\t_, err = smc.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{\n\t\t\t\t\tSecretId: s.Name,\n\t\t\t\t})\n\t\t\t\tassert.Error(t, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn map[string]func(ctx context.Context, t *testing.T, pc cocoa.ECSPodCreator, c *ECSClient, smc *SecretsManagerClient){\n\t\t\"StopIsIdempotentWhenItFails\": func(ctx context.Context, t *testing.T, pc cocoa.ECSPodCreator, c *ECSClient, smc *SecretsManagerClient) {\n\t\t\topts := makePodCreationOpts(t).AddContainerDefinitions(*makeContainerDef(t))\n\t\t\tp, err := pc.CreatePod(ctx, opts)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tc.StopTaskError = errors.New(\"fake error\")\n\n\t\t\trequire.Error(t, p.Stop(ctx))\n\n\t\t\tstat := p.StatusInfo()\n\t\t\tassert.Equal(t, cocoa.StatusStarting, stat.Status)\n\n\t\t\tc.StopTaskError = nil\n\n\t\t\trequire.NoError(t, p.Stop(ctx))\n\t\t\tstat = p.StatusInfo()\n\t\t\tassert.Equal(t, cocoa.StatusStopped, stat.Status)\n\t\t},\n\t\t\"DeleteIsIdempotentWhenStoppingTaskFails\": func(ctx context.Context, t *testing.T, pc cocoa.ECSPodCreator, c *ECSClient, smc *SecretsManagerClient) {\n\t\t\topts := makePodCreationOpts(t).AddContainerDefinitions(\n\t\t\t\t*makeContainerDef(t).AddEnvironmentVariables(\n\t\t\t\t\t*makeSecretEnvVar(t),\n\t\t\t\t),\n\t\t\t)\n\t\t\tp, err := pc.CreatePod(ctx, opts)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tc.StopTaskError = errors.New(\"fake error\")\n\n\t\t\trequire.Error(t, p.Delete(ctx))\n\n\t\t\tstat := p.StatusInfo()\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, cocoa.StatusStarting, stat.Status)\n\n\t\t\tc.StopTaskError = nil\n\n\t\t\trequire.NoError(t, p.Delete(ctx))\n\n\t\t\tcheckPodDeleted(ctx, t, p, c, smc, *opts)\n\t\t},\n\t\t\"DeleteIsIdempotentWhenDeregisteringTaskDefinitionFails\": func(ctx context.Context, t *testing.T, pc cocoa.ECSPodCreator, c *ECSClient, smc *SecretsManagerClient) {\n\t\t\topts := makePodCreationOpts(t).AddContainerDefinitions(\n\t\t\t\t*makeContainerDef(t).AddEnvironmentVariables(\n\t\t\t\t\t*makeSecretEnvVar(t),\n\t\t\t\t),\n\t\t\t)\n\t\t\tp, err := pc.CreatePod(ctx, opts)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tc.DeregisterTaskDefinitionError = errors.New(\"fake error\")\n\n\t\t\trequire.Error(t, p.Delete(ctx))\n\n\t\t\tstat := p.StatusInfo()\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, cocoa.StatusStopped, stat.Status)\n\n\t\t\tc.DeregisterTaskDefinitionError = nil\n\n\t\t\trequire.NoError(t, p.Delete(ctx))\n\n\t\t\tcheckPodDeleted(ctx, t, p, c, smc, *opts)\n\t\t},\n\t\t\"DeleteIsIdempotentWhenDeletingSecretsFails\": func(ctx context.Context, t *testing.T, pc cocoa.ECSPodCreator, c *ECSClient, smc *SecretsManagerClient) {\n\t\t\topts := makePodCreationOpts(t).AddContainerDefinitions(\n\t\t\t\t*makeContainerDef(t).AddEnvironmentVariables(\n\t\t\t\t\t*makeSecretEnvVar(t),\n\t\t\t\t),\n\t\t\t)\n\t\t\tp, err := pc.CreatePod(ctx, opts)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tsmc.DeleteSecretError = errors.New(\"fake error\")\n\n\t\t\trequire.Error(t, p.Delete(ctx))\n\n\t\t\tstat := p.StatusInfo()\n\t\t\tassert.Equal(t, cocoa.StatusStopped, stat.Status)\n\n\t\t\tsmc.DeleteSecretError = nil\n\n\t\t\trequire.NoError(t, p.Delete(ctx))\n\n\t\t\tcheckPodDeleted(ctx, t, p, c, smc, *opts)\n\t\t},\n\t}\n}", "func CreatePods(f *framework.Framework, appName string, ns string, labels map[string]string, spec v1.PodSpec, maxCount int, tuning *TuningSetType) {\n\tfor i := 0; i < maxCount; i++ {\n\t\tframework.Logf(\"%v/%v : Creating pod\", i+1, maxCount)\n\t\t// Retry on pod creation failure\n\t\tfor retryCount := 0; retryCount < maxRetries; retryCount++ {\n\t\t\t_, err := f.ClientSet.Core().Pods(ns).Create(&v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: fmt.Sprintf(appName+\"-pod-%v\", i),\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: spec,\n\t\t\t})\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tframework.ExpectNoError(err)\n\t\t}\n\t\tif tuning != nil {\n\t\t\t// If a rate limit has been defined we wait for N ms between creation\n\t\t\tif tuning.Pods.RateLimit.Delay != 0 {\n\t\t\t\tframework.Logf(\"Sleeping %d ms between podcreation.\", tuning.Pods.RateLimit.Delay)\n\t\t\t\ttime.Sleep(tuning.Pods.RateLimit.Delay * time.Millisecond)\n\t\t\t}\n\t\t\t// If a stepping tuningset has been defined in the config, we wait for the step of pods to be created, and pause\n\t\t\tif tuning.Pods.Stepping.StepSize != 0 && (i+1)%tuning.Pods.Stepping.StepSize == 0 {\n\t\t\t\tverifyRunning := f.NewClusterVerification(\n\t\t\t\t\t&v1.Namespace{\n\t\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\t\tName: ns,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tStatus: v1.NamespaceStatus{},\n\t\t\t\t\t},\n\t\t\t\t\tframework.PodStateVerification{\n\t\t\t\t\t\tSelectors: labels,\n\t\t\t\t\t\tValidPhases: []v1.PodPhase{v1.PodRunning},\n\t\t\t\t\t},\n\t\t\t\t)\n\n\t\t\t\tpods, err := verifyRunning.WaitFor(i+1, tuning.Pods.Stepping.Timeout*time.Second)\n\t\t\t\tif err != nil {\n\t\t\t\t\tframework.Failf(\"Error in wait... %v\", err)\n\t\t\t\t} else if len(pods) < i+1 {\n\t\t\t\t\tframework.Failf(\"Only got %v out of %v\", len(pods), i+1)\n\t\t\t\t}\n\n\t\t\t\tframework.Logf(\"We have created %d pods and are now sleeping for %d seconds\", i+1, tuning.Pods.Stepping.Pause)\n\t\t\t\ttime.Sleep(tuning.Pods.Stepping.Pause * time.Second)\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *MockDeploymentControllerFactory) Build(mgr mc_manager.AsyncManager, clusterName string) (controller0.DeploymentController, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", mgr, clusterName)\n\tret0, _ := ret[0].(controller0.DeploymentController)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestTriggerController(t *testing.T) {\n\tconfig, stopFn := framework.RunControlPlane(t)\n\tdefer stopFn()\n\n\tctx, cancel := context.WithTimeout(context.TODO(), time.Second*20)\n\tdefer cancel()\n\n\tfakeClock := &fakeclock.FakeClock{}\n\t// Build, instantiate and run the trigger controller.\n\tkubeClient, factory, cmCl, cmFactory := framework.NewClients(t, config)\n\n\tnamespace := \"testns\"\n\n\t// Create Namespace\n\tns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}\n\t_, err := kubeClient.CoreV1().Namespaces().Create(context.TODO(), ns, metav1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tctrl, queue, mustSync := trigger.NewController(logf.Log, cmCl, factory, cmFactory, framework.NewEventRecorder(t), fakeClock, policies.NewTriggerPolicyChain(fakeClock))\n\tc := controllerpkg.NewController(\n\t\tcontext.Background(),\n\t\t\"trigger_test\",\n\t\tmetrics.New(logf.Log),\n\t\tctrl.ProcessItem,\n\t\tmustSync,\n\t\tnil,\n\t\tqueue,\n\t)\n\tstopController := framework.StartInformersAndController(t, factory, cmFactory, c)\n\tdefer stopController()\n\n\t// Create a Certificate resource and wait for it to have the 'Issuing' condition.\n\tcert, err := cmCl.CertmanagerV1().Certificates(namespace).Create(ctx, &cmapi.Certificate{\n\t\tObjectMeta: metav1.ObjectMeta{Name: \"testcrt\", Namespace: \"testns\"},\n\t\tSpec: cmapi.CertificateSpec{\n\t\t\tSecretName: \"example\",\n\t\t\tCommonName: \"example.com\",\n\t\t\tIssuerRef: cmmeta.ObjectReference{Name: \"testissuer\"}, // doesn't need to exist\n\t\t},\n\t}, metav1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = wait.Poll(time.Millisecond*100, time.Second*5, func() (done bool, err error) {\n\t\tc, err := cmCl.CertmanagerV1().Certificates(cert.Namespace).Get(ctx, cert.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tt.Logf(\"Failed to fetch Certificate resource, retrying: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tif !apiutil.CertificateHasCondition(c, cmapi.CertificateCondition{\n\t\t\tType: cmapi.CertificateConditionIssuing,\n\t\t\tStatus: cmmeta.ConditionTrue,\n\t\t}) {\n\t\t\tt.Logf(\"Certificate does not have expected condition, got=%#v\", apiutil.GetCertificateCondition(c, cmapi.CertificateConditionIssuing))\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func TestBatch(t *testing.T) {\n\tpre := config.Presubmit{\n\t\tName: \"pr-some-job\",\n\t\tAgent: \"jenkins\",\n\t\tContext: \"Some Job Context\",\n\t}\n\tfc := &fkc{\n\t\tprowjobs: []kube.ProwJob{pjutil.NewProwJob(pjutil.BatchSpec(pre, kube.Refs{\n\t\t\tOrg: \"o\",\n\t\t\tRepo: \"r\",\n\t\t\tBaseRef: \"master\",\n\t\t\tBaseSHA: \"123\",\n\t\t\tPulls: []kube.Pull{\n\t\t\t\t{\n\t\t\t\t\tNumber: 1,\n\t\t\t\t\tSHA: \"abc\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tNumber: 2,\n\t\t\t\t\tSHA: \"qwe\",\n\t\t\t\t},\n\t\t\t},\n\t\t}))},\n\t}\n\tjc := &fjc{}\n\tc := Controller{\n\t\tkc: fc,\n\t\tjc: jc,\n\t\tca: newFakeConfigAgent(t),\n\t\tpendingJobs: make(map[string]int),\n\t\tlock: sync.RWMutex{},\n\t}\n\n\tif err := c.Sync(); err != nil {\n\t\tt.Fatalf(\"Error on first sync: %v\", err)\n\t}\n\tif fc.prowjobs[0].Status.State != kube.PendingState {\n\t\tt.Fatalf(\"Wrong state: %v\", fc.prowjobs[0].Status.State)\n\t}\n\tif !fc.prowjobs[0].Status.JenkinsEnqueued {\n\t\tt.Fatal(\"Wrong enqueued.\")\n\t}\n\tjc.enqueued = true\n\tif err := c.Sync(); err != nil {\n\t\tt.Fatalf(\"Error on second sync: %v\", err)\n\t}\n\tif !fc.prowjobs[0].Status.JenkinsEnqueued {\n\t\tt.Fatal(\"Wrong enqueued steady state.\")\n\t}\n\tjc.enqueued = false\n\tif err := c.Sync(); err != nil {\n\t\tt.Fatalf(\"Error on third sync: %v\", err)\n\t}\n\tif fc.prowjobs[0].Status.JenkinsEnqueued {\n\t\tt.Fatal(\"Wrong enqueued after leaving queue.\")\n\t}\n\tjc.status = Status{Building: true}\n\tif err := c.Sync(); err != nil {\n\t\tt.Fatalf(\"Error on fourth sync: %v\", err)\n\t}\n\tif fc.prowjobs[0].Status.State != kube.PendingState {\n\t\tt.Fatalf(\"Wrong state: %v\", fc.prowjobs[0].Status.State)\n\t}\n\tjc.status = Status{\n\t\tBuilding: false,\n\t\tNumber: 42,\n\t}\n\tif err := c.Sync(); err != nil {\n\t\tt.Fatalf(\"Error on fifth sync: %v\", err)\n\t}\n\tif fc.prowjobs[0].Status.PodName != \"pr-some-job-42\" {\n\t\tt.Fatalf(\"Wrong PodName: %s\", fc.prowjobs[0].Status.PodName)\n\t}\n\tif fc.prowjobs[0].Status.State != kube.FailureState {\n\t\tt.Fatalf(\"Wrong state: %v\", fc.prowjobs[0].Status.State)\n\t}\n\n\t// This is what the SQ reads.\n\tif fc.prowjobs[0].Spec.Context != \"Some Job Context\" {\n\t\tt.Fatalf(\"Wrong context: %v\", fc.prowjobs[0].Spec.Context)\n\t}\n}", "func Test_UniformRegistration_RegistrationOfKeptnIntegrationMultiplePods(t *testing.T) {\n\tdefer func(t *testing.T) {\n\t\tPrintLogsOfPods(t, []string{\"shipyard-controller\"})\n\t}(t)\n\n\t// make sure the echo-service uses the same distributor as Keptn core\n\timageName, err := GetImageOfDeploymentContainer(\"lighthouse-service\", \"lighthouse-service\")\n\trequire.Nil(t, err)\n\tdistributorImage := strings.Replace(imageName, \"lighthouse-service\", \"distributor\", 1)\n\n\techoServiceManifestContent := strings.ReplaceAll(echoServiceK8sManifest, \"${distributor-image}\", distributorImage)\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"replicas: 1\", \"replicas: 3\")\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"${queue-group}\", \"echo-service\")\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"${api-endpoint}\", \"\")\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"${api-token}\", \"\")\n\n\ttmpFile, err := CreateTmpFile(\"echo-service-*.yaml\", echoServiceManifestContent)\n\tdefer func() {\n\t\tif err := os.Remove(tmpFile); err != nil {\n\t\t\tt.Logf(\"Could not delete file: %v\", err)\n\t\t}\n\t}()\n\ttestUniformIntegration(t, func() {\n\t\t// install echo integration\n\t\t_, err = KubeCtlApplyFromURL(tmpFile)\n\t\trequire.Nil(t, err)\n\n\t\terr = waitForDeploymentToBeRolledOut(false, echoServiceName, GetKeptnNameSpaceFromEnv())\n\t\trequire.Nil(t, err)\n\n\t}, func() {\n\t\terr := KubeCtlDeleteFromURL(tmpFile)\n\t\trequire.Nil(t, err)\n\t}, true)\n}", "func TestServiceCreateWithMultipleContainers(t *testing.T) {\n\tif test.ServingFlags.DisableOptionalAPI {\n\t\tt.Skip(\"Multiple containers support is not required by Knative Serving API Specification\")\n\t}\n\tif !test.ServingFlags.EnableBetaFeatures {\n\t\tt.Skip()\n\t}\n\tt.Parallel()\n\tclients := test.Setup(t)\n\n\tnames := test.ResourceNames{\n\t\tService: test.ObjectNameForTest(t),\n\t\tImage: test.ServingContainer,\n\t\tSidecars: []string{\n\t\t\ttest.SidecarContainer,\n\t\t},\n\t}\n\n\t// Clean up on test failure or interrupt\n\ttest.EnsureTearDown(t, clients, &names)\n\tcontainers := []corev1.Container{{\n\t\tImage: pkgtest.ImagePath(names.Image),\n\t\tPorts: []corev1.ContainerPort{{\n\t\t\tContainerPort: 8881,\n\t\t}},\n\t}, {\n\t\tImage: pkgtest.ImagePath(names.Sidecars[0]),\n\t}}\n\n\t// Setup initial Service\n\tif _, err := v1test.CreateServiceReady(t, clients, &names, func(svc *v1.Service) {\n\t\tsvc.Spec.Template.Spec.Containers = containers\n\t}); err != nil {\n\t\tt.Fatalf(\"Failed to create initial Service %v: %v\", names.Service, err)\n\t}\n\n\t// Validate State after Creation\n\tif err := validateControlPlane(t, clients, names, \"1\" /*1 is the expected generation value*/); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif err := validateDataPlane(t, clients, names, test.MultiContainerResponse); err != nil {\n\t\tt.Error(err)\n\t}\n}", "func (m *MockServiceControllerFactory) Build(mgr mc_manager.AsyncManager, clusterName string) (controller1.ServiceController, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", mgr, clusterName)\n\tret0, _ := ret[0].(controller1.ServiceController)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestNewController(t *testing.T) {\n\tmessagingClientSet, err := clientset.NewForConfig(&rest.Config{})\n\tif err != nil {\n\t\tt.Fail()\n\t}\n\n\tmessagingInformerFactory := informers.NewSharedInformerFactory(messagingClientSet, 0)\n\tnatssChannelInformer := messagingInformerFactory.Messaging().V1alpha1().NatssChannels()\n\n\tc := NewController(reconciler.Options{\n\t\tKubeClientSet: fakekubeclientset.NewSimpleClientset(),\n\t\tDynamicClientSet: nil,\n\t\tNatssClientSet: nil,\n\t\tRecorder: nil,\n\t\tStatsReporter: nil,\n\t\tConfigMapWatcher: nil,\n\t\tLogger: logtesting.TestLogger(t),\n\t\tResyncPeriod: 0,\n\t\tStopChannel: nil,\n\t}, dispatchertesting.NewDispatcherDoNothing(), natssChannelInformer)\n\tif c == nil {\n\t\tt.Errorf(\"unable to create dispatcher controller\")\n\t}\n}", "func TestCancelManyJobs(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping integration tests in short mode\")\n\t}\n\n\tt.Parallel()\n\tc, _ := minikubetestenv.AcquireCluster(t)\n\n\t// Create an input repo\n\trepo := tu.UniqueString(\"TestCancelManyJobs\")\n\trequire.NoError(t, c.CreateRepo(pfs.DefaultProjectName, repo))\n\n\t// Create sleep pipeline\n\tpipeline := tu.UniqueString(\"pipeline\")\n\trequire.NoError(t, c.CreatePipeline(pfs.DefaultProjectName,\n\t\tpipeline,\n\t\t\"\",\n\t\t[]string{\"sleep\", \"600\"},\n\t\tnil,\n\t\t&pps.ParallelismSpec{\n\t\t\tConstant: 1,\n\t\t},\n\t\tclient.NewPFSInput(pfs.DefaultProjectName, repo, \"/*\"),\n\t\t\"\",\n\t\tfalse,\n\t))\n\n\t// Create 10 input commits, to spawn 10 jobs\n\tvar commits []*pfs.Commit\n\tfor i := 0; i < 10; i++ {\n\t\tcommit, err := c.StartCommit(pfs.DefaultProjectName, repo, \"master\")\n\t\trequire.NoError(t, c.PutFile(commit, \"file\", strings.NewReader(\"foo\")))\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, c.FinishCommit(pfs.DefaultProjectName, repo, commit.Branch.Name, commit.Id))\n\t\tcommits = append(commits, commit)\n\t}\n\n\t// For each expected job: watch to make sure the input job comes up, make\n\t// sure that it's the only job running, then cancel it\n\tfor _, commit := range commits {\n\t\t// Wait until PPS has started processing commit\n\t\tvar jobInfo *pps.JobInfo\n\t\trequire.NoErrorWithinT(t, 30*time.Second, func() error {\n\t\t\treturn backoff.Retry(func() error {\n\t\t\t\tjobInfos, err := c.ListJob(pfs.DefaultProjectName, pipeline, []*pfs.Commit{commit}, -1, true)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif len(jobInfos) != 1 {\n\t\t\t\t\treturn errors.Errorf(\"Expected one job, but got %d: %v\", len(jobInfos), jobInfos)\n\t\t\t\t}\n\t\t\t\tjobInfo = jobInfos[0]\n\t\t\t\treturn nil\n\t\t\t}, backoff.NewTestingBackOff())\n\t\t})\n\n\t\t// Stop the job\n\t\trequire.NoError(t, c.StopJob(pfs.DefaultProjectName, jobInfo.Job.Pipeline.Name, jobInfo.Job.Id))\n\n\t\t// Check that the job is now killed\n\t\trequire.NoErrorWithinT(t, 30*time.Second, func() error {\n\t\t\treturn backoff.Retry(func() error {\n\t\t\t\t// TODO(msteffen): once github.com/pachyderm/pachyderm/v2/pull/2642 is\n\t\t\t\t// submitted, change ListJob here to filter on commit1 as the input commit,\n\t\t\t\t// rather than inspecting the input in the test\n\t\t\t\tupdatedJobInfo, err := c.InspectJob(pfs.DefaultProjectName, jobInfo.Job.Pipeline.Name, jobInfo.Job.Id, false)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif updatedJobInfo.State != pps.JobState_JOB_KILLED {\n\t\t\t\t\treturn errors.Errorf(\"job %s is still running, but should be KILLED\", jobInfo.Job.Id)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}, backoff.NewTestingBackOff())\n\t\t})\n\t}\n}", "func TestConfigController(t *testing.T) {\n\tvar (\n\t\tname = \"common-service\"\n\t\tnamespace = \"ibm-common-service\"\n\t)\n\n\treq := getReconcileRequest(name, namespace)\n\tr := getReconciler(name, namespace)\n\n\tinitReconcile(t, r, req)\n\n}", "func CreatePods(c kclientset.Interface, appName string, ns string, labels map[string]string, spec kapiv1.PodSpec, maxCount int, tuning *TuningSetType) {\n\tfor i := 0; i < maxCount; i++ {\n\t\tframework.Logf(\"%v/%v : Creating pod\", i+1, maxCount)\n\t\t// Retry on pod creation failure\n\t\tfor retryCount := 0; retryCount < maxRetries; retryCount++ {\n\t\t\t_, err := c.CoreV1().Pods(ns).Create(&kapiv1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: fmt.Sprintf(appName+\"-pod-%v\", i),\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: spec,\n\t\t\t})\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tframework.ExpectNoError(err)\n\t\t}\n\t\tif tuning != nil {\n\t\t\t// If a rate limit has been defined we wait for N ms between creation\n\t\t\tif tuning.Pods.RateLimit.Delay != 0 {\n\t\t\t\tframework.Logf(\"Sleeping %d ms between podcreation.\", tuning.Pods.RateLimit.Delay)\n\t\t\t\ttime.Sleep(tuning.Pods.RateLimit.Delay * time.Millisecond)\n\t\t\t}\n\t\t\t// If a stepping tuningset has been defined in the config, we wait for the step of pods to be created, and pause\n\t\t\tif tuning.Pods.Stepping.StepSize != 0 && (i+1)%tuning.Pods.Stepping.StepSize == 0 {\n\t\t\t\tframework.Logf(\"Waiting for pods created this step to be running\")\n\t\t\t\tpods, err := exutil.WaitForPods(c.CoreV1().Pods(ns), exutil.ParseLabelsOrDie(mapToString(labels)), exutil.CheckPodIsRunningFn, i+1, tuning.Pods.Stepping.Timeout*time.Second)\n\t\t\t\tif err != nil {\n\t\t\t\t\tframework.Failf(\"Error in wait... %v\", err)\n\t\t\t\t} else if len(pods) < i+1 {\n\t\t\t\t\tframework.Failf(\"Only got %v out of %v\", len(pods), i+1)\n\t\t\t\t}\n\n\t\t\t\tframework.Logf(\"We have created %d pods and are now sleeping for %d seconds\", i+1, tuning.Pods.Stepping.Pause)\n\t\t\t\ttime.Sleep(tuning.Pods.Stepping.Pause * time.Second)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestLoad(t *testing.T) {\n\tclientset, err := k8sutils.MustGetClientset()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)\n\tdefer cancel()\n\n\t// Create namespace if it doesn't exist\n\tnamespaceExists, err := k8sutils.NamespaceExists(ctx, clientset, namespace)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif !namespaceExists {\n\t\terr = k8sutils.MustCreateNamespace(ctx, clientset, namespace)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\tdeployment, err := k8sutils.MustParseDeployment(noopDeploymentMap[*osType])\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdeploymentsClient := clientset.AppsV1().Deployments(namespace)\n\terr = k8sutils.MustCreateDeployment(ctx, deploymentsClient, deployment)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(\"Checking pods are running\")\n\terr = k8sutils.WaitForPodsRunning(ctx, clientset, namespace, podLabelSelector)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tt.Log(\"Repeating the scale up/down cycle\")\n\tfor i := 0; i < *iterations; i++ {\n\t\tt.Log(\"Iteration \", i)\n\t\tt.Log(\"Scale down deployment\")\n\t\terr = k8sutils.MustScaleDeployment(ctx, deploymentsClient, deployment, clientset, namespace, podLabelSelector, *scaleDownReplicas, *skipWait)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tt.Log(\"Scale up deployment\")\n\t\terr = k8sutils.MustScaleDeployment(ctx, deploymentsClient, deployment, clientset, namespace, podLabelSelector, *scaleUpReplicas, *skipWait)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\tt.Log(\"Checking pods are running and IP assigned\")\n\terr = k8sutils.WaitForPodsRunning(ctx, clientset, \"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif *validateStateFile {\n\t\tt.Run(\"Validate state file\", TestValidateState)\n\t}\n\n\tif *validateDualStack {\n\t\tt.Run(\"Validate dualstack overlay\", TestDualStackProperties)\n\t}\n}", "func (b *Botanist) WaitForControllersToBeActive(ctx context.Context) error {\n\ttype controllerInfo struct {\n\t\tname string\n\t\tlabels map[string]string\n\t}\n\n\ttype checkOutput struct {\n\t\tcontrollerName string\n\t\tready bool\n\t\terr error\n\t}\n\n\tvar (\n\t\tcontrollers = []controllerInfo{}\n\t\tpollInterval = 5 * time.Second\n\t)\n\n\t// Check whether the kube-controller-manager deployment exists\n\tif err := b.K8sSeedClient.Client().Get(ctx, kutil.Key(b.Shoot.SeedNamespace, v1beta1constants.DeploymentNameKubeControllerManager), &appsv1.Deployment{}); err == nil {\n\t\tcontrollers = append(controllers, controllerInfo{\n\t\t\tname: v1beta1constants.DeploymentNameKubeControllerManager,\n\t\t\tlabels: map[string]string{\n\t\t\t\t\"app\": \"kubernetes\",\n\t\t\t\t\"role\": \"controller-manager\",\n\t\t\t},\n\t\t})\n\t} else if client.IgnoreNotFound(err) != nil {\n\t\treturn err\n\t}\n\n\treturn retry.UntilTimeout(context.TODO(), pollInterval, 90*time.Second, func(ctx context.Context) (done bool, err error) {\n\t\tvar (\n\t\t\twg sync.WaitGroup\n\t\t\tout = make(chan *checkOutput)\n\t\t)\n\n\t\tfor _, controller := range controllers {\n\t\t\twg.Add(1)\n\n\t\t\tgo func(controller controllerInfo) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tpodList := &corev1.PodList{}\n\t\t\t\terr := b.K8sSeedClient.Client().List(ctx, podList,\n\t\t\t\t\tclient.InNamespace(b.Shoot.SeedNamespace),\n\t\t\t\t\tclient.MatchingLabels(controller.labels))\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check that only one replica of the controller exists.\n\t\t\t\tif len(podList.Items) != 1 {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for %s to have exactly one replica\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Check that the existing replica is not in getting deleted.\n\t\t\t\tif podList.Items[0].DeletionTimestamp != nil {\n\t\t\t\t\tb.Logger.Infof(\"Waiting for a new replica of %s\", controller.name)\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Check if the controller is active by reading its leader election record.\n\t\t\t\tleaderElectionRecord, err := common.ReadLeaderElectionRecord(b.K8sShootClient, resourcelock.EndpointsResourceLock, metav1.NamespaceSystem, controller.name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, err: err}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif delta := metav1.Now().UTC().Sub(leaderElectionRecord.RenewTime.Time.UTC()); delta <= pollInterval-time.Second {\n\t\t\t\t\tout <- &checkOutput{controllerName: controller.name, ready: true}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tb.Logger.Infof(\"Waiting for %s to be active\", controller.name)\n\t\t\t\tout <- &checkOutput{controllerName: controller.name}\n\t\t\t}(controller)\n\t\t}\n\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tclose(out)\n\t\t}()\n\n\t\tfor result := range out {\n\t\t\tif result.err != nil {\n\t\t\t\treturn retry.SevereError(fmt.Errorf(\"could not check whether controller %s is active: %+v\", result.controllerName, result.err))\n\t\t\t}\n\t\t\tif !result.ready {\n\t\t\t\treturn retry.MinorError(fmt.Errorf(\"controller %s is not active\", result.controllerName))\n\t\t\t}\n\t\t}\n\n\t\treturn retry.Ok()\n\t})\n}", "func TestTriggerController(t *testing.T) {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*40)\n\tdefer cancel()\n\n\tconfig, stopFn := framework.RunControlPlane(t, ctx)\n\tdefer stopFn()\n\n\tfakeClock := &fakeclock.FakeClock{}\n\t// Build, instantiate and run the trigger controller.\n\tkubeClient, factory, cmCl, cmFactory := framework.NewClients(t, config)\n\n\tnamespace := \"testns\"\n\n\t// Create Namespace\n\tns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}\n\t_, err := kubeClient.CoreV1().Namespaces().Create(ctx, ns, metav1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tshouldReissue := policies.NewTriggerPolicyChain(fakeClock).Evaluate\n\tctrl, queue, mustSync := trigger.NewController(logf.Log, cmCl, factory, cmFactory, framework.NewEventRecorder(t), fakeClock, shouldReissue)\n\tc := controllerpkg.NewController(\n\t\tctx,\n\t\t\"trigger_test\",\n\t\tmetrics.New(logf.Log, clock.RealClock{}),\n\t\tctrl.ProcessItem,\n\t\tmustSync,\n\t\tnil,\n\t\tqueue,\n\t)\n\tstopController := framework.StartInformersAndController(t, factory, cmFactory, c)\n\tdefer stopController()\n\n\t// Create a Certificate resource and wait for it to have the 'Issuing' condition.\n\tcert, err := cmCl.CertmanagerV1().Certificates(namespace).Create(ctx, &cmapi.Certificate{\n\t\tObjectMeta: metav1.ObjectMeta{Name: \"testcrt\", Namespace: \"testns\"},\n\t\tSpec: cmapi.CertificateSpec{\n\t\t\tSecretName: \"example\",\n\t\t\tCommonName: \"example.com\",\n\t\t\tIssuerRef: cmmeta.ObjectReference{Name: \"testissuer\"}, // doesn't need to exist\n\t\t},\n\t}, metav1.CreateOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = wait.PollImmediateUntil(time.Millisecond*100, func() (done bool, err error) {\n\t\tc, err := cmCl.CertmanagerV1().Certificates(cert.Namespace).Get(ctx, cert.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tt.Logf(\"Failed to fetch Certificate resource, retrying: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tif !apiutil.CertificateHasCondition(c, cmapi.CertificateCondition{\n\t\t\tType: cmapi.CertificateConditionIssuing,\n\t\t\tStatus: cmmeta.ConditionTrue,\n\t\t}) {\n\t\t\tt.Logf(\"Certificate does not have expected condition, got=%#v\", apiutil.GetCertificateCondition(c, cmapi.CertificateConditionIssuing))\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}, ctx.Done())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func controllerSubtest(name string, tc *sessionTestCase) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\t// This test uses the same controller to manage two sessions that are communicating with\n\t\t// each other (basically, both the \"local\" and \"remote\" session are on the same system).\n\t\t// This is possible because the local discriminators are chosen such that they are\n\t\t// different.\n\t\t//\n\t\t// While this is something that rarely (if ever) occurs in practice, it makes test setup\n\t\t// much simpler here. In the real world, BFD would configured between two systems and each\n\t\t// system would have its own controller which is in charge only of sessions on that system.\n\t\tcontroller := &bfd.Controller{\n\t\t\tSessions: []*bfd.Session{tc.sessionA, tc.sessionB},\n\t\t\tReceiveQueueSize: 10,\n\t\t}\n\n\t\t// both sessions send their messages through the same controller\n\t\tmessageQueue := &redirectSender{Destination: controller.Messages()}\n\t\ttc.sessionA.Sender = messageQueue\n\t\ttc.sessionB.Sender = messageQueue\n\t\ttc.sessionA.Logger = testlog.NewLogger(t).New(\"session\", \"a\")\n\t\ttc.sessionB.Logger = testlog.NewLogger(t).New(\"session\", \"b\")\n\n\t\t// the wait group is not used for synchronization, but rather to check that the controller\n\t\t// returns\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\n\t\tgo func() {\n\t\t\terr := controller.Run()\n\t\t\trequire.NoError(t, err)\n\t\t\twg.Done()\n\t\t}()\n\n\t\t// second argument is not used because we have a single queue\n\t\ttc.testBehavior(messageQueue, nil)\n\n\t\tassert.Equal(t, tc.expectedUpA, controller.IsUp(tc.sessionA.LocalDiscriminator))\n\t\tassert.Equal(t, tc.expectedUpB, controller.IsUp(tc.sessionB.LocalDiscriminator))\n\n\t\tmessageQueue.Close()\n\n\t\tfor i := 0; i < 2; i++ {\n\t\t\terr := <-controller.Errors()\n\t\t\tassert.NoError(t, err)\n\t\t}\n\t\twg.Wait()\n\t}\n}", "func TestGetCanGetAlldata(t *testing.T) {\n\ts1, closeFn1, clientset1, configFilename1, s2, closeFn2, clientset2, configFilename2 := setUpTwoApiservers(t)\n\tdefer deleteSinglePartitionConfigFile(t, configFilename1)\n\tdefer deleteSinglePartitionConfigFile(t, configFilename2)\n\tdefer closeFn1()\n\tdefer closeFn2()\n\n\t// create pods via 2 different api servers\n\tpod1 := createPod(t, clientset1, tenant1, \"te\", \"pod1\")\n\tdefer framework.DeleteTestingTenant(tenant1, s1, t)\n\tpod2 := createPod(t, clientset2, tenant2, \"te\", \"pod1\")\n\tdefer framework.DeleteTestingTenant(tenant2, s2, t)\n\tassert.NotNil(t, pod1)\n\tassert.NotNil(t, pod2)\n\tassert.NotEqual(t, pod1.UID, pod2.UID)\n\n\t// verify get pod with same api server\n\treadPod1, err := clientset1.CoreV1().PodsWithMultiTenancy(pod1.Namespace, pod1.Tenant).Get(pod1.Name, metav1.GetOptions{})\n\tassert.Nil(t, err, \"Failed to get pod 1 from same clientset\")\n\tassert.NotNil(t, readPod1)\n\treadPod2, err := clientset2.CoreV1().PodsWithMultiTenancy(pod2.Namespace, pod2.Tenant).Get(pod2.Name, metav1.GetOptions{})\n\tassert.Nil(t, err, \"Failed to get pod 2 from same clientset\")\n\tassert.NotNil(t, readPod2)\n\n\t// verify get pod through different api server\n\treadPod1, err = clientset2.CoreV1().PodsWithMultiTenancy(pod1.Namespace, pod1.Tenant).Get(pod1.Name, metav1.GetOptions{})\n\tassert.Nil(t, err, \"Failed to get pod 1 from different clientset\")\n\tif err == nil {\n\t\tcheckPodEquality(t, pod1, readPod1)\n\t}\n\treadPod2, err = clientset1.CoreV1().PodsWithMultiTenancy(pod2.Namespace, pod2.Tenant).Get(pod2.Name, metav1.GetOptions{})\n\tassert.Nil(t, err, \"Failed to get pod 2 from different clientset\")\n\tif err == nil {\n\t\tcheckPodEquality(t, pod2, readPod2)\n\t}\n\n\t// create replicaset via 2 different api servers\n\trs1 := createRS(t, clientset1, tenant1, \"rs1\", \"default\", 1)\n\trs2 := createRS(t, clientset2, tenant2, \"rs2\", \"default\", 1)\n\tassert.NotNil(t, rs1)\n\tassert.NotNil(t, rs2)\n\tassert.NotEqual(t, rs1.UID, rs2.UID)\n\n\t// verify get rs through different api server\n\treadRs1, err := clientset2.AppsV1().ReplicaSetsWithMultiTenancy(rs1.Namespace, rs1.Tenant).Get(rs1.Name, metav1.GetOptions{})\n\tassert.Nil(t, err, \"Failed to get rs 1 from different clientset\")\n\tif err == nil {\n\t\tcheckRSEquality(t, rs1, readRs1)\n\t}\n\treadRs2, err := clientset1.AppsV1().ReplicaSetsWithMultiTenancy(rs2.Namespace, rs2.Tenant).Get(rs2.Name, metav1.GetOptions{})\n\tassert.Nil(t, err, \"Failed to get rs 2 from different clientset\")\n\tif err == nil {\n\t\tcheckRSEquality(t, rs2, readRs2)\n\t}\n\n\t// tear down\n\tdeletePod(t, clientset1, pod1)\n\tdeletePod(t, clientset1, pod2)\n\tdeleteRS(t, clientset2, rs1)\n\tdeleteRS(t, clientset2, rs2)\n}", "func setUpTestApps(envoyMaxTLSVersion string, clientName string, serverName string, ns []string) (*v1.Pod, *v1.Service) {\n\t// Install OSM\n\tinstallOpts := Td.GetOSMInstallOpts()\n\tinstallOpts.EnablePermissiveMode = true\n\tExpect(Td.InstallOSM(installOpts)).To(Succeed())\n\tExpect(Td.WaitForPodsRunningReady(Td.OsmNamespace, 60*time.Second, 3 /* 1 controller, 1 injector, 1 bootstrap */, nil)).To(Succeed())\n\n\t// Get the meshConfig CRD\n\tmeshConfig, err := Td.GetMeshConfig(Td.OsmNamespace)\n\tExpect(err).NotTo(HaveOccurred())\n\n\t// Update envoy maxTLSVersion\n\tBy(fmt.Sprintf(\"Patching envoy maxTLSVersion to be %s\", envoyMaxTLSVersion))\n\tmeshConfig.Spec.Sidecar.TLSMaxProtocolVersion = envoyMaxTLSVersion\n\t_, err = Td.UpdateOSMConfig(meshConfig)\n\tExpect(err).NotTo(HaveOccurred())\n\n\t// Create Meshed Test NS\n\tfor _, n := range ns {\n\t\tExpect(Td.CreateNs(n, nil)).To(Succeed())\n\t\tExpect(Td.AddNsToMesh(true, n)).To(Succeed())\n\t}\n\n\t// Get simple pod definitions for the HTTP server\n\tsvcAccDef, podDef, svcDef, err := Td.GetOSSpecificHTTPBinPod(serverName, serverName, PodCommandDefault...)\n\tExpect(err).NotTo(HaveOccurred())\n\n\t// Create Server Pod\n\t_, err = Td.CreateServiceAccount(serverName, &svcAccDef)\n\tExpect(err).NotTo(HaveOccurred())\n\t_, err = Td.CreatePod(serverName, podDef)\n\tExpect(err).NotTo(HaveOccurred())\n\n\t// Create Server Service\n\tdstSvc, err := Td.CreateService(serverName, svcDef)\n\tExpect(err).NotTo(HaveOccurred())\n\t// Expect it to be up and running in it's receiver namespace\n\tExpect(Td.WaitForPodsRunningReady(serverName, 90*time.Second, 1, nil)).To(Succeed())\n\n\t// Create Client Pod\n\twithSourceKubernetesService := true\n\t// setupSource sets up a curl source service and returns the pod object\n\tclientPod := setupSource(clientName, withSourceKubernetesService)\n\treturn clientPod, dstSvc\n}", "func waitForPods(cs *framework.ClientSet, expectedTotal, min, max int32) error {\n\terr := wait.PollImmediate(1*time.Second, 5*time.Minute, func() (bool, error) {\n\t\td, err := cs.AppsV1Interface.Deployments(\"openshift-machine-config-operator\").Get(context.TODO(), \"etcd-quorum-guard\", metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\t// By this point the deployment should exist.\n\t\t\tfmt.Printf(\" error waiting for etcd-quorum-guard deployment to exist: %v\\n\", err)\n\t\t\treturn true, err\n\t\t}\n\t\tif d.Status.Replicas < 1 {\n\t\t\tfmt.Println(\"operator deployment has no replicas\")\n\t\t\treturn false, nil\n\t\t}\n\t\tif d.Status.Replicas == expectedTotal &&\n\t\t\td.Status.AvailableReplicas >= min &&\n\t\t\td.Status.AvailableReplicas <= max {\n\t\t\tfmt.Printf(\" Deployment is ready! %d %d\\n\", d.Status.Replicas, d.Status.AvailableReplicas)\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor pod, info := range pods {\n\t\tif info.status == \"Running\" {\n\t\t\tnode := info.node\n\t\t\tif node == \"\" {\n\t\t\t\treturn fmt.Errorf(\"Pod %s not associated with a node\", pod)\n\t\t\t}\n\t\t\tif _, ok := nodes[node]; !ok {\n\t\t\t\treturn fmt.Errorf(\"pod %s running on %s, not a master\", pod, node)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func checkPods(podClient v1.CoreV1Interface, logger *log.Logger, filters ...PodPredicate) ([]kubev1.Pod, error) {\n\tlogger = logging.CreateNewStdLoggerOrUseExistingLogger(logger)\n\n\tlogger.Print(\"Checking that all Pods are running or completed...\")\n\n\tlist, err := podClient.Pods(metav1.NamespaceAll).List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting pod list: %v\", err)\n\t}\n\n\tif len(list.Items) == 0 {\n\t\treturn nil, fmt.Errorf(\"pod list is empty. this should NOT happen\")\n\t}\n\n\tpods := filterPods(list, filters...)\n\n\t// Keep track of all pending pods that are not associated with a job\n\t// and store all pods associated with a job for further analysis\n\tpendingPods := []kubev1.Pod{}\n\tjobPods := []kubev1.Pod{}\n\tfor _, pod := range pods.Items {\n\t\tif IsNotControlledByJob(pod) {\n\t\t\t// Completed pod not associated with a job, e.g. a standalone pod\n\t\t\tif pod.Status.Phase == kubev1.PodSucceeded {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif pod.Status.Phase != kubev1.PodPending {\n\t\t\t\treturn nil, fmt.Errorf(\"pod %s/%s in unexpected phase %s: reason: %s message: %s\", pod.Namespace, pod.Name, pod.Status.Phase, pod.Status.Reason, pod.Status.Message)\n\t\t\t}\n\t\t\tlogger.Printf(\"pod %s/%s is not ready. Phase: %s, Reason: %s, Message: %s\", pod.Namespace, pod.Name, pod.Status.Phase, pod.Status.Reason, pod.Status.Message)\n\t\t\tpendingPods = append(pendingPods, pod)\n\t\t} else {\n\t\t\tjobPods = append(jobPods, pod)\n\t\t}\n\t}\n\n\tpendingJobPods, err := checkJobPods(jobPods, logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogger.Printf(\"%v pods are currently not running or complete:\", len(pendingPods)+len(pendingJobPods))\n\n\treturn append(pendingPods, pendingJobPods...), nil\n}", "func (k *Kubernetes) Test(ctx context.Context) error {\n\tk.l.Lock()\n\tdefer k.l.Unlock()\n\n\treturn k.updatePods(ctx)\n}", "func newPodClients(kubeClient kubernetes.Interface, namespace string) v1lister.PodLister {\n\t// We are interested in pods which are Running or Unknown or Pending\n\t// We don't want succeeded and failed pods because they don't generate any usage anymore.\n\tselector := fields.ParseSelectorOrDie(\"status.phase!=\" + string(v1.PodSucceeded) +\n\t\t\",status.phase!=\" + string(v1.PodFailed))\n\tpodListWatch := cache.NewListWatchFromClient(kubeClient.CoreV1().RESTClient(), \"pods\", namespace, selector)\n\tindexer, controller := cache.NewIndexerInformer(\n\t\tpodListWatch,\n\t\t&v1.Pod{},\n\t\ttime.Hour,\n\t\t&cache.ResourceEventHandlerFuncs{},\n\t\tcache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},\n\t)\n\tpodLister := v1lister.NewPodLister(indexer)\n\tstopCh := make(chan struct{})\n\tgo controller.Run(stopCh)\n\tif !cache.WaitForCacheSync(make(<-chan struct{}), controller.HasSynced) {\n\t\tlogrus.Fatalf(\"Failed to sync pod cache during initialization\")\n\t} else {\n\t\tlogrus.Info(\"Initial pod synced successfully\")\n\t}\n\treturn podLister\n}", "func (a *AppBuilder) Controllers(ctors ...Controller) *AppBuilder {\n\ta.init()\n\n\tvar configFile string\n\tflag.StringVar(&configFile, \"config\", \"\",\n\t\t\"The controller will load its initial configuration from this file. \"+\n\t\t\t\"Omit this flag to use the default configuration values. \"+\n\t\t\t\"Command-line flags override configuration from this file.\")\n\n\tflag.Parse()\n\n\tvar err error\n\toptions := ctrl.Options{Scheme: a.scheme}\n\tif configFile != \"\" {\n\t\toptions, err = options.AndFrom(ctrl.ConfigFile().AtPath(configFile))\n\t\tif err != nil {\n\t\t\ta.Logger.Fatalw(\"unable to load the config file\", \"err\", err)\n\t\t}\n\t}\n\toptions.Scheme = a.scheme\n\n\ta.Manager, err = ctrl.NewManager(a.Config, options)\n\tif err != nil {\n\t\ta.Logger.Fatalw(\"unable to start manager\", \"err\", err)\n\t}\n\tif err := a.Manager.AddHealthzCheck(\"healthz\", healthz.Ping); err != nil {\n\t\ta.Logger.Fatalw(\"unable to set up health check\", \"err\", err)\n\t}\n\tif err := a.Manager.AddReadyzCheck(\"readyz\", healthz.Ping); err != nil {\n\t\ta.Logger.Fatalw(\"unable to set up ready check\", \"err\", err)\n\t}\n\n\ta.Context = kmanager.WithManager(a.Context, a.Manager)\n\t// a manager implements all cluster.Cluster methods\n\ta.Context = kclient.WithCluster(a.Context, a.Manager)\n\ta.initClient(a.Manager.GetClient())\n\n\tfor _, controller := range ctors {\n\t\tname := controller.Name()\n\t\tcontrollerAtomicLevel := a.LevelManager.Get(name)\n\t\tcontrollerLogger := a.Logger.Desugar().WithOptions(zap.UpdateCore(controllerAtomicLevel, *a.ZapConfig)).Named(name).Sugar()\n\t\tif err := controller.Setup(a.Context, a.Manager, controllerLogger); err != nil {\n\t\t\ta.Logger.Fatalw(\"controller setup error\", \"ctrl\", name, \"err\", err)\n\t\t}\n\t}\n\n\ta.startFunc = append(a.startFunc, func(ctx context.Context) error {\n\t\treturn a.Manager.Start(ctx)\n\t})\n\n\treturn a\n}", "func (o *ControllerBuildOptions) Run() error {\n\tjxClient, devNs, err := o.JXClientAndDevNamespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkubeClient, err := o.KubeClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttektonClient, _, err := o.TektonClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !o.GitReporting {\n\t\tif strings.ToLower(os.Getenv(\"GIT_REPORTING\")) == \"true\" {\n\t\t\to.GitReporting = true\n\t\t}\n\t}\n\tif o.GitReporting {\n\t\t_, err = kubeClient.AppsV1().Deployments(devNs).Get(foghornDeploymentName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\tif !k8sErrors.IsNotFound(err) {\n\t\t\t\tlog.Logger().Warnf(\"failed to look up deployment %s in namespace %s: %s\", foghornDeploymentName, devNs, err)\n\t\t\t}\n\t\t} else {\n\t\t\to.foghornPresent = true\n\t\t}\n\t\tif o.TargetURLTemplate == \"\" {\n\t\t\to.TargetURLTemplate = os.Getenv(\"TARGET_URL_TEMPLATE\")\n\t\t}\n\t\tif o.TargetURLTemplate == \"\" {\n\t\t\to.TargetURLTemplate = defaultTargetURLTemplate\n\t\t}\n\t}\n\n\tns := o.Namespace\n\tif ns == \"\" {\n\t\tns = devNs\n\t}\n\n\to.EnvironmentCache = kube.CreateEnvironmentCache(jxClient, ns)\n\n\tif o.InitGitCredentials {\n\t\terr = o.InitGitConfigAndUser()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = o.ensureSourceRepositoryHasLabels(jxClient, ns)\n\tif err != nil {\n\t\tlog.Logger().Warnf(\"failed to label the legacy SourceRepository resources: %s\", err)\n\t}\n\n\terr = o.ensurePipelineActivityHasLabels(jxClient, ns)\n\tif err != nil {\n\t\tlog.Logger().Warnf(\"failed to label the legacy PipelineActivity resources: %s\", err)\n\t}\n\n\tpod := &corev1.Pod{}\n\tlog.Logger().Infof(\"Watching for Pods in namespace %s\", util.ColorInfo(ns))\n\tlistWatch := cache.NewListWatchFromClient(kubeClient.CoreV1().RESTClient(), \"pods\", ns, fields.Everything())\n\tkube.SortListWatchByName(listWatch)\n\t_, controller := cache.NewInformer(\n\t\tlistWatch,\n\t\tpod,\n\t\ttime.Minute*10,\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: func(obj interface{}) {\n\t\t\t\to.onPipelinePod(obj, kubeClient, jxClient, tektonClient, ns)\n\t\t\t},\n\t\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\t\to.onPipelinePod(newObj, kubeClient, jxClient, tektonClient, ns)\n\t\t\t},\n\t\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t},\n\t\t},\n\t)\n\n\tstop := make(chan struct{})\n\tgo controller.Run(stop)\n\n\t// Wait forever\n\tselect {}\n}", "func runAllControllers(controllers []controllerHelper, controllerThreadiness int, stopCh <-chan struct{}) {\n\n\t// Start the informer factories to begin populating the informer caches\n\tlog.Info(\"Starting controllers\")\n\n\t// for all our controllers\n\tfor _, c := range controllers {\n\t\tgo func(ch controllerHelper) {\n\t\t\terr := ch.Run(controllerThreadiness, stopCh)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Cannot run controller %s\", reflect.TypeOf(ch))\n\t\t\t}\n\t\t}(c)\n\t}\n\n\t<-stopCh\n\tlog.Info(\"Controllers stopped\")\n}", "func testDebug(t *testing.T, c *client.APIClient, projectName, repoName string) {\n\tt.Helper()\n\t// Get all the authenticated clients at the beginning of the test.\n\t// GetAuthenticatedPachClient will always re-activate auth, which\n\t// causes PPS to rotate all the pipeline tokens. This makes the RCs\n\t// change and recreates all the pods, which used to race with collecting logs.\n\talice := tu.Robot(tu.UniqueString(\"alice\"))\n\taliceClient, adminClient := tu.AuthenticateClient(t, c, alice), tu.AuthenticateClient(t, c, auth.RootUser)\n\tif projectName != \"default\" {\n\t\trequire.NoError(t, aliceClient.CreateProject(projectName))\n\t}\n\n\trequire.NoError(t, aliceClient.CreateRepo(projectName, repoName))\n\n\texpectedFiles, pipelines := tu.DebugFiles(t, projectName, repoName)\n\n\tfor _, p := range pipelines {\n\t\trequire.NoError(t, aliceClient.CreatePipeline(projectName,\n\t\t\tp,\n\t\t\t\"\",\n\t\t\t[]string{\"bash\"},\n\t\t\t[]string{\n\t\t\t\tfmt.Sprintf(\"cp /pfs/%s/* /pfs/out/\", repoName),\n\t\t\t\t\"sleep 45\",\n\t\t\t},\n\t\t\t&pps.ParallelismSpec{\n\t\t\t\tConstant: 1,\n\t\t\t},\n\t\t\tclient.NewPFSInput(projectName, repoName, \"/*\"),\n\t\t\t\"\",\n\t\t\tfalse,\n\t\t))\n\t}\n\n\tcommit1, err := aliceClient.StartCommit(projectName, repoName, \"master\")\n\trequire.NoError(t, err)\n\terr = aliceClient.PutFile(commit1, \"file\", strings.NewReader(\"foo\"))\n\trequire.NoError(t, err)\n\trequire.NoError(t, aliceClient.FinishCommit(projectName, repoName, commit1.Branch.Name, commit1.Id))\n\n\tjobInfos, err := aliceClient.WaitJobSetAll(commit1.Id, false)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 3, len(jobInfos))\n\n\trequire.YesError(t, aliceClient.Dump(nil, 0, &bytes.Buffer{}))\n\n\trequire.NoErrorWithinT(t, time.Minute, func() error {\n\t\t// Only admins can collect a debug dump.\n\t\tbuf := &bytes.Buffer{}\n\t\trequire.NoError(t, adminClient.Dump(nil, 0, buf))\n\t\tgr, err := gzip.NewReader(buf)\n\t\tif err != nil {\n\t\t\treturn err //nolint:wrapcheck\n\t\t}\n\t\tdefer func() {\n\t\t\trequire.NoError(t, gr.Close())\n\t\t}()\n\t\t// Check that all of the expected files were returned.\n\t\ttr := tar.NewReader(gr)\n\t\tfor {\n\t\t\thdr, err := tr.Next()\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\treturn err //nolint:wrapcheck\n\t\t\t}\n\t\t\tfor pattern, g := range expectedFiles {\n\t\t\t\tif g.Match(hdr.Name) {\n\t\t\t\t\tdelete(expectedFiles, pattern)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(expectedFiles) > 0 {\n\t\t\treturn errors.Errorf(\"Debug dump hasn't produced the exepcted files: %v\", expectedFiles)\n\t\t}\n\t\treturn nil\n\t})\n}", "func (t DefaultBuildManager) PodWatcher() {\n\n\tt.logger.Printf(\"Starting pod watcher\")\n\n\tdeleted := make(map[string]struct{})\n\n\tfor {\n\t\twatched, err := t.kubernetesClient.Pods(\"decap\").Watch(k8sapi.ListOptions{\n\t\t\tLabelSelector: \"type=decap-build\",\n\t\t})\n\t\tif err != nil {\n\t\t\tt.logger.Printf(\"Error watching cluster: %v\\n\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tevents := watched.ResultChan()\n\n\t\tfor event := range events {\n\t\t\tpod, ok := event.Object.(*k8sapi.Pod)\n\t\t\tif !ok {\n\t\t\t\t// we selected pods, so this will be a pod, but be conservative.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdeletePod := false\n\t\t\tfor _, v := range pod.Status.ContainerStatuses {\n\t\t\t\tif v.Name == \"build-server\" && v.State.Terminated != nil && v.State.Terminated.ContainerID != \"\" {\n\t\t\t\t\tdeletePod = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Try to elete the build pod if it has not already been deleted.\n\t\t\tif _, present := deleted[pod.Name]; !present && deletePod {\n\t\t\t\tif err := t.kubernetesClient.Pods(\"decap\").Delete(pod.Name, nil); err != nil {\n\t\t\t\t\tt.logger.Printf(\"Error deleting build-server pod: %v\\n\", err)\n\t\t\t\t} else {\n\t\t\t\t\tt.logger.Printf(\"Deleted pod %s\\n\", pod.Name)\n\t\t\t\t}\n\t\t\t\tdeleted[pod.Name] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n}", "func TestKnativeServingDeploymentRecreationReady(t *testing.T) {\n\tcancel := logstream.Start(t)\n\tdefer cancel()\n\tclients := Setup(t)\n\n\tdpList, err := clients.KubeClient.Kube.AppsV1().Deployments(test.ServingOperatorNamespace).List(metav1.ListOptions{})\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to get any deployment under the namespace %q: %v\",\n\t\t\ttest.ServingOperatorNamespace, err)\n\t}\n\t// Delete the deployments one by one to see if they will be recreated.\n\tfor _, deployment := range dpList.Items {\n\t\tif err := clients.KubeClient.Kube.AppsV1().Deployments(deployment.Namespace).Delete(deployment.Name,\n\t\t\t&metav1.DeleteOptions{}); err != nil {\n\t\t\tt.Fatalf(\"Failed to delete deployment %s/%s: %v\", deployment.Namespace, deployment.Name, err)\n\t\t}\n\t\tif _, err = resources.WaitForDeploymentAvailable(clients, deployment.Name, deployment.Namespace,\n\t\t\tresources.IsDeploymentAvailable); err != nil {\n\t\t\tt.Fatalf(\"The deployment %s/%s failed to reach the desired state: %v\",\n\t\t\t\tdeployment.Namespace, deployment.Name, err)\n\t\t}\n\t\tif _, err := resources.WaitForKnativeServingState(clients.KnativeServingAlphaClient, test.ServingOperatorName,\n\t\t\tresources.IsKnativeServingReady); err != nil {\n\t\t\tt.Fatalf(\"KnativeService %q failed to reach the desired state: %v\", test.ServingOperatorName, err)\n\t\t}\n\t\tt.Logf(\"The deployment %s/%s reached the desired state.\", deployment.Namespace, deployment.Name)\n\t}\n}", "func (mock *PodSecurityPolicyTemplateInterfaceMock) ControllerCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tlockPodSecurityPolicyTemplateInterfaceMockController.RLock()\n\tcalls = mock.calls.Controller\n\tlockPodSecurityPolicyTemplateInterfaceMockController.RUnlock()\n\treturn calls\n}", "func (h *KubernetesHelper) CheckPods(ctx context.Context, namespace string, deploymentName string, replicas int) error {\n\tvar checkedPods []corev1.Pod\n\n\terr := h.retryFor(60*time.Minute, func() error {\n\t\tcheckedPods = []corev1.Pod{}\n\t\tpods, err := h.GetPodsForDeployment(ctx, namespace, deploymentName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar deploymentReplicas int\n\t\tfor _, pod := range pods {\n\t\t\tcheckedPods = append(checkedPods, pod)\n\n\t\t\tdeploymentReplicas++\n\t\t\tif pod.Status.Phase != \"Running\" {\n\t\t\t\treturn fmt.Errorf(\"Pod [%s] in namespace [%s] is not running\",\n\t\t\t\t\tpod.Name, pod.Namespace)\n\t\t\t}\n\t\t\tfor _, container := range pod.Status.ContainerStatuses {\n\t\t\t\tif !container.Ready {\n\t\t\t\t\treturn fmt.Errorf(\"Container [%s] in pod [%s] in namespace [%s] is not running\",\n\t\t\t\t\t\tcontainer.Name, pod.Name, pod.Namespace)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif deploymentReplicas != replicas {\n\t\t\treturn fmt.Errorf(\"Expected there to be [%d] pods in deployment [%s] in namespace [%s], but found [%d]\",\n\t\t\t\treplicas, deploymentName, namespace, deploymentReplicas)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, pod := range checkedPods {\n\t\tfor _, status := range append(pod.Status.ContainerStatuses, pod.Status.InitContainerStatuses...) {\n\t\t\terrStr := fmt.Sprintf(\"Container [%s] in pod [%s] in namespace [%s] has restart count [%d]\",\n\t\t\t\tstatus.Name, pod.Name, pod.Namespace, status.RestartCount)\n\t\t\tif status.RestartCount == 1 {\n\t\t\t\treturn &RestartCountError{errStr}\n\t\t\t}\n\t\t\tif status.RestartCount > 1 {\n\t\t\t\treturn errors.New(errStr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func runSyncTests(t *testing.T, tests []controllerTest, storageClasses []*storage.StorageClass) {\n\tfor _, test := range tests {\n\t\tglog.V(4).Infof(\"starting test %q\", test.name)\n\n\t\t// Initialize the controller\n\t\tclient := &fake.Clientset{}\n\t\tctrl, err := newTestController(client, nil, true)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %q construct persistent volume failed: %v\", test.name, err)\n\t\t}\n\t\treactor := newVolumeReactor(client, ctrl, nil, nil, test.errors)\n\t\tfor _, claim := range test.initialClaims {\n\t\t\tctrl.claims.Add(claim)\n\t\t\treactor.claims[claim.Name] = claim\n\t\t}\n\t\tfor _, volume := range test.initialVolumes {\n\t\t\tctrl.volumes.store.Add(volume)\n\t\t\treactor.volumes[volume.Name] = volume\n\t\t}\n\n\t\t// Inject classes into controller via a custom lister.\n\t\tindexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})\n\t\tfor _, class := range storageClasses {\n\t\t\tindexer.Add(class)\n\t\t}\n\t\tctrl.classLister = storagelisters.NewStorageClassLister(indexer)\n\n\t\t// Run the tested functions\n\t\terr = test.test(ctrl, reactor, test)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test %q failed: %v\", test.name, err)\n\t\t}\n\n\t\t// Wait for the target state\n\t\terr = reactor.waitTest(test)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test %q failed: %v\", test.name, err)\n\t\t}\n\n\t\tevaluateTestResults(ctrl, reactor, test, t)\n\t}\n}", "func verifyInternalIngressController(t *testing.T, name types.NamespacedName, hostname, address, image string) {\n\tkubeConfig, err := config.GetConfig()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get kube config: %v\", err)\n\t}\n\tclient, err := kubernetes.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create kube client: %v\", err)\n\t}\n\n\techoPod := buildEchoPod(name.Name, name.Namespace)\n\tif err := kclient.Create(context.TODO(), echoPod); err != nil {\n\t\tt.Fatalf(\"failed to create pod %s/%s: %v\", echoPod.Namespace, echoPod.Name, err)\n\t}\n\tdefer func() {\n\t\tif err := kclient.Delete(context.TODO(), echoPod); err != nil {\n\t\t\tt.Fatalf(\"failed to delete pod %s/%s: %v\", echoPod.Namespace, echoPod.Name, err)\n\t\t}\n\t}()\n\n\techoService := buildEchoService(echoPod.Name, echoPod.Namespace, echoPod.ObjectMeta.Labels)\n\tif err := kclient.Create(context.TODO(), echoService); err != nil {\n\t\tt.Fatalf(\"failed to create service %s/%s: %v\", echoService.Namespace, echoService.Name, err)\n\t}\n\tdefer func() {\n\t\tif err := kclient.Delete(context.TODO(), echoService); err != nil {\n\t\t\tt.Fatalf(\"failed to delete service %s/%s: %v\", echoService.Namespace, echoService.Name, err)\n\t\t}\n\t}()\n\n\techoRoute := buildRouteWithHost(echoPod.Name, echoPod.Namespace, echoService.Name, hostname)\n\tif err := kclient.Create(context.TODO(), echoRoute); err != nil {\n\t\tt.Fatalf(\"failed to create route %s/%s: %v\", echoRoute.Namespace, echoRoute.Name, err)\n\t}\n\tdefer func() {\n\t\tif err := kclient.Delete(context.TODO(), echoRoute); err != nil {\n\t\t\tt.Fatalf(\"failed to delete route %s/%s: %v\", echoRoute.Namespace, echoRoute.Name, err)\n\t\t}\n\t}()\n\n\textraArgs := []string{\n\t\t\"--header\", \"HOST:\" + echoRoute.Spec.Host,\n\t\t\"-v\",\n\t\t\"--retry-delay\", \"20\",\n\t\t\"--max-time\", \"10\",\n\t}\n\tclientPodName := types.NamespacedName{Namespace: name.Namespace, Name: \"curl-\" + name.Name}\n\tclientPodSpec := buildCurlPod(clientPodName.Name, clientPodName.Namespace, image, address, echoRoute.Spec.Host, extraArgs...)\n\tclientPod := clientPodSpec.DeepCopy()\n\tif err := kclient.Create(context.TODO(), clientPod); err != nil {\n\t\tt.Fatalf(\"failed to create pod %q: %v\", clientPodName, err)\n\t}\n\tdefer func() {\n\t\tif err := kclient.Delete(context.TODO(), clientPod); err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tt.Fatalf(\"failed to delete pod %q: %v\", clientPodName, err)\n\t\t}\n\t}()\n\n\tvar curlPodLogs string\n\terr = wait.PollImmediate(10*time.Second, 10*time.Minute, func() (bool, error) {\n\t\tif err := kclient.Get(context.TODO(), clientPodName, clientPod); err != nil {\n\t\t\tt.Logf(\"error getting client pod %q: %v, retrying...\", clientPodName, err)\n\t\t\treturn false, nil\n\t\t}\n\t\t// First check if client curl pod is still starting or not running.\n\t\tif clientPod.Status.Phase == corev1.PodPending {\n\t\t\tt.Logf(\"waiting for client pod %q to start\", clientPodName)\n\t\t\treturn false, nil\n\t\t}\n\t\treadCloser, err := client.CoreV1().Pods(clientPod.Namespace).GetLogs(clientPod.Name, &corev1.PodLogOptions{\n\t\t\tContainer: \"curl\",\n\t\t\tFollow: false,\n\t\t}).Stream(context.TODO())\n\t\tif err != nil {\n\t\t\tt.Logf(\"failed to read output from pod %s: %v\", clientPod.Name, err)\n\t\t\treturn false, nil\n\t\t}\n\t\tscanner := bufio.NewScanner(readCloser)\n\t\tdefer func() {\n\t\t\tif err := readCloser.Close(); err != nil {\n\t\t\t\tt.Errorf(\"failed to close reader for pod %s: %v\", clientPod.Name, err)\n\t\t\t}\n\t\t}()\n\t\tcurlPodLogs = \"\"\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tcurlPodLogs += line + \"\\n\"\n\t\t\tif strings.Contains(line, \"HTTP/1.0 200 OK\") {\n\t\t\t\tt.Logf(\"verified connectivity with workload with address: %s with response %s\", address, line)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t\t// If failed or succeeded, the pod is stopped, but didn't provide us 200 response, let's try again.\n\t\tif clientPod.Status.Phase == corev1.PodFailed || clientPod.Status.Phase == corev1.PodSucceeded {\n\t\t\tt.Logf(\"client pod %q has stopped...restarting. Curl Pod Logs:\\n%s\", clientPodName, curlPodLogs)\n\t\t\tif err := kclient.Delete(context.TODO(), clientPod); err != nil && errors.IsNotFound(err) {\n\t\t\t\tt.Fatalf(\"failed to delete pod %q: %v\", clientPodName, err)\n\t\t\t}\n\t\t\t// Wait for deletion to prevent a race condition. Use PollInfinite since we are already in a Poll.\n\t\t\twait.PollInfinite(5*time.Second, func() (bool, error) {\n\t\t\t\terr = kclient.Get(context.TODO(), clientPodName, clientPod)\n\t\t\t\tif !errors.IsNotFound(err) {\n\t\t\t\t\tt.Logf(\"waiting for %q: to be deleted\", clientPodName)\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\tclientPod = clientPodSpec.DeepCopy()\n\t\t\tif err := kclient.Create(context.TODO(), clientPod); err != nil {\n\t\t\t\tt.Fatalf(\"failed to create pod %q: %v\", clientPodName, err)\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\tt.Fatalf(\"failed to verify connectivity with workload with address: %s using internal curl client. Curl Pod Logs:\\n%s\", address, curlPodLogs)\n\t}\n}", "func TestIssue351MultipleJobRun(t *testing.T) {\n\tctx, err := NewContext(t)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ctx.Cleanup()\n\n\t// Create initial CR to generate an initial job and create the initial k8s resources\n\n\tgitops := &gitopsv1alpha1.GitOpsConfig{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"GitOpsConfig\",\n\t\t\tAPIVersion: \"eunomia.kohls.io/v1alpha1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"gitops-issue351\",\n\t\t\tNamespace: ctx.namespace,\n\t\t},\n\t\tSpec: gitopsv1alpha1.GitOpsConfigSpec{\n\t\t\tTemplateSource: gitopsv1alpha1.GitConfig{\n\t\t\t\tURI: ctx.eunomiaURI,\n\t\t\t\tRef: ctx.eunomiaRef,\n\t\t\t\tContextDir: \"test/e2e/testdata/hello-a\",\n\t\t\t},\n\t\t\tParameterSource: gitopsv1alpha1.GitConfig{\n\t\t\t\tURI: ctx.eunomiaURI,\n\t\t\t\tRef: ctx.eunomiaRef,\n\t\t\t\tContextDir: \"test/e2e/testdata/empty-yaml\",\n\t\t\t},\n\t\t\tTriggers: []gitopsv1alpha1.GitOpsTrigger{\n\t\t\t\t{Type: \"Change\"},\n\t\t\t},\n\t\t\tTemplateProcessorImage: \"quay.io/kohlstechnology/eunomia-base:dev\",\n\t\t\tResourceHandlingMode: \"Apply\",\n\t\t\tResourceDeletionMode: \"Delete\",\n\t\t\tServiceAccountRef: \"eunomia-operator\",\n\t\t},\n\t}\n\n\terr = framework.Global.Client.Create(ctx, gitops, &framework.CleanupOptions{TestContext: ctx.TestCtx, Timeout: timeout, RetryInterval: retryInterval})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// When the initial job is created, we will use it as a template to create two additional jobs at the same time\n\terr = WaitForJobCreation(ctx.namespace, \"gitopsconfig-gitops-issue351-\", framework.Global.KubeClient)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tgitopsJob, err := GetJob(ctx.namespace, \"gitopsconfig-gitops-issue351-\", framework.Global.KubeClient)\n\n\tfirstJob := &batchv1.Job{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"GitOpsConfig\",\n\t\t\tAPIVersion: \"eunomia.kohls.io/v1alpha1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"first-job\",\n\t\t\tNamespace: ctx.namespace,\n\t\t},\n\t\tSpec: gitopsJob.Spec,\n\t}\n\t// The deep copy of the job keeps the selector and selector label that has to be generated by k8s.\n\t// Trying to create a job with those set will fail.\n\tfirstJob.Spec.Template.SetLabels(map[string]string{})\n\tfirstJob.Spec.Selector.Reset()\n\n\terr = framework.Global.Client.Create(ctx, firstJob, &framework.CleanupOptions{TestContext: ctx.TestCtx, Timeout: timeout, RetryInterval: retryInterval})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tsecondJob := &batchv1.Job{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"GitOpsConfig\",\n\t\t\tAPIVersion: \"eunomia.kohls.io/v1alpha1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"second-job\",\n\t\t\tNamespace: ctx.namespace,\n\t\t},\n\t\tSpec: gitopsJob.Spec,\n\t}\n\tsecondJob.Spec.Template.SetLabels(map[string]string{})\n\tsecondJob.Spec.Selector.Reset()\n\n\terr = framework.Global.Client.Create(ctx, secondJob, &framework.CleanupOptions{TestContext: ctx.TestCtx, Timeout: timeout, RetryInterval: retryInterval})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// Wait to make sure both of the jobs finish running\n\terr = wait.Poll(retryInterval, 60*time.Second, func() (done bool, err error) {\n\t\tjobOne, _ := GetJob(ctx.namespace, \"first-job\", framework.Global.KubeClient)\n\t\tjobTwo, _ := GetJob(ctx.namespace, \"second-job\", framework.Global.KubeClient)\n\n\t\tswitch {\n\t\tcase jobOne.Status.Succeeded == 1 && jobTwo.Status.Succeeded == 1:\n\t\t\tt.Logf(\"Both jobs are done\")\n\t\t\treturn true, nil\n\t\tdefault:\n\t\t\tt.Logf(\"Both jobs are not done\")\n\t\t\treturn false, nil\n\t\t}\n\t})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tdeploymentList, err := framework.Global.KubeClient.AppsV1().Deployments(ctx.namespace).List(metav1.ListOptions{})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif len(deploymentList.Items) != 1 {\n\t\tt.Errorf(\"There was only %d deployments when we were expecting 1\", len(deploymentList.Items))\n\t}\n\tif deploymentList.Items[0].GetDeletionTimestamp() != nil {\n\t\tt.Errorf(\"The deployment has been marked for deletion\")\n\t}\n}", "func Test_Pod_Checker(t *testing.T) {\n\tworkflow := func(name string) string {\n\t\treturn workflowPath(\"pod\", name)\n\t}\n\tconst (\n\t\tadded = \"added\"\n\t\tcontainerTerminatedError = \"containerTerminatedError\"\n\t\tcontainerTerminatedSuccess = \"containerTerminatedSuccess\"\n\t\tcontainerTerminatedSuccessRestartNever = \"containerTerminatedSuccessRestartNever\"\n\t\tcreateSuccess = \"createSuccess\"\n\t\timagePullError = \"imagePullError\"\n\t\timagePullErrorResolved = \"imagePullErrorResolved\"\n\t\tscheduled = \"scheduled\"\n\t\tunready = \"unready\"\n\t\tunscheduled = \"unscheduled\"\n\t)\n\n\ttests := []struct {\n\t\tname string\n\t\trecordingPaths []string\n\t\t// TODO: optional message validator function to check returned messages\n\t\texpectReady bool\n\t}{\n\t\t{\n\t\t\tname: \"Pod added but not ready\",\n\t\t\trecordingPaths: []string{workflow(added)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod scheduled but not ready\",\n\t\t\trecordingPaths: []string{workflow(scheduled)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod create success\",\n\t\t\trecordingPaths: []string{workflow(createSuccess)},\n\t\t\texpectReady: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod image pull error\",\n\t\t\trecordingPaths: []string{workflow(imagePullError)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod create success after image pull failure resolved\",\n\t\t\trecordingPaths: []string{workflow(imagePullError), workflow(imagePullErrorResolved)},\n\t\t\texpectReady: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod unscheduled\",\n\t\t\trecordingPaths: []string{workflow(unscheduled)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod unready\",\n\t\t\trecordingPaths: []string{workflow(unready)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod container terminated with error\",\n\t\t\trecordingPaths: []string{workflow(containerTerminatedError)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod container terminated successfully\",\n\t\t\trecordingPaths: []string{workflow(containerTerminatedSuccess)},\n\t\t\texpectReady: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Pod container terminated successfully with restartPolicy: Never\",\n\t\t\trecordingPaths: []string{workflow(containerTerminatedSuccessRestartNever)},\n\t\t\texpectReady: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tchecker := NewPodChecker()\n\n\t\t\tready, messages := mustCheckIfRecordingsReady(tt.recordingPaths, checker)\n\t\t\tif ready != tt.expectReady {\n\t\t\t\tt.Errorf(\"Ready() = %t, want %t\\nMessages: %s\", ready, tt.expectReady, messages)\n\t\t\t}\n\t\t})\n\t}\n}", "func newPodClients(kubeClient kube_client.Interface, resourceEventHandler cache.ResourceEventHandler, namespace string) v1lister.PodLister {\n\t// We are interested in pods which are Running or Unknown (in case the pod is\n\t// running but there are some transient errors we don't want to delete it from\n\t// our model).\n\t// We don't want to watch Pending pods because they didn't generate any usage\n\t// yet.\n\t// Succeeded and Failed failed pods don't generate any usage anymore but we\n\t// don't necessarily want to immediately delete them.\n\tselector := fields.ParseSelectorOrDie(\"status.phase!=\" + string(apiv1.PodPending))\n\tpodListWatch := cache.NewListWatchFromClient(kubeClient.CoreV1().RESTClient(), \"pods\", namespace, selector)\n\tindexer, controller := cache.NewIndexerInformer(\n\t\tpodListWatch,\n\t\t&apiv1.Pod{},\n\t\ttime.Hour,\n\t\tresourceEventHandler,\n\t\tcache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},\n\t)\n\tpodLister := v1lister.NewPodLister(indexer)\n\tstopCh := make(chan struct{})\n\tgo controller.Run(stopCh)\n\treturn podLister\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"jenkinsinstance-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twatchPredicate := util.NewPredicate(viper.GetString(\"namespace\"))\n\n\t// Watch for changes to JenkinsInstance\n\terr = c.Watch(&source.Kind{Type: &jenkinsv1alpha1.JenkinsInstance{}}, &handler.EnqueueRequestForObject{}, watchPredicate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch a Deployment created by JenkinsInstance\n\terr = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &jenkinsv1alpha1.JenkinsInstance{},\n\t}, watchPredicate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch a PVC created by JenkinsInstance\n\terr = c.Watch(&source.Kind{Type: &corev1.PersistentVolumeClaim{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &jenkinsv1alpha1.JenkinsInstance{},\n\t}, watchPredicate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch a Secret created by JenkinsInstance\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &jenkinsv1alpha1.JenkinsInstance{},\n\t}, watchPredicate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch a Service created by JenkinsInstance\n\terr = c.Watch(&source.Kind{Type: &corev1.Service{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &jenkinsv1alpha1.JenkinsInstance{},\n\t}, watchPredicate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch an Ingress created by JenkinsInstance\n\terr = c.Watch(&source.Kind{Type: &v1beta1.Ingress{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &jenkinsv1alpha1.JenkinsInstance{},\n\t}, watchPredicate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch a Networkpolicy created by JenkinsInstance\n\terr = c.Watch(&source.Kind{Type: &netv1.NetworkPolicy{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &jenkinsv1alpha1.JenkinsInstance{},\n\t}, watchPredicate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch Secret resources not owned by the JenkinsInstance change\n\t// This is needed for re-loading login information from the pre-provided secret\n\t// When admin login secret changes, Watch will list all JenkinsInstances\n\t// and re-enqueue the keys for the ones that refer to that admin login secret via their spec.\n\terr = c.Watch(\n\t\t&source.Kind{Type: &corev1.Secret{}},\n\t\t&handler.EnqueueRequestsFromMapFunc{\n\t\t\tToRequests: handler.ToRequestsFunc(func(a handler.MapObject) []reconcile.Request {\n\n\t\t\t\tjenkinsInstances := &jenkinsv1alpha1.JenkinsInstanceList{}\n\t\t\t\terr = mgr.GetClient().List(\n\t\t\t\t\tcontext.TODO(),\n\t\t\t\t\t&client.ListOptions{LabelSelector: labels.Everything()},\n\t\t\t\t\tjenkinsInstances)\n\t\t\t\tif err != nil {\n\t\t\t\t\tglog.Errorf(\"Could not list JenkinsInstances\")\n\t\t\t\t\treturn []reconcile.Request{}\n\t\t\t\t}\n\n\t\t\t\tvar keys []reconcile.Request\n\t\t\t\tfor _, inst := range jenkinsInstances.Items {\n\t\t\t\t\tif inst.Spec.AdminSecret == a.Meta.GetName() {\n\t\t\t\t\t\tkeys = append(keys, reconcile.Request{\n\t\t\t\t\t\t\tNamespacedName: types.NewNamespacedNameFromString(\n\t\t\t\t\t\t\t\tfmt.Sprintf(\"%s%c%s\", inst.GetNamespace(), types.Separator, inst.GetName())),\n\t\t\t\t\t\t})\n\t\t\t\t\t} else if inst.Spec.PluginConfig != nil {\n\t\t\t\t\t\tif inst.Spec.PluginConfig.ConfigSecret == a.Meta.GetName() {\n\t\t\t\t\t\t\tkeys = append(keys, reconcile.Request{\n\t\t\t\t\t\t\t\tNamespacedName: types.NewNamespacedNameFromString(\n\t\t\t\t\t\t\t\t\tfmt.Sprintf(\"%s%c%s\", inst.GetNamespace(), types.Separator, inst.GetName())),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// return found keys\n\t\t\t\treturn keys\n\t\t\t}),\n\t\t}, watchPredicate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func TestDashboardHandler_Deployments(t *testing.T) {\n\tfor _, test := range tests {\n\t\tt.Logf(\"Running test: %s\", test.Name)\n\t\tsubTest(t, test)\n\t}\n}", "func Test_Reconcile(t *testing.T) {\n\t// Fake client is buggy, and it looks like it more or less works for very basic and simple scenarios\n\t// https://github.com/kubernetes-sigs/controller-runtime/issues/348\n\tfakeClientBuilder := fake.NewClientBuilder()\n\n\t//mock registry\n\tmockRegistry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, \"Fake registry\")\n\t}))\n\tdefer mockRegistry.Close()\n\n\tu,_ := url.Parse(mockRegistry.URL)\n\n\treconc := reconciler{\n\t\tclient: nil,\n\t\tignoredNamespaces: map[string]struct{}{\"kube-system\": {}},\n\t\tbackupRegistry: u.Host+\"/namespace/backup\",\n\t}\n\n\ttests := []struct {\n\t\t// test case short title\n\t\ttitle string\n\t\tobjects []client.Object\n\t\texpetedImage string\n\t\texpectError bool\n\t}{\n\t\t{\n\t\t\ttitle: \"reconcile deployment\",\n\t\t\texpetedImage: reconc.getTargetImage(u.Host+\"/nginx:latest\"),\n\t\t\tobjects: []client.Object{\n\t\t\t\t&appsv1.Deployment{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: \"server\",\n\t\t\t\t\t\tNamespace: \"test\",\n\t\t\t\t\t},\n\t\t\t\t\tSpec: appsv1.DeploymentSpec{\n\t\t\t\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\t\t\t\tMatchLabels: map[string]string{\"deployment\": \"test\" + \"-deployment\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\t\t\t\tObjectMeta: metav1.ObjectMeta{Labels: map[string]string{\"deployment\": \"test\" + \"-deployment\"}},\n\t\t\t\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tName: \"nginx\",\n\t\t\t\t\t\t\t\t\t\tImage: u.Host+\"/nginx:latest\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\ttitle: \"reconcile daemonset\",\n\t\t\texpetedImage: reconc.getTargetImage(u.Host+\"/nginx:latest\"),\n\t\t\tobjects: []client.Object{\n\t\t\t\t&appsv1.DaemonSet{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tName: \"server\",\n\t\t\t\t\t\tNamespace: \"test\",\n\t\t\t\t\t},\n\t\t\t\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\t\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\t\t\t\tMatchLabels: map[string]string{\"deployment\": \"test\" + \"-deployment\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\t\t\t\tObjectMeta: metav1.ObjectMeta{Labels: map[string]string{\"deployment\": \"test\" + \"-deployment\"}},\n\t\t\t\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tName: \"nginx\",\n\t\t\t\t\t\t\t\t\t\tImage: u.Host+\"/nginx:latest\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.title, func(t *testing.T) {\n\t\t\t//Put mock objects to fake client\n\t\t\tfakeClientBuilder.WithObjects(test.objects...)\n\t\t\t//Set fake client to reconciler\n\t\t\treconc.client = fakeClientBuilder.Build()\n\n\t\t\tfor _, o := range test.objects {\n\t\t\t\tkind := \"\"\n\n\t\t\t\tif _, isDeployment := o.(*appsv1.Deployment); isDeployment {\n\t\t\t\t\tkind = \"Deployment\"\n\t\t\t\t}else {\n\t\t\t\t\tkind = \"DaemonSet\"\n\t\t\t\t}\n\n\t\t\t\tr := reconcile.Request{NamespacedName: types.NamespacedName{\n\t\t\t\t\tNamespace: o.GetNamespace(),\n\t\t\t\t\tName: fmt.Sprintf(\"%s:%s\", kind, o.GetName()),\n\t\t\t\t}}\n\t\t\t\t_, e := reconc.Reconcile(context.Background(), r)\n\t\t\t\trequire.Nil(t, e)\n\n\t\t\t\t//Checking if reconciled object has the right image\n\t\t\t\tkey := types.NamespacedName{\n\t\t\t\t\tName: o.GetName(),\n\t\t\t\t\tNamespace: o.GetNamespace(),\n\t\t\t\t}\n\t\t\t\tswitch kind {\n\t\t\t\tcase \"Deployment\":\n\t\t\t\t\tdp := appsv1.Deployment{}\n\t\t\t\t\treconc.client.Get(context.Background(),key,&dp)\n\t\t\t\t\trequire.Equal(t,dp.Spec.Template.Spec.Containers[0].Image,test.expetedImage)\n\n\t\t\t\tcase \"DaemonSet\":\n\t\t\t\t\tds := appsv1.DaemonSet{}\n\t\t\t\t\treconc.client.Get(context.Background(),key,&ds)\n\t\t\t\t\trequire.Equal(t,ds.Spec.Template.Spec.Containers[0].Image,test.expetedImage)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}", "func (mock *MultiClusterAppInterfaceMock) ControllerCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tlockMultiClusterAppInterfaceMockController.RLock()\n\tcalls = mock.calls.Controller\n\tlockMultiClusterAppInterfaceMockController.RUnlock()\n\treturn calls\n}", "func (m *kubeGenericRuntimeManager) computePodActions(ctx context.Context, pod *v1.Pod, podStatus *kubecontainer.PodStatus) podActions {\n\tklog.V(5).InfoS(\"Syncing Pod\", \"pod\", klog.KObj(pod))\n\n\tcreatePodSandbox, attempt, sandboxID := runtimeutil.PodSandboxChanged(pod, podStatus)\n\tchanges := podActions{\n\t\tKillPod: createPodSandbox,\n\t\tCreateSandbox: createPodSandbox,\n\t\tSandboxID: sandboxID,\n\t\tAttempt: attempt,\n\t\tContainersToStart: []int{},\n\t\tContainersToKill: make(map[kubecontainer.ContainerID]containerToKillInfo),\n\t}\n\n\t// If we need to (re-)create the pod sandbox, everything will need to be\n\t// killed and recreated, and init containers should be purged.\n\tif createPodSandbox {\n\t\tif !shouldRestartOnFailure(pod) && attempt != 0 && len(podStatus.ContainerStatuses) != 0 {\n\t\t\t// Should not restart the pod, just return.\n\t\t\t// we should not create a sandbox, and just kill the pod if it is already done.\n\t\t\t// if all containers are done and should not be started, there is no need to create a new sandbox.\n\t\t\t// this stops confusing logs on pods whose containers all have exit codes, but we recreate a sandbox before terminating it.\n\t\t\t//\n\t\t\t// If ContainerStatuses is empty, we assume that we've never\n\t\t\t// successfully created any containers. In this case, we should\n\t\t\t// retry creating the sandbox.\n\t\t\tchanges.CreateSandbox = false\n\t\t\treturn changes\n\t\t}\n\n\t\t// Get the containers to start, excluding the ones that succeeded if RestartPolicy is OnFailure.\n\t\tvar containersToStart []int\n\t\tfor idx, c := range pod.Spec.Containers {\n\t\t\tif pod.Spec.RestartPolicy == v1.RestartPolicyOnFailure && containerSucceeded(&c, podStatus) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcontainersToStart = append(containersToStart, idx)\n\t\t}\n\n\t\t// If there is any regular container, it means all init containers have\n\t\t// been initialized.\n\t\thasInitialized := hasAnyRegularContainerCreated(pod, podStatus)\n\t\t// We should not create a sandbox, and just kill the pod if initialization\n\t\t// is done and there is no container to start.\n\t\tif hasInitialized && len(containersToStart) == 0 {\n\t\t\tchanges.CreateSandbox = false\n\t\t\treturn changes\n\t\t}\n\n\t\t// If we are creating a pod sandbox, we should restart from the initial\n\t\t// state.\n\t\tif len(pod.Spec.InitContainers) != 0 {\n\t\t\t// Pod has init containers, return the first one.\n\t\t\tchanges.InitContainersToStart = []int{0}\n\t\t\treturn changes\n\t\t}\n\t\tchanges.ContainersToStart = containersToStart\n\t\treturn changes\n\t}\n\n\t// Ephemeral containers may be started even if initialization is not yet complete.\n\tfor i := range pod.Spec.EphemeralContainers {\n\t\tc := (*v1.Container)(&pod.Spec.EphemeralContainers[i].EphemeralContainerCommon)\n\n\t\t// Ephemeral Containers are never restarted\n\t\tif podStatus.FindContainerStatusByName(c.Name) == nil {\n\t\t\tchanges.EphemeralContainersToStart = append(changes.EphemeralContainersToStart, i)\n\t\t}\n\t}\n\n\thasInitialized := m.computeInitContainerActions(pod, podStatus, &changes)\n\tif changes.KillPod || !hasInitialized {\n\t\t// Initialization failed or still in progress. Skip inspecting non-init\n\t\t// containers.\n\t\treturn changes\n\t}\n\n\tif isInPlacePodVerticalScalingAllowed(pod) {\n\t\tchanges.ContainersToUpdate = make(map[v1.ResourceName][]containerToUpdateInfo)\n\t\tlatestPodStatus, err := m.GetPodStatus(ctx, podStatus.ID, pod.Name, pod.Namespace)\n\t\tif err == nil {\n\t\t\tpodStatus = latestPodStatus\n\t\t}\n\t}\n\n\t// Number of running containers to keep.\n\tkeepCount := 0\n\t// check the status of containers.\n\tfor idx, container := range pod.Spec.Containers {\n\t\tcontainerStatus := podStatus.FindContainerStatusByName(container.Name)\n\n\t\t// Call internal container post-stop lifecycle hook for any non-running container so that any\n\t\t// allocated cpus are released immediately. If the container is restarted, cpus will be re-allocated\n\t\t// to it.\n\t\tif containerStatus != nil && containerStatus.State != kubecontainer.ContainerStateRunning {\n\t\t\tif err := m.internalLifecycle.PostStopContainer(containerStatus.ID.ID); err != nil {\n\t\t\t\tklog.ErrorS(err, \"Internal container post-stop lifecycle hook failed for container in pod with error\",\n\t\t\t\t\t\"containerName\", container.Name, \"pod\", klog.KObj(pod))\n\t\t\t}\n\t\t}\n\n\t\t// If container does not exist, or is not running, check whether we\n\t\t// need to restart it.\n\t\tif containerStatus == nil || containerStatus.State != kubecontainer.ContainerStateRunning {\n\t\t\tif kubecontainer.ShouldContainerBeRestarted(&container, pod, podStatus) {\n\t\t\t\tklog.V(3).InfoS(\"Container of pod is not in the desired state and shall be started\", \"containerName\", container.Name, \"pod\", klog.KObj(pod))\n\t\t\t\tchanges.ContainersToStart = append(changes.ContainersToStart, idx)\n\t\t\t\tif containerStatus != nil && containerStatus.State == kubecontainer.ContainerStateUnknown {\n\t\t\t\t\t// If container is in unknown state, we don't know whether it\n\t\t\t\t\t// is actually running or not, always try killing it before\n\t\t\t\t\t// restart to avoid having 2 running instances of the same container.\n\t\t\t\t\tchanges.ContainersToKill[containerStatus.ID] = containerToKillInfo{\n\t\t\t\t\t\tname: containerStatus.Name,\n\t\t\t\t\t\tcontainer: &pod.Spec.Containers[idx],\n\t\t\t\t\t\tmessage: fmt.Sprintf(\"Container is in %q state, try killing it before restart\",\n\t\t\t\t\t\t\tcontainerStatus.State),\n\t\t\t\t\t\treason: reasonUnknown,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// The container is running, but kill the container if any of the following condition is met.\n\t\tvar message string\n\t\tvar reason containerKillReason\n\t\trestart := shouldRestartOnFailure(pod)\n\t\t// Do not restart if only the Resources field has changed with InPlacePodVerticalScaling enabled\n\t\tif _, _, changed := containerChanged(&container, containerStatus); changed &&\n\t\t\t(!isInPlacePodVerticalScalingAllowed(pod) ||\n\t\t\t\tkubecontainer.HashContainerWithoutResources(&container) != containerStatus.HashWithoutResources) {\n\t\t\tmessage = fmt.Sprintf(\"Container %s definition changed\", container.Name)\n\t\t\t// Restart regardless of the restart policy because the container\n\t\t\t// spec changed.\n\t\t\trestart = true\n\t\t} else if liveness, found := m.livenessManager.Get(containerStatus.ID); found && liveness == proberesults.Failure {\n\t\t\t// If the container failed the liveness probe, we should kill it.\n\t\t\tmessage = fmt.Sprintf(\"Container %s failed liveness probe\", container.Name)\n\t\t\treason = reasonLivenessProbe\n\t\t} else if startup, found := m.startupManager.Get(containerStatus.ID); found && startup == proberesults.Failure {\n\t\t\t// If the container failed the startup probe, we should kill it.\n\t\t\tmessage = fmt.Sprintf(\"Container %s failed startup probe\", container.Name)\n\t\t\treason = reasonStartupProbe\n\t\t} else if isInPlacePodVerticalScalingAllowed(pod) && !m.computePodResizeAction(pod, idx, containerStatus, &changes) {\n\t\t\t// computePodResizeAction updates 'changes' if resize policy requires restarting this container\n\t\t\tcontinue\n\t\t} else {\n\t\t\t// Keep the container.\n\t\t\tkeepCount++\n\t\t\tcontinue\n\t\t}\n\n\t\t// We need to kill the container, but if we also want to restart the\n\t\t// container afterwards, make the intent clear in the message. Also do\n\t\t// not kill the entire pod since we expect container to be running eventually.\n\t\tif restart {\n\t\t\tmessage = fmt.Sprintf(\"%s, will be restarted\", message)\n\t\t\tchanges.ContainersToStart = append(changes.ContainersToStart, idx)\n\t\t}\n\n\t\tchanges.ContainersToKill[containerStatus.ID] = containerToKillInfo{\n\t\t\tname: containerStatus.Name,\n\t\t\tcontainer: &pod.Spec.Containers[idx],\n\t\t\tmessage: message,\n\t\t\treason: reason,\n\t\t}\n\t\tklog.V(2).InfoS(\"Message for Container of pod\", \"containerName\", container.Name, \"containerStatusID\", containerStatus.ID, \"pod\", klog.KObj(pod), \"containerMessage\", message)\n\t}\n\n\tif keepCount == 0 && len(changes.ContainersToStart) == 0 {\n\t\tchanges.KillPod = true\n\t\t// To prevent the restartable init containers to keep pod alive, we should\n\t\t// not restart them.\n\t\tchanges.InitContainersToStart = nil\n\t}\n\n\treturn changes\n}", "func (t *JobUpgradeTest) Test(f *framework.Framework, done <-chan struct{}, upgrade UpgradeType) {\n\t<-done\n\tBy(\"Ensuring active pods == parallelism\")\n\trunning, err := framework.CheckForAllJobPodsRunning(f.ClientSet, t.namespace, t.job.Name, 2)\n\tExpect(err).NotTo(HaveOccurred())\n\tExpect(running).To(BeTrue())\n}", "func checkPods(podClient v1.CoreV1Interface, logger *log.Logger, filters ...PodPredicate) (bool, error) {\n\tlogger = logging.CreateNewStdLoggerOrUseExistingLogger(logger)\n\n\tlogger.Print(\"Checking that all Pods are running or completed...\")\n\n\tlistOpts := metav1.ListOptions{}\n\tlist, err := podClient.Pods(metav1.NamespaceAll).List(context.TODO(), listOpts)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"error getting pod list: %v\", err)\n\t}\n\n\tif len(list.Items) == 0 {\n\t\treturn false, fmt.Errorf(\"pod list is empty. this should NOT happen\")\n\t}\n\n\tpods := filterPods(list, filters...)\n\n\tlogger.Printf(\"%v pods are currently not running or complete:\", len(pods.Items))\n\tfor _, pod := range pods.Items {\n\t\tif pod.Status.Phase != kubev1.PodPending {\n\t\t\treturn false, fmt.Errorf(\"Pod %s errored: %s - %s\", pod.GetName(), pod.Status.Reason, pod.Status.Message)\n\t\t}\n\t\tlogger.Printf(\"%s is not ready. Phase: %s, Message: %s, Reason: %s\", pod.Name, pod.Status.Phase, pod.Status.Message, pod.Status.Reason)\n\t}\n\n\treturn len(pods.Items) > 0, nil\n}", "func (d *deploymentTester) markUpdatedPodsReady(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tns := d.deployment.Namespace\n\terr := wait.PollImmediate(pollInterval, pollTimeout, func() (bool, error) {\n\t\t// We're done when the deployment is complete\n\t\tif completed, err := d.deploymentComplete(); err != nil {\n\t\t\treturn false, err\n\t\t} else if completed {\n\t\t\treturn true, nil\n\t\t}\n\t\t// Otherwise, mark remaining pods as ready\n\t\tpods, err := d.listUpdatedPods()\n\t\tif err != nil {\n\t\t\td.t.Log(err)\n\t\t\treturn false, nil\n\t\t}\n\t\td.t.Logf(\"%d/%d of deployment pods are created\", len(pods), *d.deployment.Spec.Replicas)\n\t\tfor i := range pods {\n\t\t\tpod := pods[i]\n\t\t\tif podutil.IsPodReady(&pod) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err = markPodReady(d.c, ns, &pod); err != nil {\n\t\t\t\td.t.Logf(\"failed to update Deployment pod %s, will retry later: %v\", pod.Name, err)\n\t\t\t}\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\td.t.Errorf(\"failed to mark updated Deployment pods to ready: %v\", err)\n\t}\n}", "func (c *InstallerController) manageInstallationPods(ctx context.Context, operatorSpec *operatorv1.StaticPodOperatorSpec, originalOperatorStatus *operatorv1.StaticPodOperatorStatus) (bool, time.Duration, error) {\n\toperatorStatus := originalOperatorStatus.DeepCopy()\n\n\tif len(operatorStatus.NodeStatuses) == 0 {\n\t\treturn false, 0, nil\n\t}\n\n\t// start with node which is in worst state (instead of terminating healthy pods first)\n\tstartNode, nodeChoiceReason, err := nodeToStartRevisionWith(ctx, c.getStaticPodState, operatorStatus.NodeStatuses)\n\tif err != nil {\n\t\treturn true, 0, err\n\t}\n\n\t// determine the amount of time to delay before creating the next installer pod. We delay to avoid an LB outage (see godoc on minReadySeconds)\n\trequeueAfter := c.timeToWaitBeforeInstallingNextPod(ctx, operatorStatus.NodeStatuses)\n\tif requeueAfter > 0 {\n\t\treturn true, requeueAfter, nil\n\t}\n\n\tfor l := 0; l < len(operatorStatus.NodeStatuses); l++ {\n\t\ti := (startNode + l) % len(operatorStatus.NodeStatuses)\n\n\t\tvar currNodeState *operatorv1.NodeStatus\n\t\tvar prevNodeState *operatorv1.NodeStatus\n\t\tcurrNodeState = &operatorStatus.NodeStatuses[i]\n\t\tif l > 0 {\n\t\t\tprev := (startNode + l - 1) % len(operatorStatus.NodeStatuses)\n\t\t\tprevNodeState = &operatorStatus.NodeStatuses[prev]\n\t\t\tnodeChoiceReason = fmt.Sprintf(\"node %s is the next node in the line\", currNodeState.NodeName)\n\t\t}\n\n\t\t// if we are in a transition, check to see whether our installer pod completed\n\t\tif currNodeState.TargetRevision > currNodeState.CurrentRevision {\n\t\t\tif operatorStatus.LatestAvailableRevision > currNodeState.TargetRevision {\n\t\t\t\t// no backoff if new revision is pending\n\t\t\t} else {\n\t\t\t\tif currNodeState.LastFailedRevision == currNodeState.TargetRevision && currNodeState.LastFailedTime != nil && !currNodeState.LastFailedTime.IsZero() {\n\t\t\t\t\tvar delay time.Duration\n\t\t\t\t\tif currNodeState.LastFailedReason == nodeStatusOperandFailedFallbackReason {\n\t\t\t\t\t\tdelay = c.fallbackBackOff(currNodeState.LastFallbackCount)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdelay = c.installerBackOff(currNodeState.LastFailedCount)\n\t\t\t\t\t}\n\t\t\t\t\tearliestRetry := currNodeState.LastFailedTime.Add(delay)\n\t\t\t\t\tif !c.now().After(earliestRetry) {\n\t\t\t\t\t\tklog.V(4).Infof(\"Backing off node %s installer retry %d until %v\", currNodeState.NodeName, currNodeState.LastFailedCount+1, earliestRetry)\n\t\t\t\t\t\treturn true, earliestRetry.Sub(c.now()), nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err := c.ensureInstallerPod(ctx, operatorSpec, currNodeState); err != nil {\n\t\t\t\t\tc.eventRecorder.Warningf(\"InstallerPodFailed\", \"Failed to create installer pod for revision %d count %d on node %q: %v\",\n\t\t\t\t\t\tcurrNodeState.TargetRevision, currNodeState.LastFailedCount, currNodeState.NodeName, err)\n\t\t\t\t\t// if a newer revision is pending, continue, so we retry later with the latest available revision\n\t\t\t\t\tif !(operatorStatus.LatestAvailableRevision > currNodeState.TargetRevision) {\n\t\t\t\t\t\treturn true, 0, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnewCurrNodeState, _, reason, err := c.newNodeStateForInstallInProgress(ctx, currNodeState, operatorStatus.LatestAvailableRevision)\n\t\t\tif err != nil {\n\t\t\t\treturn true, 0, err\n\t\t\t}\n\t\t\tif newCurrNodeState.LastFailedReason == nodeStatusInstalledFailedReason && newCurrNodeState.LastFailedCount != currNodeState.LastFailedCount {\n\t\t\t\tklog.Infof(\"Will retry %q for revision %d for the %s time because %s\", currNodeState.NodeName, currNodeState.TargetRevision, nthTimeOr1st(newCurrNodeState.LastFailedCount), reason)\n\t\t\t}\n\t\t\tif newCurrNodeState.LastFailedReason == nodeStatusOperandFailedFallbackReason && newCurrNodeState.LastFallbackCount != currNodeState.LastFallbackCount {\n\t\t\t\tklog.Infof(\"Will fallback %q for revision %d to last-known-good revision for the %s time because %s\", currNodeState.NodeName, currNodeState.TargetRevision, nthTimeOr1st(newCurrNodeState.LastFallbackCount), reason)\n\t\t\t}\n\n\t\t\t// if we make a change to this status, we want to write it out to the API before we commence work on the next node.\n\t\t\t// it's an extra write/read, but it makes the state debuggable from outside this process\n\t\t\tif !equality.Semantic.DeepEqual(newCurrNodeState, currNodeState) {\n\t\t\t\tklog.Infof(\"%q moving to %v because %s\", currNodeState.NodeName, spew.Sdump(*newCurrNodeState), reason)\n\t\t\t\t_, updated, updateError := v1helpers.UpdateStaticPodStatus(ctx, c.operatorClient, setNodeStatusFn(newCurrNodeState), setAvailableProgressingNodeInstallerFailingConditions)\n\t\t\t\tif updateError != nil {\n\t\t\t\t\treturn false, 0, updateError\n\t\t\t\t} else if updated && currNodeState.CurrentRevision != newCurrNodeState.CurrentRevision {\n\t\t\t\t\tc.eventRecorder.Eventf(\"NodeCurrentRevisionChanged\", \"Updated node %q from revision %d to %d because %s\", currNodeState.NodeName,\n\t\t\t\t\t\tcurrNodeState.CurrentRevision, newCurrNodeState.CurrentRevision, reason)\n\t\t\t\t}\n\n\t\t\t\treturn false, 0, nil // no requeue because UpdateStaticPodStatus triggers an external event anyway\n\t\t\t}\n\n\t\t\tklog.V(2).Infof(\"%q is in transition to %d, but has not made progress because %s\", currNodeState.NodeName, currNodeState.TargetRevision, reasonWithBlame(reason))\n\t\t\treturn false, 0, nil\n\t\t}\n\n\t\t// here we are not in transition, i.e. there is no install pod running\n\n\t\trevisionToStart := c.getRevisionToStart(currNodeState, prevNodeState, operatorStatus)\n\t\tif revisionToStart == 0 {\n\t\t\tklog.V(4).Infof(\"%s, but node %s does not need update\", nodeChoiceReason, currNodeState.NodeName)\n\t\t\tcontinue\n\t\t}\n\n\t\tklog.Infof(\"%s and needs new revision %d\", nodeChoiceReason, revisionToStart)\n\n\t\tnewCurrNodeState := currNodeState.DeepCopy()\n\t\tnewCurrNodeState.TargetRevision = revisionToStart\n\n\t\t// if we make a change to this status, we want to write it out to the API before we commence work on the next node.\n\t\t// it's an extra write/read, but it makes the state debuggable from outside this process\n\t\tif !equality.Semantic.DeepEqual(newCurrNodeState, currNodeState) {\n\t\t\tklog.Infof(\"%q moving to %v\", currNodeState.NodeName, spew.Sdump(*newCurrNodeState))\n\t\t\tif _, updated, updateError := v1helpers.UpdateStaticPodStatus(ctx, c.operatorClient, setNodeStatusFn(newCurrNodeState), setAvailableProgressingNodeInstallerFailingConditions); updateError != nil {\n\t\t\t\treturn false, 0, updateError\n\t\t\t} else if updated && currNodeState.TargetRevision != newCurrNodeState.TargetRevision && newCurrNodeState.TargetRevision != 0 {\n\t\t\t\tc.eventRecorder.Eventf(\"NodeTargetRevisionChanged\", \"Updating node %q from revision %d to %d because %s\", currNodeState.NodeName,\n\t\t\t\t\tcurrNodeState.CurrentRevision, newCurrNodeState.TargetRevision, nodeChoiceReason)\n\t\t\t}\n\n\t\t\treturn false, 0, nil // no requeue because UpdateStaticPodStatus triggers an external event anyway\n\t\t}\n\t\tbreak\n\t}\n\n\treturn false, 0, nil\n}", "func TestSidecarsAndLabelsCheckOneValidPod(t *testing.T) {\n\tfakePodList := []v1.Pod{\n\t\tbuildPodWith(\"myPodWithSidecar\", true, true, true),\n\t}\n\n\tchecker := PodChecker{Pods: fakePodList}\n\tvalidations := checker.Check()\n\n\tassert.Equal(t, 1, len(validations))\n\tvalidation, ok := validations[models.IstioValidationKey{\"pod\", \"myPodWithSidecar\"}]\n\tassert.True(t, ok)\n\tassert.True(t, validation.Valid)\n\tassert.Equal(t, 0, len(validation.Checks))\n}", "func containerGCTest(f *framework.Framework, test testRun) {\n\tvar runtime internalapi.RuntimeService\n\tginkgo.BeforeEach(func() {\n\t\tvar err error\n\t\truntime, _, err = getCRIClient()\n\t\tframework.ExpectNoError(err)\n\t})\n\tfor _, pod := range test.testPods {\n\t\t// Initialize the getContainerNames function to use CRI runtime client.\n\t\tpod.getContainerNames = func() ([]string, error) {\n\t\t\trelevantContainers := []string{}\n\t\t\tcontainers, err := runtime.ListContainers(context.Background(), &runtimeapi.ContainerFilter{\n\t\t\t\tLabelSelector: map[string]string{\n\t\t\t\t\ttypes.KubernetesPodNameLabel: pod.podName,\n\t\t\t\t\ttypes.KubernetesPodNamespaceLabel: f.Namespace.Name,\n\t\t\t\t},\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn relevantContainers, err\n\t\t\t}\n\t\t\tfor _, container := range containers {\n\t\t\t\trelevantContainers = append(relevantContainers, container.Labels[types.KubernetesContainerNameLabel])\n\t\t\t}\n\t\t\treturn relevantContainers, nil\n\t\t}\n\t}\n\n\tginkgo.Context(fmt.Sprintf(\"Garbage Collection Test: %s\", test.testName), func() {\n\t\tginkgo.BeforeEach(func(ctx context.Context) {\n\t\t\trealPods := getPods(test.testPods)\n\t\t\te2epod.NewPodClient(f).CreateBatch(ctx, realPods)\n\t\t\tginkgo.By(\"Making sure all containers restart the specified number of times\")\n\t\t\tgomega.Eventually(ctx, func(ctx context.Context) error {\n\t\t\t\tfor _, podSpec := range test.testPods {\n\t\t\t\t\terr := verifyPodRestartCount(ctx, f, podSpec.podName, podSpec.numContainers, podSpec.restartCount)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}, setupDuration, runtimePollInterval).Should(gomega.BeNil())\n\t\t})\n\n\t\tginkgo.It(\"Should eventually garbage collect containers when we exceed the number of dead containers per container\", func(ctx context.Context) {\n\t\t\ttotalContainers := 0\n\t\t\tfor _, pod := range test.testPods {\n\t\t\t\ttotalContainers += pod.numContainers*2 + 1\n\t\t\t}\n\t\t\tgomega.Eventually(ctx, func() error {\n\t\t\t\ttotal := 0\n\t\t\t\tfor _, pod := range test.testPods {\n\t\t\t\t\tcontainerNames, err := pod.getContainerNames()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\ttotal += len(containerNames)\n\t\t\t\t\t// Check maxPerPodContainer for each container in the pod\n\t\t\t\t\tfor i := 0; i < pod.numContainers; i++ {\n\t\t\t\t\t\tcontainerCount := 0\n\t\t\t\t\t\tfor _, containerName := range containerNames {\n\t\t\t\t\t\t\tif containerName == pod.getContainerName(i) {\n\t\t\t\t\t\t\t\tcontainerCount++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif containerCount > maxPerPodContainer+1 {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"expected number of copies of container: %s, to be <= maxPerPodContainer: %d; list of containers: %v\",\n\t\t\t\t\t\t\t\tpod.getContainerName(i), maxPerPodContainer, containerNames)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//Check maxTotalContainers. Currently, the default is -1, so this will never happen until we can configure maxTotalContainers\n\t\t\t\tif maxTotalContainers > 0 && totalContainers <= maxTotalContainers && total > maxTotalContainers {\n\t\t\t\t\treturn fmt.Errorf(\"expected total number of containers: %v, to be <= maxTotalContainers: %v\", total, maxTotalContainers)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}, garbageCollectDuration, runtimePollInterval).Should(gomega.BeNil())\n\n\t\t\tif maxPerPodContainer >= 2 && maxTotalContainers < 0 { // make sure constraints wouldn't make us gc old containers\n\t\t\t\tginkgo.By(\"Making sure the kubelet consistently keeps around an extra copy of each container.\")\n\t\t\t\tgomega.Consistently(ctx, func() error {\n\t\t\t\t\tfor _, pod := range test.testPods {\n\t\t\t\t\t\tcontainerNames, err := pod.getContainerNames()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor i := 0; i < pod.numContainers; i++ {\n\t\t\t\t\t\t\tcontainerCount := 0\n\t\t\t\t\t\t\tfor _, containerName := range containerNames {\n\t\t\t\t\t\t\t\tif containerName == pod.getContainerName(i) {\n\t\t\t\t\t\t\t\t\tcontainerCount++\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif pod.restartCount > 0 && containerCount < maxPerPodContainer+1 {\n\t\t\t\t\t\t\t\treturn fmt.Errorf(\"expected pod %v to have extra copies of old containers\", pod.podName)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}, garbageCollectDuration, runtimePollInterval).Should(gomega.BeNil())\n\t\t\t}\n\t\t})\n\n\t\tginkgo.AfterEach(func(ctx context.Context) {\n\t\t\tfor _, pod := range test.testPods {\n\t\t\t\tginkgo.By(fmt.Sprintf(\"Deleting Pod %v\", pod.podName))\n\t\t\t\te2epod.NewPodClient(f).DeleteSync(ctx, pod.podName, metav1.DeleteOptions{}, e2epod.DefaultPodDeletionTimeout)\n\t\t\t}\n\n\t\t\tginkgo.By(\"Making sure all containers get cleaned up\")\n\t\t\tgomega.Eventually(ctx, func() error {\n\t\t\t\tfor _, pod := range test.testPods {\n\t\t\t\t\tcontainerNames, err := pod.getContainerNames()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif len(containerNames) > 0 {\n\t\t\t\t\t\treturn fmt.Errorf(\"%v containers still remain\", containerNames)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}, garbageCollectDuration, runtimePollInterval).Should(gomega.BeNil())\n\n\t\t\tif ginkgo.CurrentSpecReport().Failed() && framework.TestContext.DumpLogsOnFailure {\n\t\t\t\tlogNodeEvents(ctx, f)\n\t\t\t\tlogPodEvents(ctx, f)\n\t\t\t}\n\t\t})\n\t})\n}", "func (mock *PersistentVolumeClaimInterfaceMock) ControllerCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tlockPersistentVolumeClaimInterfaceMockController.RLock()\n\tcalls = mock.calls.Controller\n\tlockPersistentVolumeClaimInterfaceMockController.RUnlock()\n\treturn calls\n}", "func TestGetConcurrentAPIEndpoints(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tname string\n\t\tddURL, eventsDDURL, apiKey string\n\t\tadditionalEndpoints map[string][]string\n\t\tadditionalEventsEndpoints map[string][]string\n\t\texpectedEndpoints []apicfg.Endpoint\n\t\texpectedEventsEndpoints []apicfg.Endpoint\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\tapiKey: \"test\",\n\t\t\texpectedEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEndpoint),\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEventsEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEventsEndpoint),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set only process endpoint\",\n\t\t\tddURL: \"https://process.datadoghq.eu\",\n\t\t\tapiKey: \"test\",\n\t\t\texpectedEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(\"https://process.datadoghq.eu\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEventsEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEventsEndpoint),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"set only process-events endpoint\",\n\t\t\teventsDDURL: \"https://process-events.datadoghq.eu\",\n\t\t\tapiKey: \"test\",\n\t\t\texpectedEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEndpoint),\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEventsEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t\tEndpoint: mkurl(\"https://process-events.datadoghq.eu\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiple eps\",\n\t\t\tapiKey: \"test\",\n\t\t\tadditionalEndpoints: map[string][]string{\n\t\t\t\t\"https://mock.datadoghq.com\": {\n\t\t\t\t\t\"key1\",\n\t\t\t\t\t\"key2\",\n\t\t\t\t},\n\t\t\t\t\"https://mock2.datadoghq.com\": {\n\t\t\t\t\t\"key3\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tadditionalEventsEndpoints: map[string][]string{\n\t\t\t\t\"https://mock-events.datadoghq.com\": {\n\t\t\t\t\t\"key2\",\n\t\t\t\t},\n\t\t\t\t\"https://mock2-events.datadoghq.com\": {\n\t\t\t\t\t\"key3\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEndpoint),\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key1\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key2\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock2.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key3\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedEventsEndpoints: []apicfg.Endpoint{\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(config.DefaultProcessEventsEndpoint),\n\t\t\t\t\tAPIKey: \"test\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock-events.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key2\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tEndpoint: mkurl(\"https://mock2-events.datadoghq.com\"),\n\t\t\t\t\tAPIKey: \"key3\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tcfg := config.Mock(t)\n\t\t\tcfg.Set(\"api_key\", tc.apiKey)\n\t\t\tif tc.ddURL != \"\" {\n\t\t\t\tcfg.Set(\"process_config.process_dd_url\", tc.ddURL)\n\t\t\t}\n\n\t\t\tif tc.eventsDDURL != \"\" {\n\t\t\t\tcfg.Set(\"process_config.events_dd_url\", tc.eventsDDURL)\n\t\t\t}\n\n\t\t\tif tc.additionalEndpoints != nil {\n\t\t\t\tcfg.Set(\"process_config.additional_endpoints\", tc.additionalEndpoints)\n\t\t\t}\n\n\t\t\tif tc.additionalEventsEndpoints != nil {\n\t\t\t\tcfg.Set(\"process_config.events_additional_endpoints\", tc.additionalEventsEndpoints)\n\t\t\t}\n\n\t\t\teps, err := endpoint.GetAPIEndpoints(cfg)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.ElementsMatch(t, tc.expectedEndpoints, eps)\n\n\t\t\teventsEps, err := endpoint.GetEventsAPIEndpoints(cfg)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.ElementsMatch(t, tc.expectedEventsEndpoints, eventsEps)\n\t\t})\n\t}\n}", "func TestHandle_updateOk(t *testing.T) {\n\tvar (\n\t\tconfig *deployapi.DeploymentConfig\n\t\tdeployed *kapi.ReplicationController\n\t\texistingDeployments *kapi.ReplicationControllerList\n\t)\n\n\tcontroller := &DeploymentConfigController{\n\t\tmakeDeployment: func(config *deployapi.DeploymentConfig) (*kapi.ReplicationController, error) {\n\t\t\treturn deployutil.MakeDeployment(config, api.Codec)\n\t\t},\n\t\tdeploymentClient: &deploymentClientImpl{\n\t\t\tcreateDeploymentFunc: func(namespace string, deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\t\tdeployed = deployment\n\t\t\t\treturn deployment, nil\n\t\t\t},\n\t\t\tlistDeploymentsForConfigFunc: func(namespace, configName string) (*kapi.ReplicationControllerList, error) {\n\t\t\t\treturn existingDeployments, nil\n\t\t\t},\n\t\t\tupdateDeploymentFunc: func(namespace string, deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\t\tt.Fatalf(\"unexpected update call with deployment %v\", deployment)\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t\trecorder: &record.FakeRecorder{},\n\t}\n\n\ttype existing struct {\n\t\tversion int\n\t\treplicas int\n\t\tstatus deployapi.DeploymentStatus\n\t}\n\n\ttype scenario struct {\n\t\tversion int\n\t\texpectedReplicas int\n\t\texisting []existing\n\t}\n\n\tscenarios := []scenario{\n\t\t{1, 1, []existing{}},\n\t\t{2, 1, []existing{\n\t\t\t{1, 1, deployapi.DeploymentStatusComplete},\n\t\t}},\n\t\t{3, 4, []existing{\n\t\t\t{1, 0, deployapi.DeploymentStatusComplete},\n\t\t\t{2, 4, deployapi.DeploymentStatusComplete},\n\t\t}},\n\t\t{3, 4, []existing{\n\t\t\t{1, 4, deployapi.DeploymentStatusComplete},\n\t\t\t{2, 1, deployapi.DeploymentStatusFailed},\n\t\t}},\n\t\t{4, 2, []existing{\n\t\t\t{1, 0, deployapi.DeploymentStatusComplete},\n\t\t\t{2, 0, deployapi.DeploymentStatusFailed},\n\t\t\t{3, 2, deployapi.DeploymentStatusComplete},\n\t\t}},\n\t\t// Scramble the order of the previous to ensure we still get it right.\n\t\t{4, 2, []existing{\n\t\t\t{2, 0, deployapi.DeploymentStatusFailed},\n\t\t\t{3, 2, deployapi.DeploymentStatusComplete},\n\t\t\t{1, 0, deployapi.DeploymentStatusComplete},\n\t\t}},\n\t}\n\n\tfor _, scenario := range scenarios {\n\t\tdeployed = nil\n\t\tconfig = deploytest.OkDeploymentConfig(scenario.version)\n\t\texistingDeployments = &kapi.ReplicationControllerList{}\n\t\tfor _, e := range scenario.existing {\n\t\t\td, _ := deployutil.MakeDeployment(deploytest.OkDeploymentConfig(e.version), api.Codec)\n\t\t\td.Spec.Replicas = e.replicas\n\t\t\td.Annotations[deployapi.DeploymentStatusAnnotation] = string(e.status)\n\t\t\texistingDeployments.Items = append(existingDeployments.Items, *d)\n\t\t}\n\t\terr := controller.Handle(config)\n\n\t\tif deployed == nil {\n\t\t\tt.Fatalf(\"expected a deployment\")\n\t\t}\n\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t\t}\n\n\t\tdesired, hasDesired := deployutil.DeploymentDesiredReplicas(deployed)\n\t\tif !hasDesired {\n\t\t\tt.Fatalf(\"expected desired replicas\")\n\t\t}\n\t\tif e, a := scenario.expectedReplicas, desired; e != a {\n\t\t\tt.Errorf(\"expected desired replicas %d, got %d\", e, a)\n\t\t}\n\t}\n}", "func (suite *PouchRestartSuite) TestPouchRestartMultiContainers(c *check.C) {\n\tcontainernames := []string{\"TestPouchRestartMultiContainer-1\", \"TestPouchRestartMultiContainer-2\"}\n\tfor _, name := range containernames {\n\t\tres := command.PouchRun(\"run\", \"-d\", \"--name\", name, busyboxImage, \"top\")\n\t\tdefer DelContainerForceMultyTime(c, name)\n\t\tres.Assert(c, icmd.Success)\n\t}\n\n\tres := command.PouchRun(\"restart\", \"-t\", \"1\", containernames[0], containernames[1])\n\tres.Assert(c, icmd.Success)\n\n\tif out := res.Combined(); !strings.Contains(out, containernames[0]) || !strings.Contains(out, containernames[1]) {\n\t\tc.Fatalf(\"unexpected output: %s, expected: %s\\n%s\", out, containernames[0], containernames[1])\n\t}\n}", "func (suite *PouchRestartSuite) TestPouchRestartMultiContainers(c *check.C) {\n\tcontainernames := []string{\"TestPouchRestartMultiContainer-1\", \"TestPouchRestartMultiContainer-2\"}\n\tfor _, name := range containernames {\n\t\tres := command.PouchRun(\"run\", \"-d\", \"--name\", name, busyboxImage, \"top\")\n\t\tdefer DelContainerForceMultyTime(c, name)\n\t\tres.Assert(c, icmd.Success)\n\t}\n\n\tres := command.PouchRun(\"restart\", \"-t\", \"1\", containernames[0], containernames[1])\n\tres.Assert(c, icmd.Success)\n\n\tif out := res.Combined(); !strings.Contains(out, containernames[0]) || !strings.Contains(out, containernames[1]) {\n\t\tc.Fatalf(\"unexpected output: %s, expected: %s\\n%s\", out, containernames[0], containernames[1])\n\t}\n}", "func TestCreate(t *testing.T) {\n\t// set up fake web server\n\tr := gin.Default()\n\tbuilds.Mount(r)\n\n\t// test artifacts send to callback URL\n\tr.POST(\"/callback\", func(c *gin.Context) {\n\t\tr, _, err := c.Request.FormFile(\"file\")\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tres, err := testhelper.ShouldIncludeFileInTar(r, \"app\")\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif !res {\n\t\t\tt.Error(\"artifact should be found\")\n\t\t}\n\t})\n\n\t// run web server\n\ts := httptest.NewServer(r)\n\tdefer s.Close()\n\n\t// prepare jobqueue\n\tgo jobqueue.Wait()\n\tdefer jobqueue.Close()\n\n\t// send request\n\tbuild, err := controller_helper.Create(s.URL, \"./example/app.tar\", s.URL+\"/callback\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// wait for finishing build\n\texitCode := make(chan int, 1)\n\tgo func() {\n\t\tfor {\n\t\t\tif res, err := controller_helper.Show(s.URL, build.Id); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t} else {\n\t\t\t\tif res.Job.Finished {\n\t\t\t\t\texitCode <- res.Job.ExitCode\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\ttime.Sleep(200 * time.Millisecond)\n\t\t}\n\t}()\n\n\t// timeout after three seconds\n\tselect {\n\tcase c := <-exitCode:\n\t\tif c != 0 {\n\t\t\tt.Fatal(c)\n\t\t}\n\tcase <-time.After(3 * time.Second):\n\t\tt.Fatal(\"the build should be finished in a few second\")\n\t}\n\n\treq, err := testhelper.Get(s.URL+\"/builds/\"+build.Id+\"/log.txt\", map[string]string{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tc := http.Client{}\n\tres, err := c.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\n\tif b, err := ioutil.ReadAll(res.Body); err != nil {\n\t\tt.Fatal(err)\n\t} else if !strings.Contains(string(b), \"make\") {\n\t\tt.Fatal(\"example build shuold start with make command\")\n\t}\n}", "func TestSidecarsCheckNoPods(t *testing.T) {\n\tchecker := PodChecker{Pods: []v1.Pod{}}\n\tresult := checker.Check()\n\n\tassert.Equal(t, 0, len(result))\n}", "func ChaosPodStatus(experimentsDetails *types.ExperimentDetails, clients environment.ClientSets) error {\n\n\tfor count := 0; count < (experimentsDetails.Duration / experimentsDetails.Delay); count++ {\n\n\t\tchaosEngine, err := clients.LitmusClient.ChaosEngines(experimentsDetails.ChaosNamespace).Get(experimentsDetails.EngineName, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn errors.Errorf(\"fail to get the chaosengine %v err: %v\", experimentsDetails.EngineName, err)\n\t\t}\n\t\tif len(chaosEngine.Status.Experiments) == 0 {\n\t\t\ttime.Sleep(time.Duration(experimentsDetails.Delay) * time.Second)\n\t\t\tlog.Info(\"[Status]: Experiment initializing\")\n\t\t\tif count == ((experimentsDetails.Duration / experimentsDetails.Delay) - 1) {\n\t\t\t\treturn errors.Errorf(\"Experiment pod fail to initialise, due to %v\", err)\n\t\t\t}\n\n\t\t} else if len(chaosEngine.Status.Experiments[0].ExpPod) == 0 {\n\t\t\ttime.Sleep(time.Duration(experimentsDetails.Delay) * time.Second)\n\t\t\tif count == ((experimentsDetails.Duration / experimentsDetails.Delay) - 1) {\n\t\t\t\treturn errors.Errorf(\"Experiment pod fails to create, due to %v\", err)\n\t\t\t}\n\t\t} else if chaosEngine.Status.Experiments[0].Status != \"Running\" {\n\t\t\ttime.Sleep(time.Duration(experimentsDetails.Delay) * time.Second)\n\t\t\tlog.Infof(\"[Status]: Currently, the Chaos Pod is in %v state, Please Wait...\", chaosEngine.Status.Experiments[0].Status)\n\t\t\tif count == ((experimentsDetails.Duration / experimentsDetails.Delay) - 1) {\n\t\t\t\treturn errors.Errorf(\"Experiment pod fails to get in running state, due to %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tlog.Info(\"[Status]: Chaos pod initiated successfully\")\n\treturn nil\n}", "func (mock *NamespacedCertificateInterfaceMock) ControllerCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tlockNamespacedCertificateInterfaceMockController.RLock()\n\tcalls = mock.calls.Controller\n\tlockNamespacedCertificateInterfaceMockController.RUnlock()\n\treturn calls\n}", "func runMultisyncTests(t *testing.T, ctx context.Context, tests []controllerTest, storageClasses []*storage.StorageClass, defaultStorageClass string) {\n\tlogger := klog.FromContext(ctx)\n\trun := func(t *testing.T, test controllerTest) {\n\t\tlogger.V(4).Info(\"Starting multisync test\", \"testName\", test.name)\n\n\t\t// Initialize the controller\n\t\tclient := &fake.Clientset{}\n\t\tctrl, err := newTestController(ctx, client, nil, true)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %q construct persistent volume failed: %v\", test.name, err)\n\t\t}\n\n\t\t// Inject classes into controller via a custom lister.\n\t\tindexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})\n\t\tfor _, class := range storageClasses {\n\t\t\tindexer.Add(class)\n\t\t}\n\t\tctrl.classLister = storagelisters.NewStorageClassLister(indexer)\n\n\t\treactor := newVolumeReactor(ctx, client, ctrl, nil, nil, test.errors)\n\t\tfor _, claim := range test.initialClaims {\n\t\t\tctrl.claims.Add(claim)\n\t\t}\n\t\tfor _, volume := range test.initialVolumes {\n\t\t\tctrl.volumes.store.Add(volume)\n\t\t}\n\t\treactor.AddClaims(test.initialClaims)\n\t\treactor.AddVolumes(test.initialVolumes)\n\n\t\t// Run the tested function\n\t\terr = test.test(ctrl, reactor.VolumeReactor, test)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test %q failed: %v\", test.name, err)\n\t\t}\n\n\t\t// Simulate any \"changed\" events and \"periodical sync\" until we reach a\n\t\t// stable state.\n\t\tfirstSync := true\n\t\tcounter := 0\n\t\tfor {\n\t\t\tcounter++\n\t\t\tlogger.V(4).Info(\"Test\", \"testName\", test.name, \"iteration\", counter)\n\n\t\t\tif counter > 100 {\n\t\t\t\tt.Errorf(\"Test %q failed: too many iterations\", test.name)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Wait for all goroutines to finish\n\t\t\treactor.waitForIdle()\n\n\t\t\tobj := reactor.PopChange(ctx)\n\t\t\tif obj == nil {\n\t\t\t\t// Nothing was changed, should we exit?\n\t\t\t\tif firstSync || reactor.GetChangeCount() > 0 {\n\t\t\t\t\t// There were some changes after the last \"periodic sync\".\n\t\t\t\t\t// Simulate \"periodic sync\" of everything (until it produces\n\t\t\t\t\t// no changes).\n\t\t\t\t\tfirstSync = false\n\t\t\t\t\tlogger.V(4).Info(\"Test simulating periodical sync of all claims and volumes\", \"testName\", test.name)\n\t\t\t\t\treactor.SyncAll()\n\t\t\t\t} else {\n\t\t\t\t\t// Last sync did not produce any updates, the test reached\n\t\t\t\t\t// stable state -> finish.\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\t// waiting here cools down exponential backoff\n\t\t\ttime.Sleep(600 * time.Millisecond)\n\n\t\t\t// There were some changes, process them\n\t\t\tswitch obj.(type) {\n\t\t\tcase *v1.PersistentVolumeClaim:\n\t\t\t\tclaim := obj.(*v1.PersistentVolumeClaim)\n\t\t\t\t// Simulate \"claim updated\" event\n\t\t\t\tctrl.claims.Update(claim)\n\t\t\t\terr = ctrl.syncClaim(context.TODO(), claim)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == pvtesting.ErrVersionConflict {\n\t\t\t\t\t\t// Ignore version errors\n\t\t\t\t\t\tlogger.V(4).Info(\"Test intentionally ignores version error\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\tt.Errorf(\"Error calling syncClaim: %v\", err)\n\t\t\t\t\t\t// Finish the loop on the first error\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Process generated changes\n\t\t\t\tcontinue\n\t\t\tcase *v1.PersistentVolume:\n\t\t\t\tvolume := obj.(*v1.PersistentVolume)\n\t\t\t\t// Simulate \"volume updated\" event\n\t\t\t\tctrl.volumes.store.Update(volume)\n\t\t\t\terr = ctrl.syncVolume(context.TODO(), volume)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == pvtesting.ErrVersionConflict {\n\t\t\t\t\t\t// Ignore version errors\n\t\t\t\t\t\tlogger.V(4).Info(\"Test intentionally ignores version error\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\tt.Errorf(\"Error calling syncVolume: %v\", err)\n\t\t\t\t\t\t// Finish the loop on the first error\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Process generated changes\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tevaluateTestResults(ctx, ctrl, reactor.VolumeReactor, test, t)\n\t\tlogger.V(4).Info(\"Test finished after iterations\", \"testName\", test.name, \"iterations\", counter)\n\t}\n\n\tfor _, test := range tests {\n\t\ttest := test\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\trun(t, test)\n\t\t})\n\t}\n}", "func TestRunConsulDeploymentsPackageTests(t *testing.T) {\n\tcfg := testutil.SetupTestConfig(t)\n\tsrv, client := testutil.NewTestConsulInstance(t, &cfg)\n\tdefer func() {\n\t\tsrv.Stop()\n\t\tos.RemoveAll(cfg.WorkingDirectory)\n\t}()\n\n\tt.Run(\"groupDeployments\", func(t *testing.T) {\n\t\tt.Run(\"testArtifacts\", func(t *testing.T) {\n\t\t\ttestArtifacts(t, srv)\n\t\t})\n\t\tt.Run(\"testCapabilities\", func(t *testing.T) {\n\t\t\ttestCapabilities(t, srv)\n\t\t})\n\t\tt.Run(\"testDefinitionStore\", func(t *testing.T) {\n\t\t\ttestDefinitionStore(t)\n\t\t})\n\t\tt.Run(\"testDeploymentNodes\", func(t *testing.T) {\n\t\t\ttestDeploymentNodes(t, srv)\n\t\t})\n\t\tt.Run(\"testRequirements\", func(t *testing.T) {\n\t\t\ttestRequirements(t, srv)\n\t\t})\n\t\tt.Run(\"testResolver\", func(t *testing.T) {\n\t\t\ttestResolver(t)\n\t\t})\n\t\tt.Run(\"testGetTypePropertyDataType\", func(t *testing.T) {\n\t\t\ttestGetTypePropertyDataType(t)\n\t\t})\n\t\tt.Run(\"testGetNestedDataType\", func(t *testing.T) {\n\t\t\ttestGetNestedDataType(t)\n\t\t})\n\t\tt.Run(\"testReadComplexVA\", func(t *testing.T) {\n\t\t\ttestReadComplexVA(t)\n\t\t})\n\t\tt.Run(\"testIssueGetEmptyPropRel\", func(t *testing.T) {\n\t\t\ttestIssueGetEmptyPropRel(t)\n\t\t})\n\t\tt.Run(\"testRelationshipWorkflow\", func(t *testing.T) {\n\t\t\ttestRelationshipWorkflow(t)\n\t\t})\n\t\tt.Run(\"testGlobalInputs\", func(t *testing.T) {\n\t\t\ttestGlobalInputs(t)\n\t\t})\n\t\tt.Run(\"testInlineWorkflow\", func(t *testing.T) {\n\t\t\ttestInlineWorkflow(t)\n\t\t})\n\t\tt.Run(\"testDeleteWorkflow\", func(t *testing.T) {\n\t\t\ttestDeleteWorkflow(t)\n\t\t})\n\t\tt.Run(\"testCheckCycleInNestedWorkflows\", func(t *testing.T) {\n\t\t\ttestCheckCycleInNestedWorkflows(t)\n\t\t})\n\t\tt.Run(\"testGetCapabilityProperties\", func(t *testing.T) {\n\t\t\ttestGetCapabilityProperties(t)\n\t\t})\n\t\tt.Run(\"testSubstitutionServiceCapabilityMappings\", func(t *testing.T) {\n\t\t\ttestSubstitutionServiceCapabilityMappings(t)\n\t\t})\n\t\tt.Run(\"testSubstitutionServiceRequirementMappings\", func(t *testing.T) {\n\t\t\ttestSubstitutionServiceRequirementMappings(t)\n\t\t})\n\t\tt.Run(\"testSubstitutionClientDirective\", func(t *testing.T) {\n\t\t\ttestSubstitutionClientDirective(t)\n\t\t})\n\t\tt.Run(\"testSubstitutionClientServiceInstance\", func(t *testing.T) {\n\t\t\ttestSubstitutionClientServiceInstance(t)\n\t\t})\n\t\tt.Run(\"TestOperationImplementationArtifact\", func(t *testing.T) {\n\t\t\ttestOperationImplementationArtifact(t)\n\t\t})\n\t\tt.Run(\"TestOperationHost\", func(t *testing.T) {\n\t\t\ttestOperationHost(t)\n\t\t})\n\t\tt.Run(\"testIssueGetEmptyPropOnRelationship\", func(t *testing.T) {\n\t\t\ttestIssueGetEmptyPropOnRelationship(t)\n\t\t})\n\n\t\tt.Run(\"testTopologyUpdate\", func(t *testing.T) {\n\t\t\ttestTopologyUpdate(t)\n\t\t})\n\t\tt.Run(\"testTopologyBadUpdate\", func(t *testing.T) {\n\t\t\ttestTopologyBadUpdate(t)\n\t\t})\n\t\tt.Run(\"testRepositories\", func(t *testing.T) {\n\t\t\ttestRepositories(t)\n\t\t})\n\t\tt.Run(\"testPurgedDeployments\", func(t *testing.T) {\n\t\t\ttestPurgedDeployments(t, client)\n\t\t})\n\t\tt.Run(\"testDeleteDeployment\", func(t *testing.T) {\n\t\t\ttestDeleteDeployment(t)\n\t\t})\n\t\tt.Run(\"testDeleteInstance\", func(t *testing.T) {\n\t\t\ttestDeleteInstance(t)\n\t\t})\n\t\tt.Run(\"testDeleteAllInstances\", func(t *testing.T) {\n\t\t\ttestDeleteAllInstances(t)\n\t\t})\n\t\tt.Run(\"testDeleteRelationshipInstance\", func(t *testing.T) {\n\t\t\ttestDeleteRelationshipInstance(t)\n\t\t})\n\n\t\tt.Run(\"testResolveAttributeMapping\", func(t *testing.T) {\n\t\t\ttestResolveAttributeMapping(t)\n\t\t})\n\n\t})\n\n\tt.Run(\"CommonsTestsOn_test_topology.yml\", func(t *testing.T) {\n\t\tdeploymentID := testutil.BuildDeploymentID(t)\n\t\terr := StoreDeploymentDefinition(context.Background(), deploymentID, \"testdata/test_topology.yml\")\n\t\trequire.NoError(t, err)\n\n\t\tt.Run(\"TestNodeHasAttribute\", func(t *testing.T) {\n\t\t\ttestNodeHasAttribute(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestNodeHasProperty\", func(t *testing.T) {\n\t\t\ttestNodeHasProperty(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestTopologyTemplateMetadata\", func(t *testing.T) {\n\t\t\ttestTopologyTemplateMetadata(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestAttributeNotifications\", func(t *testing.T) {\n\t\t\ttestAttributeNotifications(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestNotifyAttributeOnValueChange\", func(t *testing.T) {\n\t\t\ttestNotifyAttributeOnValueChange(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestImportTopologyTemplate\", func(t *testing.T) {\n\t\t\ttestImportTopologyTemplateNodeMetadata(t, deploymentID)\n\t\t})\n\t\tt.Run(\"TestTopologyTemplateMetadata\", func(t *testing.T) {\n\t\t\ttestTopologyTemplateMetadata(t, deploymentID)\n\t\t})\n\t})\n\n\tt.Run(\"CommonsTestsOn_test_topology_substitution.yml\", func(t *testing.T) {\n\t\tdeploymentID := testutil.BuildDeploymentID(t)\n\t\terr := StoreDeploymentDefinition(context.Background(), deploymentID, \"testdata/test_topology_substitution.yml\")\n\t\trequire.NoError(t, err)\n\n\t\tt.Run(\"TestAddSubstitutionMappingAttributeHostNotification\", func(t *testing.T) {\n\t\t\ttestAddSubstitutionMappingAttributeHostNotification(t, deploymentID)\n\t\t})\n\t})\n}", "func TestHandle_existingDeployments(t *testing.T) {\n\tvar updatedDeployments []kapi.ReplicationController\n\tvar (\n\t\tconfig *deployapi.DeploymentConfig\n\t\tdeployed *kapi.ReplicationController\n\t\texistingDeployments *kapi.ReplicationControllerList\n\t)\n\n\tcontroller := &DeploymentConfigController{\n\t\tmakeDeployment: func(config *deployapi.DeploymentConfig) (*kapi.ReplicationController, error) {\n\t\t\treturn deployutil.MakeDeployment(config, api.Codec)\n\t\t},\n\t\tdeploymentClient: &deploymentClientImpl{\n\t\t\tcreateDeploymentFunc: func(namespace string, deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\t\tdeployed = deployment\n\t\t\t\treturn deployment, nil\n\t\t\t},\n\t\t\tlistDeploymentsForConfigFunc: func(namespace, configName string) (*kapi.ReplicationControllerList, error) {\n\t\t\t\treturn existingDeployments, nil\n\t\t\t},\n\t\t\tupdateDeploymentFunc: func(namespace string, deployment *kapi.ReplicationController) (*kapi.ReplicationController, error) {\n\t\t\t\tupdatedDeployments = append(updatedDeployments, *deployment)\n\t\t\t\t//t.Fatalf(\"unexpected update call with deployment %v\", deployment)\n\t\t\t\treturn deployment, nil\n\t\t\t},\n\t\t},\n\t\trecorder: &record.FakeRecorder{},\n\t}\n\n\ttype existing struct {\n\t\tversion int\n\t\tstatus deployapi.DeploymentStatus\n\t\tshouldCancel bool\n\t}\n\n\ttype scenario struct {\n\t\tversion int\n\t\texisting []existing\n\t\terrorType reflect.Type\n\t\texpectDeployment bool\n\t}\n\n\ttransientErrorType := reflect.TypeOf(transientError(\"\"))\n\tscenarios := []scenario{\n\t\t// No existing deployments\n\t\t{1, []existing{}, nil, true},\n\t\t// A single existing completed deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusComplete, false}}, nil, true},\n\t\t// A single existing failed deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusFailed, false}}, nil, true},\n\t\t// Multiple existing completed/failed deployments\n\t\t{3, []existing{{2, deployapi.DeploymentStatusFailed, false}, {1, deployapi.DeploymentStatusComplete, false}}, nil, true},\n\n\t\t// A single existing deployment in the default state\n\t\t{2, []existing{{1, \"\", false}}, transientErrorType, false},\n\t\t// A single existing new deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusNew, false}}, transientErrorType, false},\n\t\t// A single existing pending deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusPending, false}}, transientErrorType, false},\n\t\t// A single existing running deployment\n\t\t{2, []existing{{1, deployapi.DeploymentStatusRunning, false}}, transientErrorType, false},\n\t\t// Multiple existing deployments with one in new/pending/running\n\t\t{4, []existing{{3, deployapi.DeploymentStatusRunning, false}, {2, deployapi.DeploymentStatusComplete, false}, {1, deployapi.DeploymentStatusFailed, false}}, transientErrorType, false},\n\n\t\t// Latest deployment exists and has already failed/completed\n\t\t{2, []existing{{2, deployapi.DeploymentStatusFailed, false}, {1, deployapi.DeploymentStatusComplete, false}}, nil, false},\n\t\t// Latest deployment exists and is in new/pending/running state\n\t\t{2, []existing{{2, deployapi.DeploymentStatusRunning, false}, {1, deployapi.DeploymentStatusComplete, false}}, nil, false},\n\n\t\t// Multiple existing deployments with more than one in new/pending/running\n\t\t{4, []existing{{3, deployapi.DeploymentStatusNew, false}, {2, deployapi.DeploymentStatusRunning, true}, {1, deployapi.DeploymentStatusFailed, false}}, transientErrorType, false},\n\t\t// Multiple existing deployments with more than one in new/pending/running\n\t\t// Latest deployment has already failed\n\t\t{6, []existing{{5, deployapi.DeploymentStatusFailed, false}, {4, deployapi.DeploymentStatusRunning, false}, {3, deployapi.DeploymentStatusNew, true}, {2, deployapi.DeploymentStatusComplete, false}, {1, deployapi.DeploymentStatusNew, true}}, transientErrorType, false},\n\t}\n\n\tfor _, scenario := range scenarios {\n\t\tupdatedDeployments = []kapi.ReplicationController{}\n\t\tdeployed = nil\n\t\tconfig = deploytest.OkDeploymentConfig(scenario.version)\n\t\texistingDeployments = &kapi.ReplicationControllerList{}\n\t\tfor _, e := range scenario.existing {\n\t\t\td, _ := deployutil.MakeDeployment(deploytest.OkDeploymentConfig(e.version), api.Codec)\n\t\t\tif e.status != \"\" {\n\t\t\t\td.Annotations[deployapi.DeploymentStatusAnnotation] = string(e.status)\n\t\t\t}\n\t\t\texistingDeployments.Items = append(existingDeployments.Items, *d)\n\t\t}\n\t\terr := controller.Handle(config)\n\n\t\tif scenario.expectDeployment && deployed == nil {\n\t\t\tt.Fatalf(\"expected a deployment\")\n\t\t}\n\n\t\tif scenario.errorType == nil {\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tif err == nil {\n\t\t\t\tt.Fatalf(\"expected error\")\n\t\t\t}\n\t\t\tif reflect.TypeOf(err) != scenario.errorType {\n\t\t\t\tt.Fatalf(\"error expected: %s, got: %s\", scenario.errorType, reflect.TypeOf(err))\n\t\t\t}\n\t\t}\n\n\t\texpectedCancellations := []int{}\n\t\tactualCancellations := []int{}\n\t\tfor _, e := range scenario.existing {\n\t\t\tif e.shouldCancel {\n\t\t\t\texpectedCancellations = append(expectedCancellations, e.version)\n\t\t\t}\n\t\t}\n\t\tfor _, d := range updatedDeployments {\n\t\t\tactualCancellations = append(actualCancellations, deployutil.DeploymentVersionFor(&d))\n\t\t}\n\n\t\tsort.Ints(actualCancellations)\n\t\tsort.Ints(expectedCancellations)\n\t\tif !reflect.DeepEqual(actualCancellations, expectedCancellations) {\n\t\t\tt.Fatalf(\"expected cancellations: %v, actual: %v\", expectedCancellations, actualCancellations)\n\t\t}\n\t}\n}", "func TestDeviceController(t *testing.T) {\n\n\t// Set the logger to development mode for verbose logs.\n\tlogf.SetLogger(zap.New(zap.UseDevMode(true)))\n\n\t// Create a fake client to mock API calls.\n\tcl, s := CreateFakeClient(t)\n\n\t// Create a ReconcileBlockDevice object with the scheme and fake client.\n\tr := &BlockDeviceReconciler{Client: cl, Scheme: s, Recorder: fakeRecorder}\n\n\t// Mock request to simulate Reconcile() being called on an event for a\n\t// watched resource .\n\treq := reconcile.Request{\n\t\tNamespacedName: types.NamespacedName{\n\t\t\tName: deviceName,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\n\tres, err := r.Reconcile(context.TODO(), req)\n\tif err != nil {\n\t\tt.Fatalf(\"reconcile: (%v)\", err)\n\t}\n\n\t// Check the result of reconciliation to make sure it has the desired state.\n\tif !res.Requeue {\n\t\tt.Log(\"reconcile did not requeue request as expected\")\n\t}\n\n\tdeviceInstance := &openebsv1alpha1.BlockDevice{}\n\terr = r.Client.Get(context.TODO(), req.NamespacedName, deviceInstance)\n\tif err != nil {\n\t\tt.Errorf(\"get deviceInstance : (%v)\", err)\n\t}\n\n\t// Disk Status state should be Active as expected.\n\tif deviceInstance.Status.State == ndm.NDMActive {\n\t\tt.Logf(\"BlockDevice Object state:%v match expected state:%v\", deviceInstance.Status.State, ndm.NDMActive)\n\t} else {\n\t\tt.Fatalf(\"BlockDevice Object state:%v did not match expected state:%v\", deviceInstance.Status.State, ndm.NDMActive)\n\t}\n}", "func getOSMControllerPods(clientSet kubernetes.Interface, ns string) *corev1.PodList {\n\tlabelSelector := metav1.LabelSelector{MatchLabels: map[string]string{constants.AppLabel: constants.OSMControllerName}}\n\tlistOptions := metav1.ListOptions{\n\t\tLabelSelector: labels.Set(labelSelector.MatchLabels).String(),\n\t}\n\tpodList, _ := clientSet.CoreV1().Pods(ns).List(context.TODO(), listOptions)\n\treturn podList\n}", "func TestController(t *testing.T) {\n\tsuite.Run(t, new(ControllerTestSuite))\n}", "func TestBucketController(t *testing.T) {\n\t// Set the logger to development mode for verbose logs.\n\tlogf.SetLogger(logf.ZapLogger(true))\n\n\t// setup fake GCS storage backend\n\tserver := setupFakeStorage(t)\n\tstorageClient := server.Client()\n\n\tvar (\n\t\tname = \"bucket-operator\"\n\t\tnamespace = \"bucket\"\n\t\tbucketName string = \"my-new-bucket\"\n\t)\n\n\t// A Bucket resource with metadata and spec.\n\tbucket := &cachev1alpha1.Bucket{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tSpec: cachev1alpha1.BucketSpec{\n\t\t\tName: bucketName,\n\t\t},\n\t}\n\t// Objects to track in the fake client.\n\tobjs := []runtime.Object{\n\t\tbucket,\n\t}\n\n\t// Register operator types with the runtime scheme.\n\ts := scheme.Scheme\n\ts.AddKnownTypes(cachev1alpha1.SchemeGroupVersion, bucket)\n\t// Create a fake client to mock API calls.\n\tcl := fake.NewFakeClient(objs...)\n\t// Create a ReconcileBucket object with the scheme and fake client.\n\tr := &ReconcileBucket{storageClient: storageClient, client: cl, scheme: s}\n\n\t// Mock request to simulate Reconcile() being called on an event for a\n\t// watched resource .\n\treq := reconcile.Request{\n\t\tNamespacedName: types.NamespacedName{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t}\n\tres, err := r.Reconcile(req)\n\tif err != nil {\n\t\tt.Fatalf(\"reconcile: (%v)\", err)\n\t}\n\t// Check the result of reconciliation to make sure it has the desired state.\n\tif !res.Requeue {\n\t\tt.Error(\"reconcile did not requeue request as expected\")\n\t}\n\n\tbh := storageClient.Bucket(bucketName)\n\t// Next check if the bucket exists\n\tif _, err := bh.Attrs(context.TODO()); err != nil {\n\t\tt.Errorf(\"expected bucket %s to exist\", bucketName)\n\t}\n\n\tres, err = r.Reconcile(req)\n\tif err != nil {\n\t\tt.Fatalf(\"reconcile: (%v)\", err)\n\t}\n\t// Check the result of reconciliation to make sure it has the desired state.\n\tif res.Requeue {\n\t\tt.Error(\"reconcile requeue which is not expected\")\n\t}\n\n\tif err = os.Remove(\"./testdata/my-new-bucket\"); err != nil {\n\t\tt.Fatalf(\"couldn't delete bucket %s\", bucketName)\n\t}\n\n\t// Get the updated Bucket object.\n\tbucket = &cachev1alpha1.Bucket{}\n\terr = r.client.Get(context.TODO(), req.NamespacedName, bucket)\n\tif err != nil {\n\t\tt.Errorf(\"get bucket: (%v)\", err)\n\t}\n\n\t// Ensure Reconcile() updated the Bucket's Status as expected.\n\t// nodes := bucket.Status.Nodes\n\t// if !reflect.DeepEqual(podNames, nodes) {\n\t// \tt.Errorf(\"pod names %v did not match expected %v\", nodes, podNames)\n\t// }\n\n\tserver.Stop()\n}", "func (m *kubeGenericRuntimeManager) computePodActions(pod *v1.Pod, podStatus *kubecontainer.PodStatus) podActions {\n\tklog.V(5).Infof(\"Syncing Pod %q: %+v\", format.Pod(pod), pod)\n\tklog.V(5).Infof(\"podstatus %v\", podStatus)\n\tif podStatus.SandboxStatuses != nil {\n\t\tklog.V(5).Infof(\"pod sandbox length %v\", len(podStatus.SandboxStatuses))\n\t\tfor _, sb := range podStatus.SandboxStatuses {\n\t\t\tklog.V(5).Infof(\"pod sandbox status %v\", sb)\n\t\t}\n\t}\n\n\tcreatePodSandbox, attempt, sandboxID := m.podSandboxChanged(pod, podStatus)\n\tchanges := podActions{\n\t\tKillPod: createPodSandbox,\n\t\tCreateSandbox: createPodSandbox,\n\t\tSandboxID: sandboxID,\n\t\tAttempt: attempt,\n\t\tContainersToStart: []int{},\n\t\tContainersToKill: make(map[kubecontainer.ContainerID]containerToKillInfo),\n\t\tContainersToUpdate: make(map[string][]containerToUpdateInfo),\n\t\tContainersToRestart: []int{},\n\t}\n\n\t// If we need to (re-)create the pod sandbox, everything will need to be\n\t// killed and recreated, and init containers should be purged.\n\tif createPodSandbox {\n\t\tif !shouldRestartOnFailure(pod) && attempt != 0 {\n\t\t\t// Should not restart the pod, just return.\n\t\t\t// we should not create a sandbox for a pod if it is already done.\n\t\t\t// if all containers are done and should not be started, there is no need to create a new sandbox.\n\t\t\t// this stops confusing logs on pods whose containers all have exit codes, but we recreate a sandbox before terminating it.\n\t\t\tchanges.CreateSandbox = false\n\t\t\treturn changes\n\t\t}\n\t\tif len(pod.Spec.InitContainers) != 0 {\n\t\t\t// Pod has init containers, return the first one.\n\t\t\tchanges.NextInitContainerToStart = &pod.Spec.InitContainers[0]\n\t\t\treturn changes\n\t\t}\n\t\t// Start all containers by default but exclude the ones that succeeded if\n\t\t// RestartPolicy is OnFailure.\n\t\tfor idx, c := range pod.Spec.Containers {\n\t\t\tif containerSucceeded(&c, podStatus) && pod.Spec.RestartPolicy == v1.RestartPolicyOnFailure {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tchanges.ContainersToStart = append(changes.ContainersToStart, idx)\n\t\t}\n\t\treturn changes\n\t}\n\n\t// Check initialization progress.\n\tinitLastStatus, next, done := findNextInitContainerToRun(pod, podStatus)\n\tif !done {\n\t\tif next != nil {\n\t\t\tinitFailed := initLastStatus != nil && isInitContainerFailed(initLastStatus)\n\t\t\tif initFailed && !shouldRestartOnFailure(pod) {\n\t\t\t\tchanges.KillPod = true\n\t\t\t} else {\n\t\t\t\t// Always try to stop containers in unknown state first.\n\t\t\t\tif initLastStatus != nil && initLastStatus.State == kubecontainer.ContainerStateUnknown {\n\t\t\t\t\tchanges.ContainersToKill[initLastStatus.ID] = containerToKillInfo{\n\t\t\t\t\t\tname: next.Name,\n\t\t\t\t\t\tcontainer: next,\n\t\t\t\t\t\tmessage: fmt.Sprintf(\"Init container is in %q state, try killing it before restart\",\n\t\t\t\t\t\t\tinitLastStatus.State),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tchanges.NextInitContainerToStart = next\n\t\t\t}\n\t\t}\n\t\t// Initialization failed or still in progress. Skip inspecting non-init\n\t\t// containers.\n\t\treturn changes\n\t}\n\n\t// Number of running containers to keep.\n\tkeepCount := 0\n\n\t// check the status of containers.\n\tfor idx, container := range pod.Spec.Containers {\n\t\tcontainerStatus := podStatus.FindContainerStatusByName(container.Name)\n\n\t\t// Call internal container post-stop lifecycle hook for any non-running container so that any\n\t\t// allocated cpus are released immediately. If the container is restarted, cpus will be re-allocated\n\t\t// to it.\n\t\tif containerStatus != nil && containerStatus.State != kubecontainer.ContainerStateRunning {\n\t\t\tif err := m.internalLifecycle.PostStopContainer(containerStatus.ID.ID); err != nil {\n\t\t\t\tklog.Errorf(\"internal container post-stop lifecycle hook failed for container %v in pod %v with error %v\",\n\t\t\t\t\tcontainer.Name, pod.Name, err)\n\t\t\t}\n\t\t}\n\n\t\t// If container does not exist, or is not running, check whether we\n\t\t// need to restart it.\n\t\tif containerStatus == nil || containerStatus.State != kubecontainer.ContainerStateRunning {\n\t\t\tif kubecontainer.ShouldContainerBeRestarted(&container, pod, podStatus) {\n\t\t\t\tmessage := fmt.Sprintf(\"Container %+v is dead, but RestartPolicy says that we should restart it.\", container)\n\t\t\t\tklog.V(3).Infof(message)\n\t\t\t\tchanges.ContainersToStart = append(changes.ContainersToStart, idx)\n\t\t\t\tif containerStatus != nil && containerStatus.State == kubecontainer.ContainerStateUnknown {\n\t\t\t\t\t// If container is in unknown state, we don't know whether it\n\t\t\t\t\t// is actually running or not, always try killing it before\n\t\t\t\t\t// restart to avoid having 2 running instances of the same container.\n\t\t\t\t\tchanges.ContainersToKill[containerStatus.ID] = containerToKillInfo{\n\t\t\t\t\t\tname: containerStatus.Name,\n\t\t\t\t\t\tcontainer: &pod.Spec.Containers[idx],\n\t\t\t\t\t\tmessage: fmt.Sprintf(\"Container is in %q state, try killing it before restart\", containerStatus.State),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// The container is running, but kill the container if any of the following condition is met.\n\t\tvar message string\n\t\trestart := shouldRestartOnFailure(pod)\n\t\tif _, _, changed := containerChanged(&container, containerStatus); changed {\n\t\t\tmessage = fmt.Sprintf(\"Container %s definition changed\", container.Name)\n\t\t\t// Restart regardless of the restart policy because the container\n\t\t\t// spec changed.\n\t\t\trestart = true\n\t\t} else if liveness, found := m.livenessManager.Get(containerStatus.ID); found && liveness == proberesults.Failure {\n\t\t\t// If the container failed the liveness probe, we should kill it.\n\t\t\tmessage = fmt.Sprintf(\"Container %s failed liveness probe\", container.Name)\n\t\t} else {\n\t\t\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t\t\tkeepCount++\n\t\t\t\tapiContainerStatuses := pod.Status.ContainerStatuses\n\t\t\t\tif pod.Spec.VirtualMachine != nil && pod.Status.VirtualMachineStatus != nil {\n\t\t\t\t\tvar vmContainerState v1.ContainerState\n\t\t\t\t\tif pod.Status.VirtualMachineStatus.State == v1.VmActive {\n\t\t\t\t\t\tvmContainerState = v1.ContainerState{Running: &v1.ContainerStateRunning{StartedAt: *pod.Status.StartTime}}\n\t\t\t\t\t}\n\t\t\t\t\tvmContainerId := kubecontainer.BuildContainerID(containerStatus.ID.Type, pod.Status.VirtualMachineStatus.VirtualMachineId)\n\t\t\t\t\tapiContainerStatuses = []v1.ContainerStatus{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: pod.Status.VirtualMachineStatus.Name,\n\t\t\t\t\t\t\tContainerID: vmContainerId.String(),\n\t\t\t\t\t\t\tState: vmContainerState,\n\t\t\t\t\t\t\tReady: pod.Status.VirtualMachineStatus.Ready,\n\t\t\t\t\t\t\tRestartCount: pod.Status.VirtualMachineStatus.RestartCount,\n\t\t\t\t\t\t\tImage: pod.Status.VirtualMachineStatus.Image,\n\t\t\t\t\t\t\tImageID: pod.Status.VirtualMachineStatus.ImageId,\n\t\t\t\t\t\t\tResources: pod.Status.VirtualMachineStatus.Resources,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif container.Resources.Limits == nil || len(apiContainerStatuses) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tapiContainerStatus, exists := podutil.GetContainerStatus(apiContainerStatuses, container.Name)\n\t\t\t\tif !exists || apiContainerStatus.State.Running == nil ||\n\t\t\t\t\tcontainerStatus.State != kubecontainer.ContainerStateRunning ||\n\t\t\t\t\tcontainerStatus.ID.String() != apiContainerStatus.ContainerID ||\n\t\t\t\t\tlen(diff.ObjectDiff(container.Resources.Requests, container.ResourcesAllocated)) != 0 ||\n\t\t\t\t\tlen(diff.ObjectDiff(apiContainerStatus.Resources, container.Resources)) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// If runtime status resources is available from CRI or previous update, compare with it.\n\t\t\t\tif len(diff.ObjectDiff(containerStatus.Resources, container.Resources)) == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tresizePolicy := make(map[v1.ResourceName]v1.ContainerResizePolicy)\n\t\t\t\tfor _, pol := range container.ResizePolicy {\n\t\t\t\t\tresizePolicy[pol.ResourceName] = pol.Policy\n\t\t\t\t}\n\t\t\t\tdetermineContainerResize := func(rName v1.ResourceName, specValue, statusValue int64) (bool, bool) {\n\t\t\t\t\tif specValue == statusValue {\n\t\t\t\t\t\treturn false, false\n\t\t\t\t\t}\n\t\t\t\t\tif resizePolicy[rName] == v1.RestartContainer {\n\t\t\t\t\t\treturn true, true\n\t\t\t\t\t}\n\t\t\t\t\treturn true, false\n\t\t\t\t}\n\t\t\t\tmarkContainerForUpdate := func(rName string, specValue, statusValue int64) {\n\t\t\t\t\tcUpdateInfo := containerToUpdateInfo{\n\t\t\t\t\t\tapiContainer: &pod.Spec.Containers[idx],\n\t\t\t\t\t\tapiContainerStatus: &apiContainerStatus,\n\t\t\t\t\t\tkubeContainerStatus: containerStatus,\n\t\t\t\t\t}\n\t\t\t\t\t// Container updates are ordered so that resource decreases are applied before increases\n\t\t\t\t\tswitch {\n\t\t\t\t\tcase specValue > statusValue: // append\n\t\t\t\t\t\tchanges.ContainersToUpdate[rName] = append(changes.ContainersToUpdate[rName], cUpdateInfo)\n\t\t\t\t\tcase specValue < statusValue: // prepend\n\t\t\t\t\t\tchanges.ContainersToUpdate[rName] = append(changes.ContainersToUpdate[rName], containerToUpdateInfo{})\n\t\t\t\t\t\tcopy(changes.ContainersToUpdate[rName][1:], changes.ContainersToUpdate[rName])\n\t\t\t\t\t\tchanges.ContainersToUpdate[rName][0] = cUpdateInfo\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tspecLim := container.Resources.Limits\n\t\t\t\tspecReq := container.Resources.Requests\n\t\t\t\tstatusLim := apiContainerStatus.Resources.Limits\n\t\t\t\tstatusReq := apiContainerStatus.Resources.Requests\n\t\t\t\t// Runtime container status resources, if set, takes precedence.\n\t\t\t\tif containerStatus.Resources.Limits != nil {\n\t\t\t\t\tstatusLim = containerStatus.Resources.Limits\n\t\t\t\t}\n\t\t\t\tif containerStatus.Resources.Requests != nil {\n\t\t\t\t\tstatusReq = containerStatus.Resources.Requests\n\t\t\t\t}\n\t\t\t\tresizeMemLim, restartMemLim := determineContainerResize(v1.ResourceMemory, specLim.Memory().Value(), statusLim.Memory().Value())\n\t\t\t\tresizeCPUReq, restartCPUReq := determineContainerResize(v1.ResourceCPU, specReq.Cpu().MilliValue(), statusReq.Cpu().MilliValue())\n\t\t\t\tresizeCPULim, restartCPULim := determineContainerResize(v1.ResourceCPU, specLim.Cpu().MilliValue(), statusLim.Cpu().MilliValue())\n\t\t\t\tif restartMemLim || restartCPULim || restartCPUReq {\n\t\t\t\t\t// resize policy requires this container to restart\n\t\t\t\t\tchanges.ContainersToKill[containerStatus.ID] = containerToKillInfo{\n\t\t\t\t\t\tname: containerStatus.Name,\n\t\t\t\t\t\tcontainer: &pod.Spec.Containers[idx],\n\t\t\t\t\t\tmessage: fmt.Sprintf(\"Container %s resize requires restart\", container.Name),\n\t\t\t\t\t}\n\t\t\t\t\tchanges.ContainersToRestart = append(changes.ContainersToRestart, idx)\n\t\t\t\t\tkeepCount--\n\t\t\t\t} else {\n\t\t\t\t\tif resizeMemLim {\n\t\t\t\t\t\tmarkContainerForUpdate(memLimit, specLim.Memory().Value(), statusLim.Memory().Value())\n\t\t\t\t\t}\n\t\t\t\t\tif resizeCPUReq {\n\t\t\t\t\t\tmarkContainerForUpdate(cpuRequest, specReq.Cpu().MilliValue(), statusReq.Cpu().MilliValue())\n\t\t\t\t\t}\n\t\t\t\t\tif resizeCPULim {\n\t\t\t\t\t\tmarkContainerForUpdate(cpuLimit, specLim.Cpu().MilliValue(), statusLim.Cpu().MilliValue())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Keep the container.\n\t\t\tkeepCount++\n\t\t\tcontinue\n\t\t}\n\n\t\t// We need to kill the container, but if we also want to restart the\n\t\t// container afterwards, make the intent clear in the message. Also do\n\t\t// not kill the entire pod since we expect container to be running eventually.\n\t\tif restart {\n\t\t\tmessage = fmt.Sprintf(\"%s, will be restarted\", message)\n\t\t\tchanges.ContainersToStart = append(changes.ContainersToStart, idx)\n\t\t}\n\n\t\tchanges.ContainersToKill[containerStatus.ID] = containerToKillInfo{\n\t\t\tname: containerStatus.Name,\n\t\t\tcontainer: &pod.Spec.Containers[idx],\n\t\t\tmessage: message,\n\t\t}\n\t\tklog.V(2).Infof(\"Container %q (%q) of pod %s: %s\", container.Name, containerStatus.ID, format.Pod(pod), message)\n\t}\n\n\tif keepCount == 0 && len(changes.ContainersToStart) == 0 {\n\t\tchanges.KillPod = true\n\t\tif utilfeature.DefaultFeatureGate.Enabled(features.InPlacePodVerticalScaling) {\n\t\t\tif len(changes.ContainersToRestart) != 0 {\n\t\t\t\tchanges.KillPod = false\n\t\t\t}\n\t\t}\n\t}\n\n\t// always attempts to identify hotplug nic based on pod spec & pod status (got from runtime)\n\tif m.canHotplugNIC(pod, podStatus) {\n\t\tif len(podStatus.SandboxStatuses) > 0 && podStatus.SandboxStatuses[0].GetNetwork() != nil {\n\t\t\tnicsToAttach, nicsToDetach := computeNICHotplugs(pod.Spec.Nics, podStatus.SandboxStatuses[0].GetNetwork().GetNics())\n\t\t\tif len(nicsToAttach) > 0 {\n\t\t\t\tchanges.Hotplugs.NICsToAttach = nicsToAttach\n\t\t\t}\n\t\t\tif len(nicsToDetach) > 0 {\n\t\t\t\tchanges.Hotplugs.NICsToDetach = nicsToDetach\n\t\t\t}\n\t\t}\n\t}\n\n\treturn changes\n}", "func main() {\n\tkubeconfig := filepath.Join(\"/Users/julz\", \".kube\", \"config\")\n\tccApi := flag.String(\"cc_api\", \"internal_user\", \"\")\n\tccUser := flag.String(\"cc_user\", \"internal_user\", \"\")\n\tccPass := flag.String(\"cc_pass\", \"\", \"\")\n\tflag.Parse()\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tbatchSize := 50\n\n\tlog := lager.NewLogger(\"sink\")\n\tlog.RegisterSink(lager.NewWriterSink(os.Stdout, lager.DEBUG))\n\n\tcancel := make(chan struct{})\n\tclient := &http.Client{Transport: &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}}\n\n\tfetcher := &bulk.CCFetcher{\n\t\tBaseURI: *ccApi,\n\t\tBatchSize: batchSize,\n\t\tUsername: *ccUser,\n\t\tPassword: *ccPass,\n\t}\n\n\tticker := time.NewTicker(15 * time.Second).C\n\tfor range ticker {\n\t\tlog.Info(\"tick\", nil)\n\n\t\texisting, err := clientset.AppsV1beta1().Deployments(\"default\").List(av1.ListOptions{\n\t\t\tLabelSelector: \"cube\",\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Error(\"fetch-from-kube\", err, nil)\n\t\t\tbreak\n\t\t}\n\n\t\texistingByGuid := make(map[string]string)\n\t\tfor _, e := range existing.Items {\n\t\t\texistingByGuid[e.Name] = e.Labels[\"etag\"]\n\t\t}\n\n\t\tlog.Info(\"got-existing\", lager.Data{\"existing\": existingByGuid})\n\n\t\tfingerprints, fingerprintErr := fetcher.FetchFingerprints(log, cancel, client)\n\t\tdesired, desiredErr := fetcher.FetchDesiredApps(log, cancel, client, fingerprints)\n\t\tdeployments := convert(log, cancel, desired)\n\n\t\tfor d := range deployments {\n\t\t\tif _, ok := existingByGuid[d.Name]; !ok {\n\t\t\t\t_, err = clientset.AppsV1beta1().Deployments(\"default\").Create(d)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"created-deployment-failed\", err, nil)\n\t\t\t\t}\n\n\t\t\t\tlog.Info(\"created\", lager.Data{\"d\": d, \"e\": err})\n\t\t\t} else if existingByGuid[d.Name] != d.Labels[\"etag\"] {\n\t\t\t\t_, err = clientset.AppsV1beta1().Deployments(\"default\").Update(d)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"created-deployment-failed\", err, nil)\n\t\t\t\t}\n\n\t\t\t\tlog.Info(\"updated\", lager.Data{\"d\": d, \"e\": err})\n\t\t\t} else {\n\t\t\t\tlog.Info(\"skipped\", lager.Data{\"name\": d.Name})\n\t\t\t}\n\t\t}\n\n\t\twait(log, \"fetch-fingerprints-error\", fingerprintErr)\n\t\twait(log, \"fetch-desired-error\", desiredErr)\n\t}\n}", "func TestSimplePipelineRun(t *testing.T) {\n\tt.Parallel()\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tc, namespace := setup(ctx, t)\n\n\tknativetest.CleanupOnInterrupt(func() { tearDown(context.Background(), t, c, namespace) }, t.Logf)\n\tdefer tearDown(context.Background(), t, c, namespace)\n\n\tt.Logf(\"Creating Task in namespace %s\", namespace)\n\ttask := parse.MustParseV1Task(t, fmt.Sprintf(simpleTaskYaml, task1Name, namespace))\n\tif _, err := c.V1TaskClient.Create(ctx, task, metav1.CreateOptions{}); err != nil {\n\t\tt.Fatalf(\"Failed to create Task `%s`: %s\", task.Name, err)\n\t}\n\n\tpipeline := parse.MustParseV1Pipeline(t, fmt.Sprintf(simplePipelineYaml, helpers.ObjectNameForTest(t), namespace, task1Name, task.Name))\n\tpipelineName := pipeline.Name\n\tpipelineRun := parse.MustParseV1PipelineRun(t, fmt.Sprintf(simplePipelineRunYaml, helpers.ObjectNameForTest(t), namespace, pipeline.Name))\n\tpipelineRunName := pipelineRun.Name\n\n\tif _, err := c.V1PipelineClient.Create(ctx, pipeline, metav1.CreateOptions{}); err != nil {\n\t\tt.Fatalf(\"Failed to create Pipeline `%s`: %s\", pipeline.Name, err)\n\t}\n\tif _, err := c.V1PipelineRunClient.Create(ctx, pipelineRun, metav1.CreateOptions{}); err != nil {\n\t\tt.Fatalf(\"Failed to create PipelineRun `%s`: %s\", pipelineRunName, err)\n\t}\n\n\tt.Logf(\"Waiting for PipelineRun %s in namespace %s to complete\", pipelineRunName, namespace)\n\tif err := WaitForPipelineRunState(ctx, c, pipelineRunName, timeout, PipelineRunSucceed(pipelineRunName), \"PipelineRunSuccess\", v1Version); err != nil {\n\t\tt.Fatalf(\"Error waiting for PipelineRun %s to finish: %s\", pipelineRunName, err)\n\t}\n\n\ttaskRunName := strings.Join([]string{pipelineRunName, task1Name}, \"-\")\n\n\tpr, err := c.V1PipelineRunClient.Get(ctx, pipelineRunName, metav1.GetOptions{})\n\tif err != nil {\n\t\tt.Fatalf(\"Couldn't get expected PipelineRun %s: %s\", pipelineRunName, err)\n\t}\n\n\texpectedPipelineRun := parse.MustParseV1PipelineRun(t, fmt.Sprintf(expectedSimplePipelineRunYaml, pipelineRunName, namespace, pipelineName, taskRunName))\n\tif d := cmp.Diff(expectedPipelineRun, pr, append([]cmp.Option{filterV1PipelineRunStatus, filterV1PipelineRunSA, filterPipelineRunStatusFields}, filterV1PipelineRunFields...)...); d != \"\" {\n\t\tt.Errorf(\"Cannot get expected PipelineRun, -want, +got: %v\", d)\n\t}\n}", "func waitToObservePods(t *testing.T, podInformer cache.SharedIndexInformer, podNum int) {\n\tif err := wait.Poll(10*time.Second, 60*time.Second, func() (bool, error) {\n\t\tobjects := podInformer.GetIndexer().List()\n\t\tif len(objects) == podNum {\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\treturn false, nil\n\t\t}\n\t}); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (o *ControllerCommitStatusOptions) Run() error {\n\t// Always run in batch mode as a controller is never run interactively\n\to.BatchMode = true\n\n\tjxClient, ns, err := o.JXClientAndDevNamespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\tkubeClient, _, err := o.KubeClientAndDevNamespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\tapisClient, err := o.ApiExtensionsClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = kube.RegisterCommitStatusCRD(apisClient)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = kube.RegisterPipelineActivityCRD(apisClient)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcommitstatusListWatch := cache.NewListWatchFromClient(jxClient.JenkinsV1().RESTClient(), \"commitstatuses\", ns, fields.Everything())\n\tkube.SortListWatchByName(commitstatusListWatch)\n\t_, commitstatusController := cache.NewInformer(\n\t\tcommitstatusListWatch,\n\t\t&jenkinsv1.CommitStatus{},\n\t\ttime.Minute*10,\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: func(obj interface{}) {\n\t\t\t\to.onCommitStatusObj(obj, jxClient, ns)\n\t\t\t},\n\t\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\t\to.onCommitStatusObj(newObj, jxClient, ns)\n\t\t\t},\n\t\t\tDeleteFunc: func(obj interface{}) {\n\n\t\t\t},\n\t\t},\n\t)\n\tstop := make(chan struct{})\n\tgo commitstatusController.Run(stop)\n\n\tpodListWatch := cache.NewListWatchFromClient(kubeClient.CoreV1().RESTClient(), \"pods\", ns, fields.Everything())\n\tkube.SortListWatchByName(podListWatch)\n\t_, podWatch := cache.NewInformer(\n\t\tpodListWatch,\n\t\t&corev1.Pod{},\n\t\ttime.Minute*10,\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: func(obj interface{}) {\n\t\t\t\to.onPodObj(obj, jxClient, kubeClient, ns)\n\t\t\t},\n\t\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\t\to.onPodObj(newObj, jxClient, kubeClient, ns)\n\t\t\t},\n\t\t\tDeleteFunc: func(obj interface{}) {\n\n\t\t\t},\n\t\t},\n\t)\n\tstop = make(chan struct{})\n\tpodWatch.Run(stop)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *TestClient) createPodInformer() error {\n\tklog.Infof(\"Creating PodWatcher for namespace %q and labelSelector %q\", c.TargetConfig.TargetNamespace, c.TargetConfig.TargetLabelSelector)\n\n\tlistWatch := &cache.ListWatch{\n\t\tListFunc: func(options metav1.ListOptions) (runtime.Object, error) {\n\t\t\toptions.LabelSelector = c.TargetConfig.TargetLabelSelector\n\t\t\treturn c.K8sClient.CoreV1().Pods(c.TargetConfig.TargetNamespace).List(context.TODO(), options)\n\t\t},\n\t\tWatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {\n\t\t\toptions.LabelSelector = c.TargetConfig.TargetLabelSelector\n\t\t\treturn c.K8sClient.CoreV1().Pods(c.TargetConfig.TargetNamespace).Watch(context.TODO(), options)\n\t\t},\n\t}\n\n\thandlePodEvent := func(obj interface{}, isAddEvent bool) {\n\t\tpod, ok := obj.(*corev1.Pod)\n\t\tif !ok {\n\t\t\tklog.Warningf(\"handlePodEvent() failed to convert newObj (%T) to *corev1.Pod\", obj)\n\t\t\treturn\n\t\t}\n\n\t\tpodEvent := utils.PodEvent{PodName: pod.GetName(), IsAddEvent: isAddEvent}\n\t\tc.podCreationWorkQueue.Add(podEvent)\n\t}\n\n\tinformer := cache.NewSharedIndexInformer(listWatch, nil, 0, cache.Indexers{utils.NameIndex: utils.MetaNameIndexFunc})\n\t_, err := informer.AddEventHandler(cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: func(obj interface{}) {\n\t\t\thandlePodEvent(obj, true)\n\t\t},\n\t\tUpdateFunc: func(oldObj, newObj interface{}) {\n\t\t\thandlePodEvent(newObj, false)\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.podInformer = informer\n\tgo informer.Run(c.informerStopChan)\n\terr = utils.Retry(10, 500*time.Millisecond, func() error {\n\t\treturn utils.InformerSynced(informer.HasSynced, \"pod informer\")\n\t})\n\n\treturn err\n}", "func runMultisyncTests(t *testing.T, tests []controllerTest, storageClasses []*storage.StorageClass, defaultStorageClass string) {\n\tfor _, test := range tests {\n\t\tglog.V(4).Infof(\"starting multisync test %q\", test.name)\n\n\t\t// Initialize the controller\n\t\tclient := &fake.Clientset{}\n\t\tctrl, err := newTestController(client, nil, true)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Test %q construct persistent volume failed: %v\", test.name, err)\n\t\t}\n\n\t\t// Inject classes into controller via a custom lister.\n\t\tindexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})\n\t\tfor _, class := range storageClasses {\n\t\t\tindexer.Add(class)\n\t\t}\n\t\tctrl.classLister = storagelisters.NewStorageClassLister(indexer)\n\n\t\treactor := newVolumeReactor(client, ctrl, nil, nil, test.errors)\n\t\tfor _, claim := range test.initialClaims {\n\t\t\tctrl.claims.Add(claim)\n\t\t\treactor.claims[claim.Name] = claim\n\t\t}\n\t\tfor _, volume := range test.initialVolumes {\n\t\t\tctrl.volumes.store.Add(volume)\n\t\t\treactor.volumes[volume.Name] = volume\n\t\t}\n\n\t\t// Run the tested function\n\t\terr = test.test(ctrl, reactor, test)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test %q failed: %v\", test.name, err)\n\t\t}\n\n\t\t// Simulate any \"changed\" events and \"periodical sync\" until we reach a\n\t\t// stable state.\n\t\tfirstSync := true\n\t\tcounter := 0\n\t\tfor {\n\t\t\tcounter++\n\t\t\tglog.V(4).Infof(\"test %q: iteration %d\", test.name, counter)\n\n\t\t\tif counter > 100 {\n\t\t\t\tt.Errorf(\"Test %q failed: too many iterations\", test.name)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Wait for all goroutines to finish\n\t\t\treactor.waitForIdle()\n\n\t\t\tobj := reactor.popChange()\n\t\t\tif obj == nil {\n\t\t\t\t// Nothing was changed, should we exit?\n\t\t\t\tif firstSync || reactor.changedSinceLastSync > 0 {\n\t\t\t\t\t// There were some changes after the last \"periodic sync\".\n\t\t\t\t\t// Simulate \"periodic sync\" of everything (until it produces\n\t\t\t\t\t// no changes).\n\t\t\t\t\tfirstSync = false\n\t\t\t\t\tglog.V(4).Infof(\"test %q: simulating periodical sync of all claims and volumes\", test.name)\n\t\t\t\t\treactor.syncAll()\n\t\t\t\t} else {\n\t\t\t\t\t// Last sync did not produce any updates, the test reached\n\t\t\t\t\t// stable state -> finish.\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\t// waiting here cools down exponential backoff\n\t\t\ttime.Sleep(600 * time.Millisecond)\n\n\t\t\t// There were some changes, process them\n\t\t\tswitch obj.(type) {\n\t\t\tcase *v1.PersistentVolumeClaim:\n\t\t\t\tclaim := obj.(*v1.PersistentVolumeClaim)\n\t\t\t\t// Simulate \"claim updated\" event\n\t\t\t\tctrl.claims.Update(claim)\n\t\t\t\terr = ctrl.syncClaim(claim)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == versionConflictError {\n\t\t\t\t\t\t// Ignore version errors\n\t\t\t\t\t\tglog.V(4).Infof(\"test intentionaly ignores version error.\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\tt.Errorf(\"Error calling syncClaim: %v\", err)\n\t\t\t\t\t\t// Finish the loop on the first error\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Process generated changes\n\t\t\t\tcontinue\n\t\t\tcase *v1.PersistentVolume:\n\t\t\t\tvolume := obj.(*v1.PersistentVolume)\n\t\t\t\t// Simulate \"volume updated\" event\n\t\t\t\tctrl.volumes.store.Update(volume)\n\t\t\t\terr = ctrl.syncVolume(volume)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == versionConflictError {\n\t\t\t\t\t\t// Ignore version errors\n\t\t\t\t\t\tglog.V(4).Infof(\"test intentionaly ignores version error.\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\tt.Errorf(\"Error calling syncVolume: %v\", err)\n\t\t\t\t\t\t// Finish the loop on the first error\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Process generated changes\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tevaluateTestResults(ctrl, reactor, test, t)\n\t\tglog.V(4).Infof(\"test %q finished after %d iterations\", test.name, counter)\n\t}\n}", "func (m *MockMeshServiceControllerFactory) Build(mgr mc_manager.AsyncManager, clusterName string) (controller.MeshServiceController, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Build\", mgr, clusterName)\n\tret0, _ := ret[0].(controller.MeshServiceController)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestAdmissionLifecycle(t *testing.T) {\n\tnamespaceObj := &kapi.Namespace{\n\t\tObjectMeta: kapi.ObjectMeta{\n\t\t\tName: \"test\",\n\t\t\tNamespace: \"\",\n\t\t},\n\t\tStatus: kapi.NamespaceStatus{\n\t\t\tPhase: kapi.NamespaceActive,\n\t\t},\n\t}\n\tstore := cache.NewStore(cache.IndexFuncToKeyFuncAdapter(cache.MetaNamespaceIndexFunc))\n\tstore.Add(namespaceObj)\n\tmockClient := &testclient.Fake{}\n\tprojectcache.FakeProjectCache(mockClient, store, \"\")\n\thandler := &lifecycle{client: mockClient}\n\tbuild := &buildapi.Build{\n\t\tObjectMeta: kapi.ObjectMeta{Name: \"buildid\", Namespace: \"other\"},\n\t\tSpec: buildapi.BuildSpec{\n\t\t\tSource: buildapi.BuildSource{\n\t\t\t\tGit: &buildapi.GitBuildSource{\n\t\t\t\t\tURI: \"http://github.com/my/repository\",\n\t\t\t\t},\n\t\t\t\tContextDir: \"context\",\n\t\t\t},\n\t\t\tStrategy: buildapi.BuildStrategy{\n\t\t\t\tDockerStrategy: &buildapi.DockerBuildStrategy{},\n\t\t\t},\n\t\t\tOutput: buildapi.BuildOutput{\n\t\t\t\tTo: &kapi.ObjectReference{\n\t\t\t\t\tKind: \"DockerImage\",\n\t\t\t\t\tName: \"repository/data\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tStatus: buildapi.BuildStatus{\n\t\t\tPhase: buildapi.BuildPhaseNew,\n\t\t},\n\t}\n\terr := handler.Admit(admission.NewAttributesRecord(build, \"Build\", build.Namespace, \"name\", \"builds\", \"\", \"CREATE\", nil))\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error returned from admission handler: %v\", err)\n\t}\n\n\t// change namespace state to terminating\n\tnamespaceObj.Status.Phase = kapi.NamespaceTerminating\n\tstore.Add(namespaceObj)\n\n\t// verify create operations in the namespace cause an error\n\terr = handler.Admit(admission.NewAttributesRecord(build, \"Build\", build.Namespace, \"name\", \"builds\", \"\", \"CREATE\", nil))\n\tif err == nil {\n\t\tt.Errorf(\"Expected error rejecting creates in a namespace when it is terminating\")\n\t}\n\n\t// verify update operations in the namespace can proceed\n\terr = handler.Admit(admission.NewAttributesRecord(build, \"Build\", build.Namespace, \"name\", \"builds\", \"\", \"UPDATE\", nil))\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error returned from admission handler: %v\", err)\n\t}\n\n\t// verify delete operations in the namespace can proceed\n\terr = handler.Admit(admission.NewAttributesRecord(nil, \"Build\", build.Namespace, \"name\", \"builds\", \"\", \"DELETE\", nil))\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error returned from admission handler: %v\", err)\n\t}\n\n}", "func (rm *ReplicationManager) watchControllers(resourceVersion *string) {\n\twatching, err := rm.kubeClient.ReplicationControllers(api.NamespaceAll).Watch(\n\t\tlabels.Everything(),\n\t\tlabels.Everything(),\n\t\t*resourceVersion,\n\t)\n\tif err != nil {\n\t\tutil.HandleError(fmt.Errorf(\"unable to watch: %v\", err))\n\t\ttime.Sleep(5 * time.Second)\n\t\treturn\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-rm.syncTime:\n\t\t\trm.synchronize()\n\t\tcase event, open := <-watching.ResultChan():\n\t\t\tif !open {\n\t\t\t\t// watchChannel has been closed, or something else went\n\t\t\t\t// wrong with our etcd watch call. Let the util.Forever()\n\t\t\t\t// that called us call us again.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif event.Type == watch.Error {\n\t\t\t\tutil.HandleError(fmt.Errorf(\"error from watch during sync: %v\", errors.FromObject(event.Object)))\n\t\t\t\t// Clear the resource version, this may cause us to skip some elements on the watch,\n\t\t\t\t// but we'll catch them on the synchronize() call, so it works out.\n\t\t\t\t*resourceVersion = \"\"\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tglog.V(4).Infof(\"Got watch: %#v\", event)\n\t\t\trc, ok := event.Object.(*api.ReplicationController)\n\t\t\tif !ok {\n\t\t\t\tif status, ok := event.Object.(*api.Status); ok {\n\t\t\t\t\tif status.Status == api.StatusFailure {\n\t\t\t\t\t\tglog.Errorf(\"failed to watch: %v\", status)\n\t\t\t\t\t\t// Clear resource version here, as above, this won't hurt consistency, but we\n\t\t\t\t\t\t// should consider introspecting more carefully here. (or make the apiserver smarter)\n\t\t\t\t\t\t// \"why not both?\"\n\t\t\t\t\t\t*resourceVersion = \"\"\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tutil.HandleError(fmt.Errorf(\"unexpected object: %#v\", event.Object))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// If we get disconnected, start where we left off.\n\t\t\t*resourceVersion = rc.ResourceVersion\n\t\t\t// Sync even if this is a deletion event, to ensure that we leave\n\t\t\t// it in the desired state.\n\t\t\tglog.V(4).Infof(\"About to sync from watch: %v\", rc.Name)\n\t\t\tif err := rm.syncHandler(*rc); err != nil {\n\t\t\t\tutil.HandleError(fmt.Errorf(\"unexpected sync error: %v\", err))\n\t\t\t}\n\t\t}\n\t}\n}", "func TestConstructGo(t *testing.T) {\n\ttests := []struct {\n\t\tcomponentDir string\n\t\texpectedResourceCount int\n\t\tenv []string\n\t}{\n\t\t{\n\t\t\tcomponentDir: \"testcomponent\",\n\t\t\texpectedResourceCount: 9,\n\t\t\t// TODO[pulumi/pulumi#5455]: Dynamic providers fail to load when used from multi-lang components.\n\t\t\t// Until we've addressed this, set PULUMI_TEST_YARN_LINK_PULUMI, which tells the integration test\n\t\t\t// module to run `yarn install && yarn link @pulumi/pulumi` in the Go program's directory, allowing\n\t\t\t// the Node.js dynamic provider plugin to load.\n\t\t\t// When the underlying issue has been fixed, the use of this environment variable inside the integration\n\t\t\t// test module should be removed.\n\t\t\tenv: []string{\"PULUMI_TEST_YARN_LINK_PULUMI=true\"},\n\t\t},\n\t\t{\n\t\t\tcomponentDir: \"testcomponent-python\",\n\t\t\texpectedResourceCount: 9,\n\t\t\tenv: []string{pulumiRuntimeVirtualEnv(t, filepath.Join(\"..\", \"..\"))},\n\t\t},\n\t\t{\n\t\t\tcomponentDir: \"testcomponent-go\",\n\t\t\texpectedResourceCount: 8, // One less because no dynamic provider.\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.componentDir, func(t *testing.T) {\n\t\t\tpathEnv := pathEnv(t, filepath.Join(\"construct_component\", test.componentDir))\n\t\t\tintegration.ProgramTest(t, optsForConstructGo(t, test.expectedResourceCount, append(test.env, pathEnv)...))\n\t\t})\n\t}\n}", "func TestConcurrent(t *testing.T) {\n\tt.Parallel()\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tt.Cleanup(cancel)\n\n\tconfig := Config{MaxConcurrency: 4}\n\tcountdown := NewCountdown(config.MaxConcurrency)\n\tprocess := NewMockEventsProcess(ctx, t, config, func(ctx context.Context, event types.Event) error {\n\t\tdefer countdown.Decrement()\n\t\ttime.Sleep(time.Second)\n\t\treturn trace.Wrap(ctx.Err())\n\t})\n\n\ttimeBefore := time.Now()\n\tfor i := 0; i < config.MaxConcurrency; i++ {\n\t\tresource, err := types.NewAccessRequest(fmt.Sprintf(\"REQ-%v\", i+1), \"foo\", \"admin\")\n\t\trequire.NoError(t, err)\n\t\tprocess.Events.Fire(types.Event{Type: types.OpPut, Resource: resource})\n\t}\n\trequire.NoError(t, countdown.Wait(ctx))\n\n\ttimeAfter := time.Now()\n\tassert.InDelta(t, time.Second, timeAfter.Sub(timeBefore), float64(500*time.Millisecond))\n}", "func (mock *ComposeConfigInterfaceMock) ControllerCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tlockComposeConfigInterfaceMockController.RLock()\n\tcalls = mock.calls.Controller\n\tlockComposeConfigInterfaceMockController.RUnlock()\n\treturn calls\n}", "func TestGetStatus(t *testing.T) {\n\t_, ip := fakeInstanceProvider()\n\tpod := &v1.Pod{}\n\ttestCases := []struct {\n\t\tmilpaPodPhase api.PodPhase\n\t\tk8sPodPhase v1.PodPhase\n\t\tmodPod func(*api.Pod)\n\t}{\n\t\t{\n\t\t\tmilpaPodPhase: api.PodDispatching,\n\t\t\tk8sPodPhase: v1.PodPending,\n\t\t},\n\t\t{\n\t\t\tmilpaPodPhase: api.PodFailed,\n\t\t\tk8sPodPhase: v1.PodPending,\n\t\t},\n\t\t{\n\t\t\tmilpaPodPhase: api.PodFailed,\n\t\t\tk8sPodPhase: v1.PodFailed,\n\t\t\tmodPod: func(p *api.Pod) {\n\t\t\t\tp.Spec.RestartPolicy = api.RestartPolicyNever\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmilpaPodPhase: api.PodFailed,\n\t\t\tk8sPodPhase: v1.PodFailed,\n\t\t\tmodPod: func(p *api.Pod) {\n\t\t\t\tp.Status.StartFailures = allowedStartFailures + 1\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tmilpaPodPhase: api.PodRunning,\n\t\t\tk8sPodPhase: v1.PodRunning,\n\t\t},\n\t\t{\n\t\t\tmilpaPodPhase: api.PodSucceeded,\n\t\t\tk8sPodPhase: v1.PodSucceeded,\n\t\t},\n\t\t{\n\t\t\tmilpaPodPhase: api.PodTerminated,\n\t\t\tk8sPodPhase: v1.PodFailed,\n\t\t},\n\t\t{\n\t\t\tmilpaPodPhase: api.PodWaiting,\n\t\t\tk8sPodPhase: v1.PodPending,\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tmilpaPod := api.GetFakePod()\n\t\tmilpaPod.Status.Phase = tc.milpaPodPhase\n\t\tif tc.modPod != nil {\n\t\t\ttc.modPod(milpaPod)\n\t\t}\n\t\tpodStatus := getStatus(ip, milpaPod, pod)\n\t\tassert.Equal(t, podStatus.Phase, tc.k8sPodPhase)\n\t}\n}", "func getControllerDeployments(clientSet kubernetes.Interface) (*appsv1.DeploymentList, error) {\n\tdeploymentsClient := clientSet.AppsV1().Deployments(\"\") // Get deployments from all namespaces\n\tlabelSelector := metav1.LabelSelector{MatchLabels: map[string]string{constants.AppLabel: constants.OSMControllerName}}\n\tlistOptions := metav1.ListOptions{\n\t\tLabelSelector: labels.Set(labelSelector.MatchLabels).String(),\n\t}\n\treturn deploymentsClient.List(context.TODO(), listOptions)\n}", "func (t *TestSpec) RunTest(kub *helpers.Kubectl) {\n\tdefer func() { go t.Destroy(destroyDelay, kub.BasePath()) }()\n\n\tt.Kub = kub\n\terr := t.CreateManifests()\n\tgomega.Expect(err).To(gomega.BeNil(), \"cannot create pods manifest for %s\", t.Prefix)\n\n\tmanifest, err := t.ApplyManifest(kub.BasePath())\n\tgomega.Expect(err).To(gomega.BeNil(), \"cannot apply pods manifest for %s\", t.Prefix)\n\tlog.WithField(\"prefix\", t.Prefix).Infof(\"Manifest '%s' is created correctly\", manifest)\n\n\terr = t.Destination.CreateApplyManifest(t, kub.BasePath())\n\tgomega.Expect(err).To(gomega.BeNil(), \"cannot apply destination for %s\", t.Prefix)\n\n\tif t.IsPolicyInvalid() {\n\t\t// Some policies cannot be applied correctly because of different\n\t\t// rules. This code makes sure that the status of the policy has a error\n\t\t// in the status.\n\t\tcnp, err := t.InvalidNetworkPolicyApply(kub.BasePath())\n\t\tkub.Exec(fmt.Sprintf(\"%s delete cnp %s\", helpers.KubectlCmd, t.Prefix))\n\t\tgomega.Expect(err).To(gomega.BeNil(), \"Cannot apply network policy\")\n\t\tgomega.Expect(cnp).NotTo(gomega.BeNil(), \"CNP is not a valid struct\")\n\t\tgomega.Expect(cnp.Status.Nodes).NotTo(gomega.BeEmpty(), \"CNP Status is empty\")\n\n\t\tfor node, status := range cnp.Status.Nodes {\n\t\t\tgomega.Expect(status.Error).NotTo(gomega.BeEmpty(),\n\t\t\t\t\"Node %q applied invalid policy and do not raise an error\", node)\n\t\t}\n\t\treturn\n\t}\n\n\terr = t.NetworkPolicyApply(kub.BasePath())\n\tgomega.Expect(err).To(gomega.BeNil(), \"cannot apply network policy for %s\", t.Prefix)\n\n\terr = kub.CiliumEndpointWaitReady()\n\tgomega.Expect(err).To(gomega.BeNil(), \"Endpoints are not ready after timeout\")\n\n\terr = t.ExecTest()\n\tgomega.Expect(err).To(gomega.BeNil(), \"cannot execute test for %s\", t.Prefix)\n}", "func ECSPodCreatorTests() map[string]ECSPodCreatorTestCase {\n\treturn map[string]ECSPodCreatorTestCase{\n\t\t\"CreatePodSucceedsWithNonSecretSettings\": func(ctx context.Context, t *testing.T, c cocoa.ECSPodCreator) {\n\t\t\tenvVar := cocoa.NewEnvironmentVariable().SetName(\"name\").SetValue(\"value\")\n\t\t\tcontainerDef := cocoa.NewECSContainerDefinition().\n\t\t\t\tSetImage(\"image\").\n\t\t\t\tSetWorkingDir(\"working_dir\").\n\t\t\t\tAddEnvironmentVariables(*envVar).\n\t\t\t\tSetMemoryMB(128).\n\t\t\t\tSetCPU(128).\n\t\t\t\tAddPortMappings(*cocoa.NewPortMapping().SetContainerPort(1337)).\n\t\t\t\tSetName(\"container\")\n\n\t\t\texecOpts := cocoa.NewECSPodExecutionOptions().SetCluster(testutil.ECSClusterName())\n\n\t\t\topts := cocoa.NewECSPodCreationOptions().\n\t\t\t\tSetName(testutil.NewTaskDefinitionFamily(t)).\n\t\t\t\tAddContainerDefinitions(*containerDef).\n\t\t\t\tSetMemoryMB(128).\n\t\t\t\tSetCPU(128).\n\t\t\t\tSetNetworkMode(cocoa.NetworkModeBridge).\n\t\t\t\tSetExecutionOptions(*execOpts)\n\t\t\tassert.NoError(t, opts.Validate())\n\n\t\t\tp, err := c.CreatePod(ctx, *opts)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotNil(t, p)\n\n\t\t\tdefer func() {\n\t\t\t\trequire.NoError(t, p.Delete(ctx))\n\t\t\t}()\n\n\t\t\tps := p.StatusInfo()\n\t\t\tassert.Equal(t, cocoa.StatusStarting, ps.Status)\n\t\t},\n\t\t\"CreatePodFailsWithInvalidCreationOpts\": func(ctx context.Context, t *testing.T, c cocoa.ECSPodCreator) {\n\t\t\topts := cocoa.NewECSPodCreationOptions()\n\n\t\t\tp, err := c.CreatePod(ctx, *opts)\n\t\t\trequire.Error(t, err)\n\t\t\trequire.Zero(t, p)\n\t\t},\n\t\t\"CreatePodFailsWithSecretsButNoVault\": func(ctx context.Context, t *testing.T, c cocoa.ECSPodCreator) {\n\t\t\tenvVar := cocoa.NewEnvironmentVariable().\n\t\t\t\tSetName(\"envVar\").\n\t\t\t\tSetSecretOptions(*cocoa.NewSecretOptions().\n\t\t\t\t\tSetName(testutil.NewSecretName(t)).\n\t\t\t\t\tSetNewValue(\"value\"))\n\t\t\tcontainerDef := cocoa.NewECSContainerDefinition().\n\t\t\t\tSetImage(\"image\").\n\t\t\t\tAddEnvironmentVariables(*envVar).\n\t\t\t\tSetName(\"container\")\n\n\t\t\texecOpts := cocoa.NewECSPodExecutionOptions().SetCluster(testutil.ECSClusterName())\n\n\t\t\topts := cocoa.NewECSPodCreationOptions().\n\t\t\t\tSetName(testutil.NewTaskDefinitionFamily(t)).\n\t\t\t\tAddContainerDefinitions(*containerDef).\n\t\t\t\tSetMemoryMB(128).\n\t\t\t\tSetCPU(128).\n\t\t\t\tSetTaskRole(testutil.ECSTaskRole()).\n\t\t\t\tSetExecutionRole(testutil.ECSExecutionRole()).\n\t\t\t\tSetExecutionOptions(*execOpts)\n\t\t\tassert.NoError(t, opts.Validate())\n\n\t\t\tp, err := c.CreatePod(ctx, *opts)\n\t\t\trequire.Error(t, err)\n\t\t\trequire.Zero(t, p)\n\t\t},\n\t\t\"CreatePodFailsWithRepoCredsButNoVault\": func(ctx context.Context, t *testing.T, c cocoa.ECSPodCreator) {\n\t\t\tstoredCreds := cocoa.NewStoredRepositoryCredentials().\n\t\t\t\tSetUsername(\"username\").\n\t\t\t\tSetPassword(\"password\")\n\t\t\tcreds := cocoa.NewRepositoryCredentials().\n\t\t\t\tSetName(testutil.NewSecretName(t)).\n\t\t\t\tSetNewCredentials(*storedCreds)\n\t\t\tcontainerDef := cocoa.NewECSContainerDefinition().\n\t\t\t\tSetImage(\"image\").\n\t\t\t\tSetRepositoryCredentials(*creds).\n\t\t\t\tSetName(\"container\")\n\n\t\t\texecOpts := cocoa.NewECSPodExecutionOptions().SetCluster(testutil.ECSClusterName())\n\n\t\t\topts := cocoa.NewECSPodCreationOptions().\n\t\t\t\tSetName(testutil.NewTaskDefinitionFamily(t)).\n\t\t\t\tAddContainerDefinitions(*containerDef).\n\t\t\t\tSetMemoryMB(128).\n\t\t\t\tSetCPU(128).\n\t\t\t\tSetTaskRole(testutil.ECSTaskRole()).\n\t\t\t\tSetExecutionRole(testutil.ECSExecutionRole()).\n\t\t\t\tSetExecutionOptions(*execOpts)\n\t\t\tassert.NoError(t, opts.Validate())\n\n\t\t\tp, err := c.CreatePod(ctx, *opts)\n\t\t\trequire.Error(t, err)\n\t\t\trequire.Zero(t, p)\n\t\t},\n\t}\n}" ]
[ "0.84638107", "0.8257509", "0.8186716", "0.60766035", "0.6004586", "0.59796965", "0.59095436", "0.5886478", "0.58263564", "0.5762557", "0.56721723", "0.558922", "0.5555907", "0.552705", "0.54982966", "0.5487726", "0.5478104", "0.54566073", "0.54116815", "0.5399274", "0.5397287", "0.53831124", "0.5361766", "0.53452146", "0.53281623", "0.53267515", "0.52472734", "0.52287954", "0.52143574", "0.52141976", "0.51844275", "0.5173044", "0.5171113", "0.51710427", "0.51660305", "0.516224", "0.515601", "0.51433486", "0.5142413", "0.51164305", "0.5103288", "0.50923485", "0.50708205", "0.5052067", "0.505137", "0.5045441", "0.50349444", "0.50343037", "0.503374", "0.503335", "0.50230014", "0.50012356", "0.49980873", "0.49966413", "0.49963886", "0.49950498", "0.4983873", "0.497605", "0.49729398", "0.49639863", "0.49630603", "0.49536446", "0.4952177", "0.4940275", "0.49355957", "0.4934006", "0.49330196", "0.49272802", "0.49231806", "0.4921366", "0.4907492", "0.4907492", "0.49047804", "0.4900442", "0.48930517", "0.4878781", "0.48750737", "0.48745224", "0.4865608", "0.4859887", "0.4851759", "0.48477086", "0.4831941", "0.48176813", "0.48141533", "0.4811102", "0.4808589", "0.4804731", "0.4799627", "0.47935545", "0.4792832", "0.47924808", "0.4787456", "0.47651082", "0.47648245", "0.47590473", "0.474897", "0.47489592", "0.47480914", "0.47465536" ]
0.88891226
0
Register registers new database migration. Must be called from file with name like "1_initialize_db.go", where: 1 migration version; initialize_db comment.
func Register(fns ...func(DB) error) error { return DefaultCollection.Register(fns...) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Register(up, down func(DB) error) error {\n\t_, file, _, _ := runtime.Caller(1)\n\tversion, err := extractVersion(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tallMigrations = append(allMigrations, Migration{\n\t\tVersion: version,\n\t\tUp: up,\n\t\tDown: down,\n\t})\n\treturn nil\n}", "func registerMigration(dir string) {\n\tmigrations.MustRegisterTx(func(db migrations.DB) error {\n\t\tpath := dir + \"/up.sql\"\n\t\tsql, err := loadMigrationFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = db.Exec(sql)\n\t\treturn err\n\t}, func(db migrations.DB) error {\n\t\tpath := dir + \"/down.sql\"\n\t\tsql, err := loadMigrationFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = db.Exec(sql)\n\t\treturn err\n\t})\n}", "func Register(namespace string, migration Migration) {\n\tif _, ok := namespacedMigrations[namespace]; !ok {\n\t\tnamespacedMigrations[namespace] = make(Migrations)\n\t}\n\n\tnamespacedMigrations[namespace][migration.Version] = migration\n}", "func migrateNew() {\n\tif len(flag.Args()) == 0 {\n\t\tlog.Fatalf(\"ERROR: Migration's name not specified\\n\")\n\t\treturn\n\t}\n\twd, _ := os.Getwd()\n\tname := path.Join(wd, \"migrations\", fmt.Sprintf(\"%d_%s.sql\", time.Now().Unix(), flag.Arg(0)))\n\tfile, err := os.Create(name)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: %s\\n\", err)\n\t\treturn\n\t}\n\tfmt.Fprintf(file, \"-- +migrate Up\\n\")\n\tfmt.Fprintf(file, \"-- SQL in section 'Up' is executed when this migration is applied\\n\\n\\n\")\n\tfmt.Fprintf(file, \"-- +migrate Down\\n\")\n\tfmt.Fprintf(file, \"-- SQL in section 'Down' is executed when this migration is rolled back\\n\\n\\n\")\n\terr = file.Close()\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: %s\\n\", err)\n\t} else {\n\t\tlog.Printf(\"INFO: File %s has been successfully created\\n\", name)\n\t}\n}", "func init() {\n\tMigrations = append(Migrations, addUserMigration0001)\n}", "func Migration(table, directory string) Initializer {\n\tif _, err := os.Stat(directory); os.IsNotExist(err) {\n\t\tstartup_base.PanicOnError(err, \"No database migration files found\")\n\t}\n\n\treturn func(db *sqlx.DB) error {\n\t\tmigrate.SetTable(table)\n\n\t\tmigrations := &migrate.FileMigrationSource{Dir: directory}\n\t\tn, err := migrate.Exec(db.DB, \"postgres\", migrations, migrate.Up)\n\t\tif err != nil {\n\t\t\treturn errors.WithMessage(err, \"applying database migration\")\n\t\t}\n\n\t\tlogrus.WithField(\"prefix\", \"database\").\n\t\t\tInfof(\"%d migrations executed\", n)\n\n\t\treturn nil\n\t}\n}", "func InitDatabase(database *models.Database) error {\n\tdb, err := getDatabase(database)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Registering database: %s\", db.String())\n\tif err := db.Register(); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(\"Register database completed\")\n\treturn nil\n}", "func initialMigration() {\n\tdb, err := gorm.Open(\"sqlite3\", \"test.db\")\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tpanic(\"failed to connect database\")\n\t}\n\tdefer db.Close()\n\n\t// Migrate the schema\n\tdb.AutoMigrate(&User{})\n}", "func Initialize(ctx context.Context, migrationDir string, db Database, queries QueryAdapter) error {\n\t// make sure migrations can persist\n\t_, err := db.ExecContext(ctx, queries.CreateTableSQL())\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\t// Get the migration with the highest ID number\n\trow := db.QueryRowContext(ctx, queries.SelectLatestMigrationSQL())\n\tif err := row.Err(); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tlatest := 0\n\n\tif err := row.Scan(&latest); err != nil {\n\t\tif err != sql.ErrNoRows {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t}\n\n\t// Load up the migrations and run starting from the last known run migration\n\tmigs := fromDir(migrationDir)\n\tfor _, migration := range migs[:latest] {\n\t\tfmt.Printf(\"Already ran migration: %d\\n\", migration.Order)\n\t}\n\n\tfor _, migration := range migs[latest:] {\n\t\tfmt.Printf(\"Running migration %d\\n\", migration.Order)\n\t\tif _, err := db.ExecContext(ctx, migration.Up); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := db.ExecContext(ctx, queries.InsertMigrationSQL(), migration.Order); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func RegisterDBCreator(name string, creator KVDBCreator) {\n\t_, ok := dbCreators[name]\n\tif ok {\n\t\tpanic(fmt.Sprintf(\"duplicate register database %s\", name))\n\t}\n\n\tdbCreators[name] = creator\n}", "func TestInitSchemaWithMigrations(t *testing.T) {\n\tforEachDatabase(t, func(db *sqlx.DB) {\n\t\tm := New(db, DefaultOptions, migrations)\n\t\tm.InitSchema(func(tx *sqlx.DB) error {\n\t\t\tq := `CREATE TABLE \"people\" (\"id\" serial,\"created_at\" timestamp with time zone,\"updated_at\" timestamp with time zone,\"deleted_at\" timestamp with time zone,\"name\" text , PRIMARY KEY (\"id\"))`\n\t\t\t_, err := tx.Exec(q)\n\t\t\treturn err\n\t\t})\n\n\t\tassert.NoError(t, m.Migrate())\n\t\tassert.True(t, m.hasTable(\"people\"))\n\t\tassert.False(t, m.hasTable(\"pets\"))\n\t\tassert.Equal(t, 3, tableCount(t, db, \"migrations\"))\n\t})\n}", "func InitialMigration() {\r\n\tdb, err = gorm.Open(\"sqlite3\", \"collegiateCS.db\")\r\n\tif err != nil {\r\n\t\tfmt.Println(err.Error())\r\n\t\tpanic(\"Failed to connect to db\")\r\n\t}\r\n\tdefer db.Close()\r\n\r\n\t//db.AutoMigrate(&dbStats{})\r\n\t//db.AutoMigrate(&dbPlayer{})\r\n\t//db.AutoMigrate(&dbRoster{})\r\n\t//db.AutoMigrate(&dbGame{})\r\n\t//db.AutoMigrate(&dbSet{})\r\n}", "func RegisterFS(namespace string, in fs.FS) error {\n\tif _, ok := namespacedMigrations[namespace]; !ok {\n\t\tnamespacedMigrations[namespace] = make(Migrations)\n\t}\n\n\treturn fs.WalkDir(in, \".\", func(path string, d fs.DirEntry, err error) error {\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// We only accept .sql files\n\t\text := filepath.Ext(path)\n\t\tif strings.ToLower(ext) != \".sql\" {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Get the version name, it must be an int\n\t\tname := strings.TrimSuffix(filepath.Base(path), ext)\n\t\tversion, err := strconv.Atoi(name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse filename as int: %w\", err)\n\t\t}\n\n\t\t// Finally, let's read the contents...\n\t\tfile, err := in.Open(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open file: %w\", err)\n\t\t}\n\n\t\tbs, err := ioutil.ReadAll(file)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read file: %w\", err)\n\t\t}\n\n\t\tnamespacedMigrations[namespace][version] = Migration{\n\t\t\tVersion: version,\n\t\t\tCommands: []string{string(bs)},\n\t\t}\n\n\t\treturn err\n\t})\n}", "func TestInitSchemaExistingMigrations(t *testing.T) {\n\tforEachDatabase(t, func(db *sqlx.DB) {\n\t\tm := New(db, DefaultOptions, migrations)\n\n\t\t// Migrate without initialisation\n\t\tassert.NoError(t, m.Migrate())\n\n\t\t// Then migrate again, this time with a non empty initialisation\n\t\t// This initialisation should not happen!\n\t\tm.InitSchema(func(tx *sqlx.DB) error {\n\t\t\tq := `CREATE TABLE \"cars\" (\"id\" serial,\"created_at\" timestamp with time zone,\"updated_at\" timestamp with time zone,\"deleted_at\" timestamp with time zone,\"name\" text , PRIMARY KEY (\"id\"))`\n\t\t\t_, err := tx.Exec(q)\n\t\t\treturn err\n\t\t})\n\t\tassert.NoError(t, m.Migrate())\n\n\t\tassert.False(t, m.hasTable(\"cars\"))\n\t\tassert.Equal(t, 2, tableCount(t, db, \"migrations\"))\n\t})\n}", "func setupDatabase(driver string, db *sql.DB) error {\n\treturn ddl.Migrate(driver, db)\n}", "func InitializeDatabase() {\n\tvar err error\n\tconnectionString := os.Getenv(\"POSTGRES_CONNECTION_STRING\")\n\n\tif connectionString == \"\" {\n\t\tconnectionString = \"user=crudwizard password=crudwizard dbname=crudwizard sslmode=disable\"\n\t}\n\n\tDatabase, err = gorm.Open(\"postgres\", connectionString)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvalidations.RegisterCallbacks(Database)\n\n\tDatabase.LogMode(true)\n\tDatabase.AutoMigrate(&models.User{})\n\tDatabase.AutoMigrate(&models.Project{})\n\tDatabase.AutoMigrate(&models.AuthToken{})\n}", "func (drv SQLiteDriver) InsertMigration(db Transaction, version string, project string) error {\n\t_, err := db.Exec(\"insert into schema_migrations (version, project) values (?, ?)\", version, project)\n\n\treturn err\n}", "func createMigrationsTable(db *sql.DB) {\n\tquery := `\n\t\tCREATE TABLE IF NOT EXISTS _migrations(\n\t\t id serial PRIMARY KEY,\n\t\t migration VARCHAR (255) UNIQUE NOT NULL,\n\t\t migrated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n\t\t);\n\t`\n\n\t_, err := db.Exec(query)\n\tif err != nil {\n\t\tLogErr(\"%s\\n\", err)\n\t}\n}", "func AddMigration(up func(*sql.Tx) error, down func(*sql.Tx) error) {\n\t// We can't just use globalGoose.AddMigration here because we need to\n\t// correctly record the caller.\n\t_, filename, _, _ := runtime.Caller(1)\n\tv, _ := NumericComponent(filename)\n\tmigration := &Migration{Version: v, Next: -1, Previous: -1, UpFn: up, DownFn: down, Source: filename}\n\n\tglobalGoose.Migrations = append(globalGoose.Migrations, migration)\n}", "func migrate() {\n\n}", "func InitialMigration() {\r\n\r\n\tdb, err = gorm.Open(\"sqlite3\", \"website.db\")\r\n\tif err != nil {\r\n\t\tpanic(\"Failed to connect!\")\r\n\t}\r\n\tdefer db.Close()\r\n\r\n\tdb.AutoMigrate(&Website{}, &WebsiteHealthStatusHistory{})\r\n}", "func Migrate(db *sql.DB) {\n\tmodel.CreateUserTable(db)\n}", "func registerMigrations(ctx context.Context, db dbutil.DB, outOfBandMigrationRunner *oobmigration.Runner) error {\n\tmigrators := map[int]oobmigration.Migrator{\n\t\tmigration.DiagnosticsCountMigrationID: migration.NewDiagnosticsCountMigrator(services.lsifStore, config.DiagnosticsCountMigrationBatchSize),\n\t\tmigration.DefinitionsCountMigrationID: migration.NewLocationsCountMigrator(services.lsifStore, \"lsif_data_definitions\", config.DefinitionsCountMigrationBatchSize),\n\t\tmigration.ReferencesCountMigrationID: migration.NewLocationsCountMigrator(services.lsifStore, \"lsif_data_references\", config.ReferencesCountMigrationBatchSize),\n\t}\n\n\tfor id, migrator := range migrators {\n\t\tif err := outOfBandMigrationRunner.Register(id, migrator, oobmigration.MigratorOptions{Interval: time.Second}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (drv ClickHouseDriver) InsertMigration(db Transaction, version string) error {\n\t_, err := db.Exec(\"insert into schema_migrations (version) values (?)\", version)\n\treturn err\n}", "func RegisterDatabase(db Database, ro bool) (err error) {\n\tif err = db.Open(); err != nil {\n\t\treturn\n\t}\n\n\tif ro {\n\t\treadOnlyDB = db\n\t} else {\n\t\treadWriteDB = db\n\t\tif readOnlyDB == nil {\n\t\t\treadOnlyDB = db\n\t\t}\n\t}\n\n\treturn\n}", "func Migrate() {\n\tlog.Info(\"Executing migrations...\")\n\tDb.AutoMigrate(&models.Repository{}, &models.Week{}, &models.Contributor{})\n}", "func (db *DbCtxt) InitDatabase() error {\n\tvar models []interface{}\n\tmodels = append(models,\n\t\t&Hotel{},\n\t\t&Room{},\n\t\t&RatePlan{},\n\t)\n\tfor _, model := range models {\n\t\terr := db.client.AutoMigrate(model)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func TestInitSchemaAlreadyInitialised(t *testing.T) {\n\n\tforEachDatabase(t, func(db *sqlx.DB) {\n\t\tm := New(db, DefaultOptions, []*Migration{})\n\n\t\t// Migrate with empty initialisation\n\t\tm.InitSchema(func(tx *sqlx.DB) error {\n\t\t\treturn nil\n\t\t})\n\t\tassert.NoError(t, m.Migrate())\n\n\t\t// Then migrate again, this time with a non empty initialisation\n\t\t// This second initialisation should not happen!\n\t\tm.InitSchema(func(tx *sqlx.DB) error {\n\t\t\tq := `CREATE TABLE \"cars\" (\"id\" serial,\"created_at\" timestamp with time zone,\"updated_at\" timestamp with time zone,\"deleted_at\" timestamp with time zone,\"name\" text , PRIMARY KEY (\"id\"))`\n\t\t\t_, err := tx.Exec(q)\n\t\t\treturn err\n\t\t})\n\t\tassert.NoError(t, m.Migrate())\n\n\t\tassert.False(t, m.hasTable(\"cars\"))\n\t\tassert.Equal(t, 1, tableCount(t, db, \"migrations\"))\n\t})\n}", "func Migrate(db *gorm.DB) {\n\tdb.AutoMigrate(&User{})\n\tfmt.Println(\"Auto migration has been completed\")\n}", "func migrate0001(db *gorm.DB) error {\n\tmigrationName := \"oauth_initial\"\n\n\tmigration := new(migrations.Migration)\n\tfound := !db.Where(\"name = ?\", migrationName).First(migration).RecordNotFound()\n\n\tif found {\n\t\tlogger.INFO.Printf(\"Skipping %s migration\", migrationName)\n\t\treturn nil\n\t}\n\n\tlogger.INFO.Printf(\"Running %s migration\", migrationName)\n\n\tvar err error\n\n\t// Create oauth_clients table\n\tif err := db.CreateTable(new(Client)).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error creating oauth_clients table: %s\", err)\n\t}\n\n\t// Create oauth_scopes table\n\tif err := db.CreateTable(new(Scope)).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error creating oauth_scopes table: %s\", err)\n\t}\n\n\t// Create oauth_users table\n\tif err := db.CreateTable(new(User)).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error creating oauth_users table: %s\", err)\n\t}\n\n\t// Create oauth_refresh_tokens table\n\tif err := db.CreateTable(new(RefreshToken)).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error creating oauth_refresh_tokens table: %s\", err)\n\t}\n\n\t// Create oauth_access_tokens table\n\tif err := db.CreateTable(new(AccessToken)).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error creating oauth_access_tokens table: %s\", err)\n\t}\n\n\t// Create oauth_authorization_codes table\n\tif err := db.CreateTable(new(AuthorizationCode)).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error creating oauth_authorization_codes table: %s\", err)\n\t}\n\n\t// Add foreign key on oauth_refresh_tokens.client_id\n\terr = db.Model(new(RefreshToken)).AddForeignKey(\n\t\t\"client_id\",\n\t\t\"oauth_clients(id)\",\n\t\t\"RESTRICT\",\n\t\t\"RESTRICT\",\n\t).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating foreign key on \"+\n\t\t\t\"oauth_refresh_tokens.client_id for oauth_clients(id): %s\", err)\n\t}\n\n\t// Add foreign key on oauth_refresh_tokens.user_id\n\terr = db.Model(new(RefreshToken)).AddForeignKey(\n\t\t\"user_id\",\n\t\t\"oauth_users(id)\",\n\t\t\"RESTRICT\",\n\t\t\"RESTRICT\",\n\t).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating foreign key on \"+\n\t\t\t\"oauth_refresh_tokens.user_id for oauth_users(id): %s\", err)\n\t}\n\n\t// Add foreign key on oauth_access_tokens.client_id\n\terr = db.Model(new(AccessToken)).AddForeignKey(\n\t\t\"client_id\",\n\t\t\"oauth_clients(id)\",\n\t\t\"RESTRICT\",\n\t\t\"RESTRICT\",\n\t).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating foreign key on \"+\n\t\t\t\"oauth_access_tokens.client_id for oauth_clients(id): %s\", err)\n\t}\n\n\t// Add foreign key on oauth_access_tokens.user_id\n\terr = db.Model(new(AccessToken)).AddForeignKey(\n\t\t\"user_id\",\n\t\t\"oauth_users(id)\",\n\t\t\"RESTRICT\",\n\t\t\"RESTRICT\",\n\t).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating foreign key on \"+\n\t\t\t\"oauth_access_tokens.user_id for oauth_users(id): %s\", err)\n\t}\n\n\t// Add foreign key on oauth_authorization_codes.client_id\n\terr = db.Model(new(AuthorizationCode)).AddForeignKey(\n\t\t\"client_id\",\n\t\t\"oauth_clients(id)\",\n\t\t\"RESTRICT\",\n\t\t\"RESTRICT\",\n\t).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating foreign key on \"+\n\t\t\t\"oauth_authorization_codes.client_id for oauth_clients(id): %s\", err)\n\t}\n\n\t// Add foreign key on oauth_authorization_codes.user_id\n\terr = db.Model(new(AuthorizationCode)).AddForeignKey(\n\t\t\"user_id\",\n\t\t\"oauth_users(id)\",\n\t\t\"RESTRICT\",\n\t\t\"RESTRICT\",\n\t).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating foreign key on \"+\n\t\t\t\"oauth_authorization_codes.user_id for oauth_users(id): %s\", err)\n\t}\n\n\t// Save a record to migrations table,\n\t// so we don't rerun this migration again\n\tmigration.Name = migrationName\n\tif err := db.Create(migration).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error saving record to migrations table: %s\", err)\n\t}\n\n\treturn nil\n}", "func Migrate(logger logger.Logger, db *sqlx.DB) {\n\tlogger.Info().Msg(\"Starting database migration\")\n\n\tdbInstance, err := postgres.WithInstance(db.DB, &postgres.Config{})\n\tif err != nil {\n\t\tlogger.Fatal().Err(err).Msg(\"Failed to create migrate database instance\")\n\t}\n\n\tsrcInstance, err := httpfs.New(pkger.Dir(\"/migrate/migrations\"), \"\")\n\tif err != nil {\n\t\tlogger.Fatal().Err(err).Msg(\"Failed to create migrate source instance\")\n\t}\n\n\tms, err := migrate.NewWithInstance(\"httpfs\", srcInstance, \"postgres\", dbInstance)\n\tif err != nil {\n\t\tlogger.Fatal().Err(err).Msg(\"Failed to create migration service\")\n\t}\n\n\tversion, _, err := ms.Version()\n\tif err != nil {\n\t\tif err == migrate.ErrNilVersion {\n\t\t\tlogger.Info().Msg(\"No migrations have been applied yet\")\n\t\t} else {\n\t\t\tlogger.Fatal().Err(err).Msg(\"Failed to get migration version\")\n\t\t}\n\t} else {\n\t\tlogger.Info().Uint(\"migrationVersion\", version).Send()\n\t}\n\n\tif err := ms.Up(); err != nil {\n\t\tif err == migrate.ErrNoChange {\n\t\t\tlogger.Info().Msg(\"No new migrations to apply\")\n\t\t} else {\n\t\t\tlogger.Fatal().Err(err).Msg(\"Failed to apply migrations\")\n\t\t}\n\t}\n\n\tlogger.Info().Msg(\"Database migration complete\")\n}", "func Register(ext *sqlite.ExtensionApi, opt *options.Options) (_ sqlite.ErrorCode, err error) {\n\t// register virtual table modules\n\tvar modules = map[string]sqlite.Module{\n\t\t\"commits\": &LogModule{Locator: opt.Locator, Context: opt.Context},\n\t\t\"refs\": &RefModule{Locator: opt.Locator, Context: opt.Context},\n\t\t\"stats\": native.NewStatsModule(opt.Locator, opt.Context),\n\t\t\"files\": native.NewFilesModule(opt.Locator, opt.Context),\n\t\t\"blame\": native.NewBlameModule(opt.Locator, opt.Context),\n\t}\n\n\tfor name, mod := range modules {\n\t\tif err = ext.CreateModule(name, mod); err != nil {\n\t\t\treturn sqlite.SQLITE_ERROR, errors.Wrapf(err, \"failed to register %q module\", name)\n\t\t}\n\t}\n\n\tvar fns = map[string]sqlite.Function{\n\t\t\"commit_from_tag\": &CommitFromTagFn{},\n\t}\n\n\tfor name, fn := range fns {\n\t\tif err = ext.CreateFunction(name, fn); err != nil {\n\t\t\treturn sqlite.SQLITE_ERROR, errors.Wrapf(err, \"failed to register %q function\", name)\n\t\t}\n\t}\n\n\treturn sqlite.SQLITE_OK, nil\n}", "func InitDatabase(dbName *string, dst ...interface{}) {\n\tlog.Info().Msgf(\"Loading database %v\", *dbName)\n\tvar err error\n\tdbFile = sqlite.Open(fmt.Sprintf(\"%v.db\", *dbName))\n\tdatastore, err = gorm.Open(dbFile, &gorm.Config{\n\t\tDisableForeignKeyConstraintWhenMigrating: true,\n\t})\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\n\t// Migrate the schema\n\terr = datastore.AutoMigrate(dst...)\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Migration failed! Please check the logs!\")\n\t}\n}", "func init() {\n\tSchemeBuilder.Register(&AtlasDatabaseUser{}, &AtlasDatabaseUserList{})\n}", "func Migrate() error {\n\n\toldVersion, newVersion, err := migrations.Run(database.DB, \"init\")\n\toldVersion, newVersion, err = migrations.Run(database.DB)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif newVersion != oldVersion {\n\t\tlog.Printf(\"migrated from version %d to %d\\n\", oldVersion, newVersion)\n\t}\n\t// else {\n\t// \tlog.Printf(\"version is %d\\n\", oldVersion)\n\t// }\n\treturn nil\n}", "func init() {\n\tmigrations.AddPluginMigration(\"inputs.cassandra\", migrate)\n}", "func (my *MySQL) Register(sql string) {\n my.init_cmds = append(my.init_cmds, sql)\n}", "func (db *Database) RunMigrations(ctx context.Context) error {\n\tlogger := logging.FromContext(ctx)\n\tm := gormigrate.New(db.db, gormigrate.DefaultOptions, []*gormigrate.Migration{\n\t\t{\n\t\t\tID: \"00001-CreateUsers\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating users table\")\n\t\t\t\treturn tx.AutoMigrate(&User{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"users\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00002-CreateVerificationCodes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating verification codes table\")\n\t\t\t\treturn tx.AutoMigrate(&VerificationCode{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"verification_codes\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00003-CreateAuthorizedApps\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating authorized apps table\")\n\t\t\t\treturn tx.AutoMigrate(&AuthorizedApp{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"authorized_apps\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00004-CreateTokens\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating tokens table\")\n\t\t\t\treturn tx.AutoMigrate(&Token{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"tokens\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00005-CreateCleanups\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating cleanup status table\")\n\t\t\t\tif err := tx.AutoMigrate(&CleanupStatus{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// Seed database w/ cleanup record.\n\t\t\t\tif err := tx.Create(&CleanupStatus{Type: \"cleanup\", Generation: 1, NotBefore: time.Now()}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"cleanup_statuses\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00006-AddIndexes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: add users purge index\")\n\t\t\t\tif err := tx.Model(&User{}).AddIndex(\"users_purge_index\", \"disabled\", \"updated_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: add verification code purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).AddIndex(\"ver_code_purge_index\", \"expires_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: add tokens purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).AddIndex(\"token_purge_index\", \"expires_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: drop users purge index\")\n\t\t\t\tif err := tx.Model(&User{}).RemoveIndex(\"users_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: drop verification code purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).RemoveIndex(\"ver_code_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: drop tokens purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).RemoveIndex(\"token_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00007-AddSymptomOnset\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Info(\"db migrations: rename test_date to symptom_date\")\n\t\t\t\t// AutoMigrate will add missing fields.\n\t\t\t\tif err := tx.AutoMigrate(&VerificationCode{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// If not upgrading from an old version, this column will have never been created.\n\t\t\t\tif tx.NewScope(&VerificationCode{}).HasColumn(\"test_date\") {\n\t\t\t\t\tif err := tx.Model(&VerificationCode{}).DropColumn(\"test_date\").Error; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err := tx.AutoMigrate(&Token{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// If not upgrading from an old version, this column will have never been created.\n\t\t\t\tif tx.NewScope(&Token{}).HasColumn(\"test_date\") {\n\t\t\t\t\tif err := tx.Model(&Token{}).DropColumn(\"test_date\").Error; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Info(\"db migrations: rename symptom_date to test_date\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).DropColumn(\"symptom_date\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := tx.Model(&Token{}).DropColumn(\"symptom_date\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00008-AddKeyTypes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: upgrading authorized_apps table.\")\n\t\t\t\treturn tx.AutoMigrate(&AuthorizedApp{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"admin_key\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00009-AddIssuerColumns\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: adding issuer columns to issued codes\")\n\t\t\t\treturn tx.AutoMigrate(&VerificationCode{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"issuing_user\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"issuing_app\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00010-AddSMSConfig\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: adding sms_configs table\")\n\t\t\t\treturn tx.AutoMigrate(&SMSConfig{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"sms_configs\").Error\n\t\t\t},\n\t\t},\n\t})\n\n\tlogger.Infof(\"database migrations complete\")\n\n\treturn m.Migrate()\n}", "func Migrate(l log.Logger, db *sqlx.DB) error {\n\tmigrations, err := pgmigrate.LoadMigrations(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: \"schema\"})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnumber, err := pgmigrate.DefaultConfig.Migrate(db.DB, migrations)\n\tl.Log(\"msg\", \"migrated postgres\", \"count\", number.Len(), \"total_migrations\", migrations.Len())\n\treturn err\n}", "func (b *bot) migrateDB() {\n\tif _, err := b.DB().Exec(`create table if not exists variables (\n\t\t\tid integer primary key,\n\t\t\tname string,\n\t\t\tvalue string\n\t\t);`); err != nil {\n\t\tlog.Fatal().Err(err).Msgf(\"Initial db migration create variables table\")\n\t}\n\tif _, err := b.DB().Exec(`create table if not exists pluginBlacklist (\n\t\t\tchannel string,\n\t\t\tname string,\n\t\t\tprimary key (channel, name)\n\t\t);`); err != nil {\n\t\tlog.Fatal().Err(err).Msgf(\"Initial db migration create blacklist table\")\n\t}\n\tif _, err := b.DB().Exec(`create table if not exists pluginWhitelist (\n\t\t\tname string primary key\n\t\t);`); err != nil {\n\t\tlog.Fatal().Err(err).Msgf(\"Initial db migration create whitelist table\")\n\t}\n}", "func InitialMigration() {\n\tconnection := GetDatabase()\n\tdefer Closeddatabase(connection)\n\tconnection.AutoMigrate(User{})\n}", "func MigrateDB(db *sql.DB) {\n\tmigrationSource := &migrate.PackrMigrationSource{\n\t\tBox: packr.NewBox(\"../migrations\"),\n\t}\n\n\tfmt.Printf(\"[migration] Begin migration...\\n\\n\")\n\n\ti, err := migrate.Exec(db, \"mysql\", migrationSource, migrate.Up)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tmigrations, _ := migrationSource.FindMigrations()\n\n\tif len(migrations) > 0 {\n\t\tfmt.Printf(\"[migration] Last migration id: %s\\n\\n\", migrations[len(migrations)-1].Id)\n\t}\n\n\tif i > 0 {\n\t\tfmt.Printf(\"[migration] %d migrations executed\\n\\n\", i)\n\t} else {\n\t\tfmt.Printf(\"[migration] There is no new migration\\n\\n\")\n\t}\n\n\tfmt.Printf(\"[migration] Migration finished\\n\\n\")\n}", "func (c *Config) MigrateUp(ctx context.Context, txOpts *sql.TxOptions, logFilename func(string)) error {\n\tmigratedVersions, err := c.existingVersions(ctx)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"unable to query existing versions\")\n\t}\n\n\ttx, err := c.adapter.BeginTx(ctx, c.db, txOpts)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"unable to create transaction\")\n\t}\n\tdefer tx.Rollback() // ok to fail rollback if we did `tx.Commit`\n\n\tmigrationFiles := c.migrationFiles\n\tsort.SliceStable(migrationFiles, func(i int, j int) bool {\n\t\treturn strings.Compare(migrationFiles[i].Name(), migrationFiles[j].Name()) == -1 // in ascending order\n\t})\n\n\tfor i := range migrationFiles {\n\t\tcurrFile := migrationFiles[i]\n\t\tcurrName := currFile.Name()\n\t\tif !strings.HasSuffix(currName, \".up.sql\") {\n\t\t\tcontinue // skip if this isn't a `.up.sql`\n\t\t}\n\t\tcurrVer := strings.Split(currName, \"_\")[0]\n\t\tif _, found := migratedVersions.Find(currVer); found {\n\t\t\tcontinue // skip if we've migrated this version\n\t\t}\n\n\t\t// read the file, run the sql and insert a row into `dbmigrate_versions`\n\t\tfilecontent, err := c.fileContent(currName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, currName)\n\t\t}\n\n\t\tif len(bytes.TrimSpace(filecontent)) == 0 {\n\t\t\t// treat empty file as success; don't run it\n\t\t} else if _, err := tx.ExecContext(ctx, string(filecontent)); err != nil {\n\t\t\treturn errors.Wrapf(err, currName)\n\t\t}\n\t\tif _, err := tx.ExecContext(ctx, c.adapter.InsertNewVersion, currVer); err != nil {\n\t\t\treturn errors.Wrapf(err, \"fail to register version %q\", currVer)\n\t\t}\n\t\tlogFilename(currName)\n\t}\n\treturn tx.Commit()\n}", "func Migrate(x *xorm.Engine, db *gorm.DB) error {\n\tif err := x.Sync(new(Version)); err != nil {\n\t\treturn fmt.Errorf(\"sync: %v\", err)\n\t}\n\n\tcurrentVersion := &Version{ID: 1}\n\thas, err := x.Get(currentVersion)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get: %v\", err)\n\t} else if !has {\n\t\t// If the version record does not exist we think\n\t\t// it is a fresh installation and we can skip all migrations.\n\t\tcurrentVersion.ID = 0\n\t\tcurrentVersion.Version = int64(minDBVersion + len(migrations))\n\n\t\tif _, err = x.InsertOne(currentVersion); err != nil {\n\t\t\treturn fmt.Errorf(\"insert: %v\", err)\n\t\t}\n\t}\n\n\tv := currentVersion.Version\n\tif minDBVersion > v {\n\t\tlog.Fatal(`\nHi there, thank you for using Gogs for so long!\nHowever, Gogs has stopped supporting auto-migration from your previously installed version.\nBut the good news is, it's very easy to fix this problem!\nYou can migrate your older database using a previous release, then you can upgrade to the newest version.\n\nPlease save following instructions to somewhere and start working:\n\n- If you were using below 0.6.0 (e.g. 0.5.x), download last supported archive from following link:\n\thttps://gogs.io/gogs/releases/tag/v0.7.33\n- If you were using below 0.7.0 (e.g. 0.6.x), download last supported archive from following link:\n\thttps://gogs.io/gogs/releases/tag/v0.9.141\n- If you were using below 0.11.55 (e.g. 0.9.141), download last supported archive from following link:\n\thttps://gogs.io/gogs/releases/tag/v0.12.0\n\nOnce finished downloading:\n\n1. Extract the archive and to upgrade steps as usual.\n2. Run it once. To verify, you should see some migration traces.\n3. Once it starts web server successfully, stop it.\n4. Now it's time to put back the release archive you originally intent to upgrade.\n5. Enjoy!\n\nIn case you're stilling getting this notice, go through instructions again until it disappears.`)\n\t\treturn nil\n\t}\n\n\tif int(v-minDBVersion) > len(migrations) {\n\t\t// User downgraded Gogs.\n\t\tcurrentVersion.Version = int64(len(migrations) + minDBVersion)\n\t\t_, err = x.Id(1).Update(currentVersion)\n\t\treturn err\n\t}\n\tfor i, m := range migrations[v-minDBVersion:] {\n\t\tlog.Info(\"Migration: %s\", m.Description())\n\t\tif err = m.Migrate(db); err != nil {\n\t\t\treturn fmt.Errorf(\"do migrate: %v\", err)\n\t\t}\n\t\tcurrentVersion.Version = v + int64(i) + 1\n\t\tif _, err = x.Id(1).Update(currentVersion); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (conn *dbconn) Migrate(path string) (err error) {\n\tvar exists bool\n\tif exists, err = conn.tableExists(\"schema_migrations\"); err == nil {\n\t\tif !exists {\n\t\t\t_, err = conn.Execute(\"CREATE TABLE `schema_migrations` (`Name` VARCHAR(300) NOT NULL, `Date` DATETIME NOT NULL DEFAULT NOW());\")\n\t\t}\n\t}\n\n\tif err == nil {\n\t\terr = files.ExecuteThroughDirectory(path, false, func(fpath string, file os.FileInfo) (err error) {\n\n\t\t\tif strings.Contains(file.Name(), \".up.\") {\n\t\t\t\tvar exists bool\n\t\t\t\tif exists, err = conn.dbChangeExists(file.Name()); !exists && err == nil {\n\n\t\t\t\t\tfmt.Printf(\"Executing %v\\n\", file.Name())\n\n\t\t\t\t\tvar command string\n\t\t\t\t\t// Get the sql string from the file\n\t\t\t\t\tif command, err = files.GetStringFromFile(fpath); err == nil {\n\n\t\t\t\t\t\t// Execute the file against the database\n\t\t\t\t\t\t_, err = conn.Execute(command)\n\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t_, err = conn.Execute(fmt.Sprintf(\"INSERT INTO schema_migrations (Name) VALUE ('%v');\", file.Name()))\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfmt.Printf(\"Error in file [%s/%s] : %s\\n\", path, file.Name(), err.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn err\n\t\t})\n\t}\n\n\treturn err\n}", "func RunMigrations(db *gorm.DB) {\n\tdb.AutoMigrate(&Todo{})\n\n\tfmt.Println(\"AutoMigrations completed.\")\n}", "func (p *Provider) RegisterDatabase(db Database) {\n\tp.mu.Lock() // for any case\n\tp.databases = append(p.databases, db)\n\tp.mu.Unlock()\n}", "func Insert(db gorp.SqlExecutor, mig *sdk.Migration) error {\n\tmig.Created = time.Now()\n\tif mig.Release != \"\" && mig.Release != \"snapshot\" {\n\t\tv, err := semver.Parse(mig.Release)\n\t\tif err != nil {\n\t\t\treturn sdk.WrapError(err, \"Your migration %s with release %s is not semver compatible\", mig.Name, mig.Release)\n\t\t}\n\t\tmig.Major = v.Major\n\t\tmig.Minor = v.Minor\n\t\tmig.Patch = v.Patch\n\t}\n\treturn sdk.WrapError(gorpmapping.Insert(db, mig), \"Unable to insert migration %s\", mig.Name)\n}", "func (c *Client) AddMigration(up func(*sql.Tx) error, down func(*sql.Tx) error) {\n\t_, filename, _, _ := runtime.Caller(1)\n\tv, _ := NumericComponent(filename)\n\tmigration := &Migration{Version: v, Next: -1, Previous: -1, UpFn: up, DownFn: down, Source: filename}\n\n\tc.Migrations = append(c.Migrations, migration)\n}", "func (dbWrapper *DB) migrate() (err error) {\n\n\tdb := dbWrapper.gormDB\n\n\tif !db.HasTable(&MamidMetadata{}) {\n\n\t\t// run the populating query\n\n\t\tddlStatements, err := Asset(\"model/sql/mamid_postgresql.sql\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"sql DDL data not found: %s\", err)\n\t\t}\n\n\t\terr = db.Exec(string(ddlStatements), []interface{}{}).Error\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error running DDL statements: %s\", err)\n\t\t}\n\n\t\t// persist schema version\n\t\tif err = dbWrapper.setMetadata(\"schema_version\", SCHEMA_VERSION); err != nil {\n\t\t\treturn fmt.Errorf(\"error setting schema version: %s\", err)\n\t\t}\n\n\t} else {\n\n\t\tversion, err := dbWrapper.schemaVersion()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error determining schema version: %s\", err)\n\t\t}\n\n\t\tif version != SCHEMA_VERSION {\n\t\t\treturn fmt.Errorf(\"the database has already been populated, migrations are not supported\")\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func Migrate(values ...interface{}) {\n\tdb.AutoMigrate(values...)\n}", "func Migrate(db *sql.DB) error {\n\tif err := createTable(db); err != nil {\n\t\treturn err\n\t}\n\tcompleted, err := selectCompleted(db)\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn err\n\t}\n\tfor _, migration := range migrations {\n\t\tif _, ok := completed[migration.name]; ok {\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, err := db.Exec(migration.stmt); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := insertMigration(db, migration.name); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\tif err := initTemplete(db); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Migrate(tx *gorm.DB) error {\n\treturn tx.Exec(`\n\t ALTER TABLE initiators ADD COLUMN \"polling_interval\" BigInt;\n\t`).Error\n}", "func MigrateDatabase(url string) error {\n\tparts := strings.Split(url, \"/\")\n\tdbName := parts[len(parts)-1]\n\n\tdbForCreate, err := sql.Open(\"mysql\", strings.TrimSuffix(url, dbName))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := dbForCreate.Exec(`CREATE DATABASE IF NOT EXISTS ` + dbName); err != nil {\n\t\treturn err\n\t}\n\tif err := dbForCreate.Close(); err != nil {\n\t\treturn err\n\t}\n\n\tdb, err := sql.Open(\"mysql\", url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := db.Close(); err != nil {\n\t\t\tlog(nil, err).Error(\"migrator db close failed\")\n\t\t}\n\t}()\n\n\tif _, err := db.Exec(ensureSchemaMigrations); err != nil {\n\t\treturn err\n\t}\n\n\t// Multiple processes coming up and trying to run migrations at the same time\n\t// could be bad news if our migrations aren't idempotent and we don't lock.\n\tlog(nil, nil).Info(\"locking table schema_migrations\")\n\tif _, err := db.Exec(\"LOCK TABLES schema_migrations WRITE\"); err != nil {\n\t\treturn err\n\t}\n\tlog(nil, nil).Info(\"acquired table lock on schema_migrations\")\n\n\tfor _, migration := range migrations {\n\t\tif err := runMigration(db, migration); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif _, err := db.Exec(\"UNLOCK TABLES\"); err != nil {\n\t\treturn err\n\t}\n\tlog(nil, nil).Info(\"released table lock on schema_migrations\")\n\n\tlog(nil, nil).Info(\"migrations done\")\n\n\treturn nil\n}", "func SetupDatabase(db *gorm.DB, logMode bool) {\n\tdb.LogMode(logMode)\n\n\tuserDB = models.NewUserDB(*db)\n}", "func TestInitSchemaNoMigrations(t *testing.T) {\n\tforEachDatabase(t, func(db *sqlx.DB) {\n\t\tm := New(db, DefaultOptions, []*Migration{})\n\t\tm.InitSchema(func(tx *sqlx.DB) error {\n\t\t\tq := `CREATE TABLE \"animals\" (\"id\" serial,\"created_at\" timestamp with time zone,\"updated_at\" timestamp with time zone,\"deleted_at\" timestamp with time zone,\"name\" text , PRIMARY KEY (\"id\"))`\n\t\t\t_, err := tx.Exec(q)\n\t\t\treturn err\n\t\t})\n\n\t\tassert.NoError(t, m.Migrate())\n\t\tassert.True(t, m.hasTable(\"animals\"))\n\t\tassert.Equal(t, 1, tableCount(t, db, \"migrations\"))\n\t})\n}", "func UpgradeDB() (err error) {\n\tmigrations, err := GetLastestMigrations()\n\tif err != nil {\n\t\treturn\n\t}\n\tvar lastTime int64\n\tif migrations != nil {\n\t\tlastTime, err = getCreateTimeByName(migrations.Name)\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t}\n\treturn migration.Upgrade(lastTime)\n}", "func RunDBMigrate() error {\n\t// Add your custom code\n\tfmt.Println(\"RunDBMigrate: not implemented yet!\")\n\treturn nil\n}", "func Register(db *gorp.DbMap) {\n\tregisterBuildCount(db)\n\tregisterPendingBuildCount(db)\n\tregisterRepoCount(db)\n\tregisterRunningBuildCount(db)\n\tregisterUserCount(db)\n\tregisterFailedBuildCount(db)\n}", "func (s *Suite) Add(m *Migration) {\n\tif m == nil {\n\t\tpanic(\"nil migration\")\n\t}\n\tif s.Stmts == nil {\n\t\ts.Stmts = &Stmts{\n\t\t\tCreateTableSQL: fmt.Sprintf(`CREATE TABLE IF NOT EXISTS \"%s\" ( \"%s\" INTEGER )`, TableName, ColumnName),\n\t\t\tSelectVersionSQL: fmt.Sprintf(`SELECT \"%s\" FROM \"%s\" LIMIT 1`, ColumnName, TableName),\n\t\t\tInsertVersionSQL: fmt.Sprintf(`INSERT INTO \"%s\" ( \"%s\" ) VALUES ( $1 )`, TableName, ColumnName),\n\t\t\tUpdateVersionSQL: fmt.Sprintf(`UPDATE \"%s\" SET \"%s\" = $1 WHERE \"%s\" = $2`, TableName, ColumnName, ColumnName),\n\t\t}\n\t}\n\n\tm.id = len(s.Migrations)\n\ts.Migrations = append(s.Migrations, m)\n}", "func (t TicketsDB) migrateDB(sqlFiles ...string) error {\n\tfor _, sqlFile := range sqlFiles {\n\t\tsetupScript, err := ioutil.ReadFile(sqlFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = t.DB.Exec(string(setupScript))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Migrate() {\n\tif err := Db.Ping(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdriver, _ := postgres.WithInstance(Db, &postgres.Config{})\n\n\tm, e := migrate.NewWithDatabaseInstance(\n\t\t\"file:///home/osama/go/src/graphServer/db/mydatabase\",\n\t\t\"postgres\",\n\t\tdriver,\n\t)\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n\tif err := m.Up(); err != nil && err != migrate.ErrNoChange {\n\t\tfmt.Println(\"Eror\")\n\t\tlog.Fatal(err)\n\t}\n\n}", "func MigrateDB() {\n\t// 迁移 schema\n\tdb.AutoMigrate(&User{}, &UserInfo{}, &Post{}, &Agreement{},\n\t\t&Comment{}, &Report{}, &Edit{}, &Ban{}, &SysNotice{})\n}", "func Migrate(x *xorm.Engine) error {\n\tif err := x.Sync2(new(Version)); err != nil {\n\t\treturn fmt.Errorf(\"sync: %v\", err)\n\t}\n\n\tcurrentVersion := &Version{ID: 1}\n\thas, err := x.Get(currentVersion)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get: %v\", err)\n\t} else if !has {\n\t\t// If the version record does not exist we think\n\t\t// it is a fresh installation and we can skip all migrations.\n\t\tcurrentVersion.ID = 0\n\t\tcurrentVersion.Version = int64(_MIN_DB_VER + len(migrations))\n\n\t\tif _, err = x.InsertOne(currentVersion); err != nil {\n\t\t\treturn fmt.Errorf(\"insert: %v\", err)\n\t\t}\n\t}\n\n\tv := currentVersion.Version\n\tif _MIN_DB_VER > v {\n\t\tlog.Print(`\nQmoon can not auto-migration from your previously installed version.\n`)\n\t\treturn nil\n\t}\n\n\tif int(v-_MIN_DB_VER) > len(migrations) {\n\t\tcurrentVersion.Version = int64(len(migrations) + _MIN_DB_VER)\n\t\t_, err = x.ID(1).Update(currentVersion)\n\t\treturn err\n\t}\n\tfor i, m := range migrations[v-_MIN_DB_VER:] {\n\t\tif err = m.Migrate(x); err != nil {\n\t\t\treturn fmt.Errorf(\"do migrate: %v\", err)\n\t\t}\n\t\tcurrentVersion.Version = v + int64(i) + 1\n\t\tif _, err = x.ID(1).Update(currentVersion); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func MigrateDatabase(db *gorm.DB) error {\n\treturn db.AutoMigrate(models.Class{}, models.ClassEvent{}, models.Booking{})\n}", "func RegisterTables() {\n\tdb := model.GetMysqlConn()\n\tdb.AutoMigrate(\n\t\t&model.BaseRole{},\n\t\t&model.BaseUser{},\n\t)\n\tinitRoles := []model.BaseRole{\n\t\t{\n\t\t\tRoleId: \"1\",\n\t\t\tRoleName: \"Administrator\",\n\t\t},\n\t\t{\n\t\t\tRoleId: \"2\",\n\t\t\tRoleName: \"NormalUser\",\n\t\t},\n\t}\n\tfor _, role := range initRoles {\n\t\tdb.Where(role).FirstOrCreate(&role)\n\t}\n\n\tinitUsers := []model.BaseUser{\n\t\t{\n\t\t\tUsername: \"grant\",\n\t\t\tPassword: tools.Md5(\"grant\"),\n\t\t\tEmail: \"granty1@163.com\",\n\t\t\tNickName: \"Granty1\",\n\t\t\tPhone: \"15316368801\",\n\t\t\tRoleID: \"1\",\n\t\t},\n\t\t{\n\t\t\tUsername: \"karl\",\n\t\t\tPassword: tools.Md5(\"karl\"),\n\t\t\tEmail: \"karl@163.com\",\n\t\t\tNickName: \"KralW\",\n\t\t\tPhone: \"15316368801\",\n\t\t\tRoleID: \"2\",\n\t\t},\n\t}\n\tfor _, user := range initUsers {\n\t\tdb.Where(user).FirstOrCreate(&user)\n\t}\n}", "func (drv SQLiteDriver) CreateMigrationsTable(db *sql.DB) error {\n\t_, err := db.Exec(`create table if not exists schema_migrations (\n\t\tversion varchar(255) primary key)`)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add the project column if it doesn't already exist.\n\t_, err = db.Exec(`select project from schema_migrations limit 1`)\n\tif err != nil {\n\t\t_, err = db.Exec(`alter table schema_migrations\n\t\t\tadd column project varchar(255) default 'default'`)\n\t}\n\n\treturn err\n}", "func DbInit() {\n\tsqlStatement := `\n\t\tCREATE TABLE benutzer (\n\t\t\tfdNummer VARCHAR(256) PRIMARY KEY, \n\t\t\tVorname VARCHAR(256) NOT NULL, \n\t\t\tNachname VARCHAR(256) NULL,\n\t\t\tAge TINYINT NULL,\n\t\t\tStudiengang VARCHAR(256) NULL,\n\t\t\tSemester TINYINT NULL\n\t\t\t);\n\n\t\tCREATE TABLE nachrichten (\n\t\t\tNachrichtID INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\tfdNummer VARCHAR(256) NOT NULL,\n\t\t\tGroupID INTEGER NOT NULL,\n\t\t\tmessage VARCHAR(256) NOT NULL,\n\t\t\tgesendeteUhrzeit DEFAULT CURRENT_TIMESTAMP\n\t\t\t);\n\n\t\tCREATE TABLE chatgroup (\n\t\t\tGroupID INTEGER PRIMARY KEY,\n\t\t\tGroupName VARCHAR(256) NOT NULL\n\t\t\t);\n\t`\n\n\tCreate(sqlStatement)\n}", "func LoadDBMigrations(config *config.Config, createConnector func(*config.Config) db.Connector) []types.MigrationDB {\n\tconnector := createConnector(config)\n\tconnector.Init()\n\tdefer connector.Dispose()\n\tdbMigrations := connector.GetMigrations()\n\tlog.Printf(\"Read [%d] DB migrations ==> OK\", len(dbMigrations))\n\treturn dbMigrations\n}", "func New(name string) error {\n\treturn createMigration(name, \"/* Your up migration code here */\", \"/* Your down migration code here */\")\n}", "func Migrate(configFile string) error {\n log.INFO.Print(\"迁移数据库\")\n _, db, err := initConfigDB(configFile)\n if err != nil {\n return err\n }\n defer func() {\n err := db.Close()\n if err != nil {\n log.FATAL.Print(err)\n }\n }()\n\n // Bootstrap migrations\n if err := migrations.Bootstrap(db); err != nil {\n return err\n }\n\n // Run migrations for the oauth service\n if err := models.MigrateAll(db); err != nil {\n return err\n }\n\n return nil\n}", "func setupDatabase(db *sqlx.DB) error {\n\t// turn on write-ahead log and store temp tables on disk.\n\t_, err := db.Exec(`\n\t\tPRAGMA journal_mode=WAL;\n\t\tPRAGMA temp_store=1;\n\t\tPRAGMA foreign_keys=ON;\n\t\tPRAGMA encoding='UTF-8';\n\t`)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"execute PRAGMAs: %w\", err)\n\t}\n\n\ttx, err := db.Beginx()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"begin Tx: %w\", err)\n\t}\n\tdefer tx.Rollback()\n\n\tvar version int\n\tif err = tx.Get(&version, `PRAGMA user_version;`); err != nil {\n\t\treturn fmt.Errorf(\"PRAGMA user_version: %w\", err)\n\t}\n\tlog.Printf(\"[repo] current schema: %d\", version)\n\n\tswitch version {\n\tcase 0:\n\t\tlog.Printf(\"initialising database ...\")\n\t\t_, err = tx.Exec(`\n\t\t\t-- data table\n\t\t\tCREATE TABLE IF NOT EXISTS codepoints (\n\t\t\t\thex TEXT PRIMARY KEY,\n\t\t\t\tdec INTEGER,\n\t\t\t\tcategory TEXT,\n\t\t\t\tname TEXT,\n\t\t\t\taliases TEXT,\n\t\t\t\tentity TEXT\n\t\t\t);\n\t\t\t-- CREATE INDEX IF NOT EXISTS idx_hex ON codepoints(hex);\n\n\t\t\t-- full-text search\n\t\t\tCREATE VIRTUAL TABLE IF NOT EXISTS search USING FTS5(\n\t\t\t\tname,\n\t\t\t\taliases,\n\t\t\t\tentity,\n\t\t\t\thex,\n\t\t\t\tdec,\n\t\t\t\tcontent = 'codepoints',\n\t\t\t\ttokenize = \"unicode61 remove_diacritics 1 separators '-'\"\n\t\t\t);\n\n\t\t\tCREATE TRIGGER IF NOT EXISTS codepoints_ai AFTER INSERT ON codepoints\n\t\t\tBEGIN\n\t\t\t\tINSERT INTO search (rowid, name, aliases, entity, hex, dec)\n\t\t\t\t\tVALUES (new.rowid, new.name, new.aliases, new.entity, new.hex, new.dec);\n\t\t\tEND;\n\t\t\tCREATE TRIGGER IF NOT EXISTS codepoints_ad AFTER DELETE ON codepoints\n\t\t\tBEGIN\n\t\t\t\tINSERT INTO search (search, rowid, name, aliases, entity, hex, dec)\n\t\t\t\t\tVALUES ('delete', old.rowid, old.name, old.aliases, old.entity, old.hex, old.dec);\n\t\t\tEND;\n\t\t\tCREATE TRIGGER IF NOT EXISTS codepoints_au AFTER UPDATE ON codepoints\n\t\t\tBEGIN\n\t\t\t\tINSERT INTO search (search, rowid, name, aliases, entity, hex, dec)\n\t\t\t\t\tVALUES ('delete', old.rowid, old.name, old.aliases, old.entity, old.hex, old.dec);\n\t\t\t\tINSERT INTO search (rowid, name, aliases, entity, hex, dec)\n\t\t\t\t\tVALUES (new.rowid, new.name, new.aliases, new.entity, new.hex, new.dec);\n\t\t\tEND;\n\n\t\t\tPRAGMA user_version = 1;\n\t\t`)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"migrate to version 1: %w\", err)\n\t\t}\n\t\tfallthrough\n\tcase 1: // future migration\n\t\tbreak\n\t}\n\n\tif err = tx.Commit(); err != nil {\n\t\treturn fmt.Errorf(\"commit schema updates: %w\", err)\n\t}\n\tvar n int\n\tif err = db.Get(&n, `PRAGMA user_version;`); err != nil {\n\t\treturn fmt.Errorf(\"PRAGMA user_version: %w\", err)\n\t}\n\n\tif n > version {\n\t\tif _, err := db.Exec(`VACUUM;`); err != nil {\n\t\t\treturn fmt.Errorf(\"VACUUM database: %w\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func Migrate(db *sqlx.DB) error {\n\tctx := context.Background()\n\tfiles, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tchecktable := table{}\n\temptyParams := map[string]interface{}{}\n\terr = Query(ctx, db, \"SELECT to_regclass('metadata') as table_name\", emptyParams, &checktable)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tmigrationVersion := 0\n\tif checktable.TableName == nil {\n\t\ttx.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS \"metadata\" (\n\t\t\tkey VARCHAR (50) PRIMARY KEY,\n\t\t\tvalue VARCHAR (50) NOT NULL\n\t\t);\n\t\tINSERT INTO public.metadata (\"key\",value) VALUES ('MIRAGRATION_VERSION','`+strconv.Itoa(len(files))+`');`)\n\t} else {\n\t\tvar meta metadata\n\t\terr = Query(ctx, db, \"SELECT key,value from metadata\", emptyParams, &meta)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmigrationVersion, _ = strconv.Atoi(meta.Value)\n\t}\n\n\terr = execMigration(ctx, files, tx, migrationVersion)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\ttx.Commit()\n\treturn nil\n}", "func (db *SQL) Migrate() (e error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif tR, ok := r.(error); ok {\n\t\t\t\te = tR\n\t\t\t} else {\n\t\t\t\tpanic(r)\n\t\t\t}\n\t\t}\n\t}()\n\n\tversion, err := db.CurrentVersion()\n\tif err != nil {\n\t\tif err = setupStatsSchemaTable(db); err != nil {\n\t\t\treturn fmt.Errorf(\"Could not create schema table: %v\", err)\n\t\t}\n\t}\n\n\tfor v := version; v < Version; v++ {\n\t\ttx := db.MustBegin()\n\t\ttx.MustExec(string(MustAsset(fmt.Sprintf(\n\t\t\t\"static/migrations/%s/v%d.sql\", db.DriverName(), v+1,\n\t\t))))\n\t\ttx.MustExec(fmt.Sprintf(\n\t\t\t\"UPDATE stats_schema SET version = %d;\", v+1,\n\t\t))\n\t\ttx.Commit()\n\t}\n\treturn nil\n}", "func (w *DeploymentWrite) Register(c *sql.DB, l ...*logrus.Logger) {\n\tw.conn = c\n\tw.appLog = l[0]\n\tw.reqLog = l[1]\n\tw.errLog = l[2]\n}", "func (db *Postgres) initDB() error {\n\t// Create the schema\n\t// @afiune Can we rename this library?\n\tif err := migrator.Migrate(db.URI, db.SchemaPath); err != nil {\n\t\treturn errors.Wrapf(err, \"Unable to create database schema. [path:%s]\", db.SchemaPath)\n\t}\n\n\t// Add the tables to the database mappings\n\tdb.AddTableWithName(deployment{}, \"deployment\").SetKeys(true, \"id\")\n\tdb.AddTableWithName(supervisor{}, \"supervisor\").SetKeys(true, \"id\")\n\tdb.AddTableWithName(serviceGroup{}, \"service_group\").SetKeys(true, \"id\")\n\tdb.AddTableWithName(service{}, \"service\").SetKeys(true, \"id\")\n\n\t//return db.CreateTablesIfNotExists() // I don't think we can ensure the foreign keys\n\treturn nil\n}", "func (s *SchemaEditor) prepareSchemaMigrations() (err error) {\n\tqb := utils.QueryBuilder().\n\t\tSelect(\"COUNT(*)\").\n\t\tFrom(\"information_schema.tables\").\n\t\tWhere(\"table_name = ?\", MIGRATIONS_DB_TABLE)\n\n\tvar (\n\t\targs []interface{}\n\t\tcount int\n\t\tquery string\n\t)\n\n\tif query, args, err = qb.ToSql(); err != nil {\n\t\treturn\n\t}\n\n\tif err = s.context.DB.Get(&count, query, args...); err != nil {\n\t\treturn\n\t}\n\n\t// schema migrations table already exists\n\tif count > 0 {\n\t\treturn\n\t}\n\n\tglog.V(2).Info(\"Create schema migrations table.\")\n\tschema := fmt.Sprintf(`CREATE TABLE %s (\n\t\t id character varying(200) NOT NULL,\n\t\t plugin_id character varying(200) NOT NULL,\n\t\t created timestamp NULL default now(),\n\t\t queries text[],\n\t\t PRIMARY KEY(id));`, MIGRATIONS_DB_TABLE)\n\t_, err = s.context.DB.Exec(schema)\n\treturn err\n}", "func (d *DatabaseAPI) Register(route gin.IRoutes) {\n\troute.GET(DatabasePath, d.GetByName)\n}", "func MigrateDB(db *sql.DB) {\n\terr := db.Ping()\n\tif err != nil {\n\t\tfmt.Print(err)\n\t}\n\n\tdriver, _ := postgres.WithInstance(db, &postgres.Config{})\n\tm, err := migrate.NewWithDatabaseInstance(\"file://app/infrastructure/db/migrations\", \"postgres\", driver)\n\tif err != nil {\n\t\tfmt.Print(err)\n\t}\n\tif err := m.Up(); err != nil && err != migrate.ErrNoChange {\n\t\tlog.Fatal(err)\n\t}\n}", "func RegisterLegacyMigrater(eventName string, migrationHandler func(t time.Time, data string) error) {\n\tregisteredMigraters[eventName] = migrationHandler\n\n\tlogrus.Debug(\"[scheduledEvents2] Registered migration handler for \", eventName)\n}", "func doDatabaseMigrations(db *WowDB, env *Env, blizzard Blizzard) {\n\n\tif ! db.HasTable(&Race{}) {\n\t\tlog.Debug(\"Migrating race\")\n\t\tdb.AutoMigrate(&Race{})\n\t\terr := UpdateRacesFromBlizzard(env, blizzard)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Could not update races: %v\", err)\n\t\t}\n\t}\n\n\tif ! db.HasTable(&ToonClass{}) {\n\t\tlog.Println(\"Migrating classes\")\n\t\tdb.AutoMigrate(&ToonClass{})\n\t\terr := UpdateClassesFromBlizzard(env, blizzard)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Could not update classes: %v\", err)\n\t\t}\n\t}\n\n\tdb.AutoMigrate(&Stat{})\n\tdb.AutoMigrate(&Toon{})\n\n\tif ! db.HasTable(&ClassColor{}) {\n\t\tdb.AutoMigrate(&ClassColor{})\n\t\tdb.Model(&ClassColor{}).AddForeignKey(\"toon_class_id\", \"toon_classes(id)\", \"RESTRICT\", \"RESTRICT\")\n\t\tvar tColor = ClassColor{ToonClassID: 1, Color: \"#C79C63\"}\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 2\n\t\ttColor.Color = \"#F58CBA\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 3\n\t\ttColor.Color = \"#ABD473\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 4\n\t\ttColor.Color = \"#FFF569\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 5\n\t\ttColor.Color = \"#F0EBE0\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 6\n\t\ttColor.Color = \"#C41F3B\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 7\n\t\ttColor.Color = \"#0070DE\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 8\n\t\ttColor.Color = \"#69CCF0\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 9\n\t\ttColor.Color = \"#9482C9\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 10\n\t\ttColor.Color = \"#00FF96\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 11\n\t\ttColor.Color = \"#FF7D0A\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 12\n\t\ttColor.Color = \"#A330C9\"\n\t\tdb.Create(&tColor)\n\t}\n\n\tdb.Model(&Toon{}).AddForeignKey(\"race_id\", \"races(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&Toon{}).AddForeignKey(\"class_id\", \"toon_classes(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&Stat{}).AddForeignKey(\"toon_id\", \"toons(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&Stat{}).AddUniqueIndex(\"idx_toon_id_create_date\", \"toon_id\", \"insert_date\")\n}", "func registerMysql(dataBase, dataSource string) {\r\n\r\n\t// count of database register\r\n\tcount := 0\r\n\tfor {\r\n\t\t// drive register\r\n\t\terr := orm.RegisterDriver(dataBase, orm.DRMySQL)\r\n\t\tif err != nil {\r\n\t\t\t//\t output err\r\n\t\t}\r\n\t\t// database regsiter\r\n\t\terr = orm.RegisterDataBase(\"default\", dataBase, dataSource, maxIdle, maxConn)\r\n\t\tif err != nil {\r\n\t\t\t// output err\r\n\t\t}\r\n\t\tcount++\r\n\t\tif count == 3 {\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n}", "func MigrateDatabase() {\n\tdatabase := ConnectDatabase()\n\n\tif !database.HasTable(&model.User{}) {\n\t\tdatabase.CreateTable(&model.User{})\n\t\tdatabase.Set(\"gorm:table_options\", \"ENGINE=InnoDB\").CreateTable(&model.User{})\n\t}\n}", "func (db *DB) Migrate(databaseName string) error {\n\t// Create the tables if necessary\n\terr := MigrateSQL(db.DB.DB, Archive{}.Schema())\n\tif err == nil {\n\t\terr = MigrateSQL(db.DB.DB, Transform{}.Schema())\n\t}\n\tswitch err.(type) {\n\tcase *mysql.MySQLError:\n\t\t// \"database does not exist\" error\n\t\tif err.(*mysql.MySQLError).Number == 0x419 {\n\t\t\t// Connect to a db that we know exists and then run the CREATE DATABASE\n\t\t\t// query\n\t\t\tconn, err := sql.Open(\"mysql\", \"root@/mysql?parseTime=true\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = MigrateSQL(conn, fmt.Sprintf(\"CREATE DATABASE %s\", databaseName))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// Create the tables if we just created the database\n\t\t\terr = MigrateSQL(db.DB.DB, Archive{}.Schema())\n\t\t}\n\t}\n\treturn err\n}", "func prepareDatabase() {\n\t// Register database\n\torm.RegisterDriver(\"sqlite3\", orm.DRSqlite)\n\torm.RegisterDataBase(\"default\", \"sqlite3\", \"_data/data.db\")\n\n\t// Migrate schema\n\tif err := orm.RunSyncdb(\"default\", false, false); err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\t// Apply registrations\n\tmodels.ApplyDefaultEffectRegistration()\n}", "func Migrate(db *gorm.DB) {\n\tdb.AutoMigrate(&User{}, &Team{})\n\n\tdb.Model(&Team{}).AddForeignKey(\"owner_id\", \"users(id)\", \"CASCADE\", \"CASCADE\")\n\tfmt.Println(\"Auto Migration has beed processed\")\n}", "func (sl SQLiteStruct) CreateMigrationTable() {\n\tquery := \"CREATE TABLE \" + bTQ + migrationTableName + bTQ + \" (\" + bTQ + \"version\" + bTQ + \" VARCHAR(15));\"\n\tfmt.Println(query)\n\tq, err := Db.Query(query)\n\tdefer q.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tlog.Println(\"Table Created Successfully.\")\n\t}\n}", "func migrateDatabase(db *gorm.DB) error {\n\tif err := db.AutoMigrate(&model.Report{}); err != nil {\n\t\treturn errors.Wrap(err, \"migrate user model failed\")\n\t}\n\tif err := db.AutoMigrate(&model.ReportMessage{}); err != nil {\n\t\treturn errors.Wrap(err, \"migrate policy model failed\")\n\t}\n\n\treturn nil\n}", "func (conn *DBConn) MigrateDatabase() {\n\tlogging.Logger.Infoln(\"[DB] Running migrations...\")\n\n\tif err := conn.DB.AutoMigrate(\n\t\t&model.User{},\n\t\t&model.Task{},\n\t\t&auth.AccessDetails{},\n\t); err != nil {\n\t\tlogging.Logger.Panicln(\"[DB] Failed to migrate database\", err)\n\t}\n}", "func setupDB(db *sql.DB) error {\n\tsqlScript, err := ioutil.ReadFile(\"dbSchema.sql\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstatements := strings.Split(string(sqlScript), \";\")\n\tif len(statements) > 0 {\n\t\tstatements = statements[:len(statements)-1]\n\t}\n\n\tfor _, statement := range statements {\n\t\t_, err = db.Exec(statement)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (drv ClickHouseDriver) CreateMigrationsTable(db *sql.DB) error {\n\t_, err := db.Exec(`\n\t\tcreate table if not exists schema_migrations (\n\t\t\tversion String,\n\t\t\tts DateTime default now(),\n\t\t\tapplied UInt8 default 1\n\t\t) engine = ReplacingMergeTree(ts)\n\t\tprimary key version\n\t\torder by version\n\t`)\n\treturn err\n}", "func migrate() *gorm.DB {\n\tdb.AutoMigrate(&models.Book{})\n\treturn db\n}", "func Setup(config *config.Config) error {\n\tcreateDb := false\n\tif _, err = os.Stat(config.DBPath); err != nil || config.DBPath == \":memory:\" {\n\t\tcreateDb = true\n\t}\n\t// Open our database connection\n\tdb, err = gorm.Open(config.DBName, config.DBPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdb.LogMode(false)\n\tdb.SetLogger(log.Logger)\n\tdb.DB().SetMaxOpenConns(1)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Migrate up to the latest version\n\t//If the database didn't exist, we need to create the admin user\n\terr := db.AutoMigrate(\n\t\t&User{},\n\t\t&Credential{},\n\t\t&Authenticator{},\n\t).Error\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgorm.NowFunc = func() time.Time {\n\t\treturn time.Now().UTC()\n\t}\n\n\tif createDb {\n\t\t// Create the default user\n\t\tinitUser := User{\n\t\t\tUsername: \"admin\",\n\t\t\tDisplayName: \"Example Admin\",\n\t\t}\n\t\terr = db.Save(&initUser).Error\n\t\tif err != nil {\n\t\t\tlog.Infof(\"error creating initial user: %s\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (s Sequence) Migrate() error {\n\tif s.cfg.Active && s.db != nil {\n\t\tif err := goose.Up(s.db, s.cfg.Dir); err != nil {\n\t\t\treturn fmt.Errorf(errApplyMigration, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func MigrateDatabase(ctx context.Context, dEnv *env.DoltEnv, dropConflicts bool) error {\n\tmenv, err := migrate.NewEnvironment(ctx, dEnv)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmenv.DropConflicts = dropConflicts\n\n\tif curr := menv.Existing.DoltDB.Format(); types.IsFormat_DOLT(curr) {\n\t\tcli.Println(\"database is already migrated\")\n\t\treturn nil\n\t}\n\n\tp, err := menv.Migration.FS.Abs(\".\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tcli.Println(\"migrating database at tmp dir: \", p)\n\n\terr = migrate.TraverseDAG(ctx, menv, menv.Existing.DoltDB, menv.Migration.DoltDB)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn migrate.SwapChunkStores(ctx, menv)\n}", "func (kv *KV) Register(table []byte) error {\n\tif len(table) == 0 {\n\t\treturn gkv.ErrTableName\n\t}\n\tkv.table = table\n\t_, err := kv.db.Exec(fmt.Sprintf(`\nPRAGMA foreign_keys = FALSE;\nCREATE TABLE IF NOT EXISTS %s (\n\tid VARCHAR(34) NOT NULL,\n\tk TEXT NOT NULL,\n\tv TEXT NOT NULL,\n\tPRIMARY KEY (id)\n);\nPRAGMA foreign_keys = TRUE;\n`, string(table)))\n\treturn err\n}", "func (d *DB) InitDB() {\n\tdb, err := gorm.Open(\"mysql\", \"root@/users?charset=utf8&parseTime=True&loc=Local\")\n\tif err != nil {\n\t\tpanic(\"failed to connect to the database :(\")\n\t}\n\t// defer db.Close()\n\n\tdb.AutoMigrate(&User{})\n\n\td.db = db\n\td.CodeMap = make(map[string]CodeItem)\n\td.CodeMap[\"\"] = CodeItem{Code: -1}\n}", "func Migrate() {\n\tconn, err := db.NewConn()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Close()\n\n\terr = conn.Sync2(User{})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func SetupAndMigrate(\n\tctx context.Context,\n\tlog logrus.FieldLogger,\n\tdb interface {\n\t\tBeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error)\n\t\tExec(context.Context, string, ...any) (pgconn.CommandTag, error)\n\t},\n\ttableName string,\n\tschemas []string,\n) error {\n\ttableName = pgx.Identifier{tableName}.Sanitize()\n\n\tvar version int32\n\tvar migrateErr error\n\n\t// this is split off from the rest because we might not have permissions to\n\t// CREATE TABLE, which is checked even if the table exists\n\tif _, err := RetryIdempotent(ctx, log, func() (struct{}, error) {\n\t\t_, err := db.Exec(ctx,\n\t\t\tfmt.Sprintf(`CREATE TABLE IF NOT EXISTS %v (\n\t\t\t\tversion integer PRIMARY KEY CHECK (version > 0),\n\t\t\t\tcreated timestamptz NOT NULL DEFAULT now()\n\t\t\t)`, tableName), pgx.QueryExecModeExec,\n\t\t)\n\t\treturn struct{}{}, trace.Wrap(err)\n\t}); err != nil {\n\t\t// the very first SELECT in the next transaction will fail, we don't\n\t\t// need anything higher than debug here\n\t\tlog.WithError(err).Debugf(\"Failed to confirm the existence of the %v table.\", tableName)\n\t}\n\n\tconst idempotent = true\n\tif err := RetryTx(ctx, log, db, pgx.TxOptions{\n\t\tIsoLevel: pgx.Serializable,\n\t\tAccessMode: pgx.ReadWrite,\n\t}, idempotent, func(tx pgx.Tx) error {\n\t\tif err := tx.QueryRow(ctx,\n\t\t\tfmt.Sprintf(\"SELECT COALESCE(max(version), 0) FROM %v\", tableName),\n\t\t\tpgx.QueryExecModeExec,\n\t\t).Scan(&version); err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\n\t\tif int(version) > len(schemas) {\n\t\t\tmigrateErr = trace.BadParameter(\"unsupported schema version %v\", version)\n\t\t\t// the transaction succeeded, the error is outside of the transaction\n\t\t\treturn nil\n\t\t}\n\n\t\tif int(version) == len(schemas) {\n\t\t\treturn nil\n\t\t}\n\n\t\tfor _, s := range schemas[version:] {\n\t\t\tif _, err := tx.Exec(ctx, s, pgx.QueryExecModeExec); err != nil {\n\t\t\t\treturn trace.Wrap(err)\n\t\t\t}\n\t\t}\n\n\t\tif _, err := tx.Exec(ctx,\n\t\t\tfmt.Sprintf(\"INSERT INTO %v (version) VALUES ($1)\", tableName),\n\t\t\tpgx.QueryExecModeExec, len(schemas),\n\t\t); err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\n\t\treturn nil\n\t}); err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tif migrateErr != nil {\n\t\treturn trace.Wrap(migrateErr)\n\t}\n\n\tif int(version) != len(schemas) {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"previous_version\": version,\n\t\t\t\"current_version\": len(schemas),\n\t\t}).Info(\"Migrated database schema.\")\n\t}\n\n\treturn nil\n}", "func (s *Service) RegistTable(t interface{}) {\n\tif ok := s.DB.HasTable(t); !ok {\n\t\tif err := s.DB.CreateTable(t).Error; err != nil {\n\t\t\tlog.Fatalf(\"create mysql table error:%s\", err.Error())\n\t\t}\n\t}\n\tvar tab []interface{}\n\ts.DB.AutoMigrate(append(tab, t))\n}" ]
[ "0.77468985", "0.67866886", "0.62771386", "0.59007233", "0.58881843", "0.5785044", "0.57692766", "0.5756132", "0.5736178", "0.56210345", "0.5598174", "0.5567961", "0.5492138", "0.54760194", "0.5455018", "0.5444859", "0.5422033", "0.5421633", "0.5414794", "0.53998196", "0.53763086", "0.5375355", "0.53497696", "0.5346878", "0.53359395", "0.5323585", "0.5278839", "0.5262048", "0.5257681", "0.5250012", "0.5247608", "0.5246807", "0.52394736", "0.5237104", "0.5234185", "0.523232", "0.5231585", "0.52156204", "0.5210023", "0.5199212", "0.5189548", "0.5184173", "0.5181888", "0.51805073", "0.51641804", "0.51523566", "0.51511264", "0.51465887", "0.5143402", "0.51411754", "0.51388246", "0.51382375", "0.51214325", "0.51179045", "0.51157844", "0.51133627", "0.5099221", "0.50864595", "0.5083634", "0.50767", "0.5051795", "0.50505173", "0.504845", "0.50436723", "0.5018942", "0.50066483", "0.49976957", "0.49951845", "0.49814337", "0.49797562", "0.4978934", "0.49365637", "0.4935996", "0.49353147", "0.49274403", "0.4926147", "0.49249637", "0.49187285", "0.4916943", "0.4901664", "0.4898208", "0.48827195", "0.48817483", "0.4879489", "0.48790905", "0.4878819", "0.48767957", "0.48739794", "0.48663175", "0.486092", "0.48591375", "0.48554334", "0.48523805", "0.48486692", "0.48384926", "0.48380652", "0.4827369", "0.4826033", "0.48250026", "0.48234722" ]
0.5412613
19
RegisterTx is just like Register but marks the migration to be executed inside a transaction.
func RegisterTx(fns ...func(DB) error) error { return DefaultCollection.RegisterTx(fns...) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pg *Postgres) Tx(ctx context.Context, txFunc store.TxFunc) (err error) {\n\ttx := shared.GetTx(ctx)\n\n\tif tx != nil {\n\t\treturn txFunc(ctx)\n\t}\n\n\ttx, err = pg.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"begin tx failed\")\n\t}\n\n\tctx = shared.WithTx(ctx, tx)\n\n\t//nolint:gocritic\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif err := tx.Rollback(); err != nil {\n\t\t\t\tlog.Warn(ctx, \"tx rollback failed\", \"err\", err)\n\t\t\t}\n\t\t\tpanic(r)\n\t\t} else if err != nil {\n\t\t\tif err := tx.Rollback(); err != nil {\n\t\t\t\tlog.Warn(ctx, \"tx rollback failed\", \"err\", err)\n\t\t\t}\n\t\t} else {\n\t\t\terr = tx.Commit()\n\t\t}\n\t}()\n\n\terr = txFunc(ctx)\n\n\treturn err\n}", "func (p *Postgres) Tx(ctx context.Context, txFunc store.TxFunc) (err error) {\n\ttx := shared.GetTx(ctx)\n\n\tif tx != nil {\n\t\treturn txFunc(ctx)\n\t}\n\n\ttx, err = p.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"begin tx failed\")\n\t}\n\n\tctx = shared.WithTx(ctx, tx)\n\n\t//nolint:gocritic\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif err := tx.Rollback(); err != nil {\n\t\t\t\tlog.Warn(ctx, \"tx rollback failed\", \"err\", err)\n\t\t\t}\n\t\t\tpanic(r)\n\t\t} else if err != nil {\n\t\t\tif err := tx.Rollback(); err != nil {\n\t\t\t\tlog.Warn(ctx, \"tx rollback failed\", \"err\", err)\n\t\t\t}\n\t\t} else {\n\t\t\terr = tx.Commit()\n\t\t}\n\t}()\n\n\terr = txFunc(ctx)\n\n\treturn err\n}", "func RegisterTransaction(data models.TransactionCache) (string, error) {\n\n\tgenKey, err := shortid.Generate()\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn \"\", err\n\t}\n\tstoreKey := fmt.Sprintf(transactionKeyFmt, data.UserID, genKey)\n\n\tdataJSON, err := json.Marshal(data)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn \"\", err\n\t}\n\n\tif err := redisClient.Set(ctx, storeKey, dataJSON, 180*time.Second).Err(); err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn \"\", err\n\t}\n\n\treturn storeKey, nil\n\n}", "func registerMigration(dir string) {\n\tmigrations.MustRegisterTx(func(db migrations.DB) error {\n\t\tpath := dir + \"/up.sql\"\n\t\tsql, err := loadMigrationFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = db.Exec(sql)\n\t\treturn err\n\t}, func(db migrations.DB) error {\n\t\tpath := dir + \"/down.sql\"\n\t\tsql, err := loadMigrationFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = db.Exec(sql)\n\t\treturn err\n\t})\n}", "func (db *DB) Transaction(fc func(db *DB) error) (err error) {\n\tpanicked := true\n\ttx := &DB{db.DB.Begin()}\n\n\tdefer func() {\n\t\t// Make sure to rollback when panic, Block error or Commit error\n\t\tif panicked || err != nil {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\terr = fc(tx)\n\tif err == nil {\n\t\terr = tx.DB.Commit().Error\n\t}\n\tpanicked = false\n\treturn\n}", "func (m Middleware) Tx(db *sql.DB) TxFunc {\n\treturn func(f func(tx daos.Transaction, w http.ResponseWriter, r *http.Request) error) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\tt, err := db.Begin()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tl := m.log.WithRequest(r)\n\t\t\t\tif p := recover(); p != nil {\n\t\t\t\t\tt.Rollback()\n\t\t\t\t\tl.Info(\"transaction rollbacked\")\n\t\t\t\t\tpanic(p)\n\t\t\t\t} else if err != nil {\n\t\t\t\t\tt.Rollback()\n\t\t\t\t\tl.Info(\"transaction rollbacked\")\n\t\t\t\t\tpanic(err)\n\t\t\t\t} else {\n\t\t\t\t\terr = t.Commit()\n\t\t\t\t\tl.Info(\"transaction commited\")\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\terr = f(t, w, r)\n\t\t}\n\t}\n}", "func (m CarregisterMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }", "func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }", "func (d *Driver) Tx(ctx context.Context) (dialect.Tx, error) {\n\treturn d.BeginTx(ctx, nil)\n}", "func Tx(ctx context.Context, db *sqlx.DB, opts *sqltx.Options, fn TXFn) (err error) {\n\treturn sqltx.TxHandler(ctx, &sqlxDB{db}, opts, func(tx sqltx.TXer) error {\n\t\treturn fn(tx.(*sqlx.Tx))\n\t})\n}", "func (db *DB) Transaction(ctx context.Context, fn TxHandlerFunc) error {\n\tdb.mu.Lock()\n\tdefer db.mu.Unlock()\n\n\torigin, err := db.master.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to begin transaction: %v\", err)\n\t}\n\ttx := &Tx{origin}\n\n\tif err := fn(ctx, tx); err != nil {\n\t\tif re := tx.parent.Rollback(); re != nil {\n\t\t\tif re.Error() != sql.ErrTxDone.Error() {\n\t\t\t\treturn fmt.Errorf(\"fialed to rollback: %v\", err)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"failed to execcute transaction: %v\", err)\n\t}\n\treturn tx.parent.Commit()\n}", "func (_UpkeepRegistrationRequests *UpkeepRegistrationRequestsTransactor) Register(opts *bind.TransactOpts, name string, encryptedEmail []byte, upkeepContract common.Address, gasLimit uint32, adminAddress common.Address, checkData []byte, amount *big.Int, source uint8) (*types.Transaction, error) {\n\treturn _UpkeepRegistrationRequests.contract.Transact(opts, \"register\", name, encryptedEmail, upkeepContract, gasLimit, adminAddress, checkData, amount, source)\n}", "func (_KNS *KNSTransactor) Register(opts *bind.TransactOpts, prime_owner common.Address, wallet common.Address, Jid string, tel string) (*types.Transaction, error) {\n\treturn _KNS.contract.Transact(opts, \"Register\", prime_owner, wallet, Jid, tel)\n}", "func Transaction(db *sql.DB, fns ...func(DB) error) error {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, fn := range fns {\n\t\terr := fn(tx)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = tx.Commit()\n\terr = interpretScanError(err)\n\treturn err\n}", "func Example_transactions() {\n\tdb, _ := dbx.Open(\"mysql\", \"user:pass@/example\")\n\n\tdb.Transactional(func(tx *dbx.Tx) error {\n\t\t_, err := tx.Insert(\"user\", dbx.Params{\n\t\t\t\"name\": \"user1\",\n\t\t}).Execute()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.Insert(\"user\", dbx.Params{\n\t\t\t\"name\": \"user2\",\n\t\t}).Execute()\n\t\treturn err\n\t})\n}", "func (ds *MySQLDatastore) Tx(f func(*sql.Tx) error) error {\n\ttx, err := ds.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = f(tx)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}", "func Transaction(db *sql.DB, f func()) {\n\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr := tx.Rollback()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tpanic(r)\n\t\t} else {\n\t\t\terr = tx.Commit()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}()\n\tf()\n}", "func sendRegisterTx(cdc *wire.Codec) client.CommandTxCallback {\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\tctx := client.NewCoreContextFromViper()\n\t\tname := viper.GetString(client.FlagUser)\n\t\treferrer := viper.GetString(client.FlagReferrer)\n\t\tamount := viper.GetString(client.FlagAmount)\n\n\t\tresetPriv := secp256k1.GenPrivKey()\n\t\ttransactionPriv := secp256k1.GenPrivKey()\n\t\tappPriv := secp256k1.GenPrivKey()\n\n\t\tfmt.Println(\"reset private key is:\", strings.ToUpper(hex.EncodeToString(resetPriv.Bytes())))\n\t\tfmt.Println(\"transaction private key is:\", strings.ToUpper(hex.EncodeToString(transactionPriv.Bytes())))\n\t\tfmt.Println(\"app private key is:\", strings.ToUpper(hex.EncodeToString(appPriv.Bytes())))\n\n\t\t// // create the message\n\t\tmsg := acc.NewRegisterMsg(\n\t\t\treferrer, name, types.LNO(amount),\n\t\t\tresetPriv.PubKey(), transactionPriv.PubKey(), appPriv.PubKey())\n\n\t\t// build and sign the transaction, then broadcast to Tendermint\n\t\tres, err := ctx.SignBuildBroadcast([]sdk.Msg{msg}, cdc)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Printf(\"Committed at block %d. Hash: %s\\n\", res.Height, res.Hash.String())\n\t\treturn nil\n\t}\n}", "func Transaction(ctx context.Context, db *sql.DB, f func(tx *sql.Tx) error) (err error) {\n\tfinish := func(tx *sql.Tx) {\n\t\tif err != nil {\n\t\t\tif err2 := tx.Rollback(); err2 != nil {\n\t\t\t\terr = multierror.Append(err, err2)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\terr = tx.Commit()\n\t}\n\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"Transaction\")\n\tdefer func() {\n\t\tif err != nil {\n\t\t\text.Error.Set(span, true)\n\t\t\tspan.SetTag(\"err\", err.Error())\n\t\t}\n\t\tspan.Finish()\n\t}()\n\n\ttx, err := db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer finish(tx)\n\treturn f(tx)\n}", "func (dao *PagesDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {\n\treturn dao.Ctx(ctx).Transaction(ctx, f)\n}", "func Transact(db *sql.DB, txFunc func(*sql.Tx) error) (err error) {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif p := recover(); p != nil {\n\t\t\ttx.Rollback()\n\t\t\tpanic(p)\n\t\t} else if err != nil {\n\t\t\ttx.Rollback()\n\t\t} else {\n\t\t\terr = tx.Commit()\n\t\t}\n\t}()\n\terr = txFunc(tx)\n\treturn err\n}", "func (dao *SysConfigDao) Transaction(ctx context.Context, f func(ctx context.Context, tx gdb.TX) error) (err error) {\n\treturn dao.Ctx(ctx).Transaction(ctx, f)\n}", "func (dp *dataProvider) Tx(fn func(*pg.Tx) error) error {\n\treturn wrapError(dp.db.RunInTransaction(func(tx *pg.Tx) error {\n\t\tdefer func(t *pg.Tx) {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tt.Rollback()\n\t\t\t\t// rethrow the panic once the database is safe\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}(tx)\n\t\treturn fn(tx)\n\t}))\n}", "func (c *Conn) Transaction(fn func(*Conn) error) error {\r\n\tvar (\r\n\t\ttx = c.Begin()\r\n\t\tconn = &Conn{}\r\n\t)\r\n\tcopier.Copy(conn, c)\r\n\tconn.DB = tx\r\n\tif err := fn(conn); err != nil {\r\n\t\ttx.Rollback()\r\n\t\treturn err\r\n\t}\r\n\ttx.Commit()\r\n\treturn nil\r\n}", "func (m PeopleMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func Register(up, down func(DB) error) error {\n\t_, file, _, _ := runtime.Caller(1)\n\tversion, err := extractVersion(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tallMigrations = append(allMigrations, Migration{\n\t\tVersion: version,\n\t\tUp: up,\n\t\tDown: down,\n\t})\n\treturn nil\n}", "func register(transaction string, cfg *Config) error {\n\treturn circuit.Register(transaction, cfg.commandName(), cfg.circuitBreaker(),\n\t\tfunc(transaction, commandName string, state string) {\n\t\t\tif state == circuit.Open {\n\t\t\t\tReConnect(transaction, cfg)\n\t\t\t} else if state == circuit.Close {\n\t\t\t\tConnected(transaction, cfg)\n\t\t\t}\n\t\t})\n}", "func Transact(db *gorm.DB, tf func(tx *gorm.DB) error) (err error) {\n\tif commonDB, ok := db.CommonDB().(sqlTx); ok && commonDB != nil {\n\t\t// If the db is already in a transaction, just execute tf\n\t\t// and let the outer transaction handle Rollback and Commit.\n\t\treturn tf(db)\n\t}\n\n\ttx := db.Begin()\n\tif tx.Error != nil {\n\t\treturn fmt.Errorf(\"could not start transaction. %s\", err)\n\t}\n\tdefer func() {\n\t\tif p := recover(); p != nil {\n\t\t\ttx.Rollback()\n\t\t\tpanic(p)\n\t\t}\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t} else {\n\t\t\terr = tx.Commit().Error\n\t\t}\n\t}()\n\treturn tf(tx)\n}", "func (_Ethdkg *EthdkgTransactor) Register(opts *bind.TransactOpts, public_key [2]*big.Int) (*types.Transaction, error) {\n\treturn _Ethdkg.contract.Transact(opts, \"register\", public_key)\n}", "func (_UpkeepRegistrationRequests *UpkeepRegistrationRequestsTransactorSession) Register(name string, encryptedEmail []byte, upkeepContract common.Address, gasLimit uint32, adminAddress common.Address, checkData []byte, amount *big.Int, source uint8) (*types.Transaction, error) {\n\treturn _UpkeepRegistrationRequests.Contract.Register(&_UpkeepRegistrationRequests.TransactOpts, name, encryptedEmail, upkeepContract, gasLimit, adminAddress, checkData, amount, source)\n}", "func (s *PersonStore) Transaction(callback func(*PersonStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PersonStore{store})\n\t})\n}", "func (db *DB) TransactionTx(ctx context.Context, fn TxHandlerFunc, opts *sql.TxOptions) error {\n\tdb.mu.Lock()\n\tdefer db.mu.Unlock()\n\n\torigin, err := db.master.BeginTx(ctx, opts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to begin transaction: %v\", err)\n\t}\n\ttx := &Tx{origin}\n\n\tif err := fn(ctx, tx); err != nil {\n\t\tif re := tx.parent.Rollback(); re != nil {\n\t\t\tif re.Error() != sql.ErrTxDone.Error() {\n\t\t\t\treturn fmt.Errorf(\"fialed to rollback: %v\", err)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"failed to execcute transaction: %v\", err)\n\t}\n\treturn tx.parent.Commit()\n}", "func (m EventRSVPMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (ingest *Ingestion) Transaction(\n\tid int64,\n\ttx *core.Transaction,\n\tfee *core.TransactionFee,\n) error {\n\n\tsql := ingest.transactionInsertBuilder(id, tx, fee)\n\t_, err := ingest.DB.Exec(sql)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (dao *InfoDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {\n\treturn dao.Ctx(ctx).Transaction(ctx, f)\n}", "func (m CleanernameMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m MedicalrecordstaffMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (_KNS *KNSTransactorSession) Register(prime_owner common.Address, wallet common.Address, Jid string, tel string) (*types.Transaction, error) {\n\treturn _KNS.Contract.Register(&_KNS.TransactOpts, prime_owner, wallet, Jid, tel)\n}", "func (db *database) Transact(txHandler func(tx *sqlx.Tx) error) (err error) {\n\ttx, err := db.Beginx()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to begin transaction\")\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\t_ = tx.Rollback()\n\t\t\tpanic(r)\n\t\t}\n\n\t\tif err != nil {\n\t\t\t_ = tx.Rollback()\n\t\t\treturn\n\t\t}\n\n\t\ttx.Commit()\n\t}()\n\n\terr = txHandler(tx)\n\treturn\n}", "func WithTransaction(db *sqlx.DB, fn TxFn) (err error) {\n\ttx, err := db.Beginx()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\tif p := recover(); p != nil { // recover from panic\n\t\t\ttx.Rollback()\n\t\t\tpanic(p)\n\t\t} else if err != nil { // rollback because error happens\n\t\t\ttx.Rollback()\n\t\t} else { // no error, commit\n\t\t\terr = tx.Commit()\n\t\t}\n\t}()\n\n\terr = fn(tx)\n\treturn err\n}", "func Transact(db DB, fn func(tx *sql.Tx) error) (err error) {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif p := recover(); p != nil {\n\t\t\ttx.Rollback()\n\t\t\tpanic(p)\n\t\t} else if err != nil {\n\t\t\ttx.Rollback()\n\t\t} else {\n\t\t\terr = tx.Commit()\n\t\t}\n\t}()\n\terr = fn(tx)\n\treturn err\n}", "func (exec *StormPerf) runInTx(fn func(tx storm.Node) error) error {\n\ttx, err := exec.db.Begin(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Rollback()\n\n\tif err := fn(tx); err != nil {\n\t\treturn err\n\t}\n\n\treturn tx.Commit()\n}", "func (s *UserStore) Transaction(callback func(*UserStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&UserStore{store})\n\t})\n}", "func (store *Store) execTx(ctx context.Context, fn func(*Queries) error) error {\n\ttx, err := store.db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tq := New(tx)\n\terr = fn(q)\n\tif err != nil {\n\t\tif rbErr := tx.Rollback(); rbErr != nil {\n\t\t\treturn fmt.Errorf(\"tx err: %v, rb err: %v\", err, rbErr)\n\t\t}\n\t\treturn err\n\t}\n\n\treturn tx.Commit()\n}", "func upsertMigrationStateTx(tx *sql.Tx, state *MigrationState, incrementNextMigration bool) (err error) {\n\tif incrementNextMigration {\n\t\tstate.NextMigration++\n\t}\n\tmigrationStateJSON := encoding.EncodeJSON(state)\n\t_, err = tx.Exec(setMetastateUpsert, migrationMetastateKey, migrationStateJSON)\n\n\treturn err\n}", "func (db *DataBase) Register(user *models.UserPrivateInfo) (userID int, err error) {\n\n\tvar (\n\t\ttx *sql.Tx\n\t)\n\n\tif tx, err = db.Db.Begin(); err != nil {\n\t\treturn\n\t}\n\tdefer tx.Rollback()\n\n\tif userID, err = db.createPlayer(tx, user); err != nil {\n\t\treturn\n\t}\n\n\tif err = db.createRecords(tx, userID); err != nil {\n\t\treturn\n\t}\n\n\terr = tx.Commit()\n\treturn\n}", "func NewTx(sqlTx *sql.Tx) (sqlbuilder.Tx, error) {\n\treturn registeredAdapter.NewTx(sqlTx)\n}", "func (m ZoneMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (t *Transaction) RegisterExecute(fun func() error) {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\n\tt.execute = append(t.execute, fun)\n}", "func setupTX(t testing.TB) (*reform.DB, *reform.TX) {\n\tt.Helper()\n\n\tdb := setupDB(t)\n\n\ttx, err := db.Begin()\n\trequire.NoError(t, err)\n\treturn db, tx\n}", "func (_KNS *KNSSession) Register(prime_owner common.Address, wallet common.Address, Jid string, tel string) (*types.Transaction, error) {\n\treturn _KNS.Contract.Register(&_KNS.TransactOpts, prime_owner, wallet, Jid, tel)\n}", "func (m PatientrightstypeMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m StartWorkMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (b *Store) CreateTx(ctx context.Context, tx *sql.Tx, userID, username, password string) error {\n\terr := permission.LimitCheckAny(ctx, permission.System, permission.Admin, permission.MatchUser(userID))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = validate.Many(\n\t\tvalidate.UUID(\"UserID\", userID),\n\t\tvalidate.UserName(\"UserName\", username),\n\t\tvalidate.Text(\"Password\", password, 8, 200),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), passCost)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = tx.StmtContext(ctx, b.insert).ExecContext(ctx, userID, username, string(hashedPassword))\n\treturn err\n}", "func (r *OrdersRepository) Tx() (tx *dbr.Tx, err error) {\n\tdb := r.PG.PostgresTrade()\n\n\ttx, err = db.Begin()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"event\": \"error when begin transaction in postgres\",\n\t\t}).Error(err)\n\t}\n\n\treturn\n}", "func Transaction(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\tt, ctx := orm.NewTransaction(r.Context())\n\t\tdefer func() {\n\t\t\tif rec := recover(); rec != nil {\n\t\t\t\tt.Rollback()\n\t\t\t\t// Panic to let recoverer handle 500\n\t\t\t\tpanic(rec)\n\t\t\t} else {\n\t\t\t\terr := t.Commit()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func (m ResourceMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (d DB) Transaction(f func(DB) error) error {\n\tif _, ok := d.dbProxy.(*sql.Tx); ok {\n\t\t// Already in a nested transaction\n\t\treturn f(d)\n\t}\n\n\ttx, err := d.dbProxy.(*sql.DB).Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = f(DB{\n\t\tdbProxy: tx,\n\t\tStatementBuilderType: statementBuilder(tx),\n\t})\n\tif err != nil {\n\t\t// Rollback error is ignored as we already have one in progress\n\t\tif err2 := tx.Rollback(); err2 != nil {\n\t\t\tlevel.Warn(util_log.Logger).Log(\"msg\", \"transaction rollback error (ignored)\", \"err\", err2)\n\t\t}\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}", "func (_UpkeepRegistrationRequests *UpkeepRegistrationRequestsSession) Register(name string, encryptedEmail []byte, upkeepContract common.Address, gasLimit uint32, adminAddress common.Address, checkData []byte, amount *big.Int, source uint8) (*types.Transaction, error) {\n\treturn _UpkeepRegistrationRequests.Contract.Register(&_UpkeepRegistrationRequests.TransactOpts, name, encryptedEmail, upkeepContract, gasLimit, adminAddress, checkData, amount, source)\n}", "func (acn *Account) registryTransaction(tsn *Transaction) {\n\tacn.transactions = append(acn.transactions, tsn)\n}", "func (m NametitleMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m CarbrandMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (dao *ConfigAuditProcessDao) Transaction(ctx context.Context, f func(ctx context.Context, tx *gdb.TX) error) (err error) {\n\treturn dao.Ctx(ctx).Transaction(ctx, f)\n}", "func (pge *PgEngine) StartTransaction(ctx context.Context) (pgx.Tx, error) {\n\treturn pge.ConfigDb.Begin(ctx)\n}", "func (m PlaceMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m CarserviceMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m BillingstatusMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m TenantMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m TenantMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m BookcourseMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (store *Store) execTx(ctx context.Context, fn func(*Queries) error) error {\n\ttx, err := store.db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tq := New(tx) // create a new Queries object but instead of passing in sql.DB, we are passing in a sql.Tx Object for transactions\n\terr = fn(q) // call the input function as queries\n\t// If there was an error with the transaction\n\tif err != nil {\n\t\tif rollbackErr := tx.Rollback(); rollbackErr != nil {\n\t\t\treturn fmt.Errorf(\"tx error: %v, rollback error: %v\", err, rollbackErr)\n\t\t}\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}", "func (m PatientrightsMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m BarTimeRangeMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func ExecuteInTxAndRollback(t *testing.T, db *sql.DB, f func(tx *sql.Tx)) {\n\ttx, err := db.Begin()\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\terr := tx.Rollback()\n\t\trequire.NoError(t, err)\n\t}()\n\n\tf(tx)\n}", "func (m CarRepairrecordMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (db *DB) WriteTx() *WriteTx {\n\treturn &WriteTx{\n\t\tdb: db,\n\t}\n}", "func AddTx(m *Tx) (err error) {\n\td := db.Create(m)\n\treturn d.Error\n}", "func (s *Service) CreateTx(tx *sql.Tx, headerID uint, ms Models) error {\n\treturn s.storage.CreateTx(tx, headerID, ms)\n}", "func (store *SQLStore) execTx(ctx context.Context, fn func(*Queries) error) error {\n\ttx, err := store.db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// get back new query object \n\tq := New(tx)\n\terr = fn(q)\n\t// rollback on error - if rollback error return both errors \n\tif err != nil {\n\t\tif rbErr := tx.Rollback(); rbErr != nil {\n\t\t\treturn fmt.Errorf(\"tx err: %v, rb err: %v\", err, rbErr)\n\t\t}\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}", "func (m EndWorkMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m ZoneproductMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func StartTransaction(w http.ResponseWriter, DB *sql.DB) (*sql.Tx, error) {\n\tvar err error\n\ttx, err := DB.Begin()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\trequestUtils.RespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn nil, err\n\t}\n\treturn tx, err\n}", "func (m CompanyMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func Transaction(ctx context.Context, driver Driver, opts *TxOptions,\n\thandler func(driver Driver) error) error {\n\n\tif driver == nil {\n\t\treturn errors.Wrap(ErrInvalidDriver, \"makroud: cannot create a transaction\")\n\t}\n\n\ttx, err := driver.Begin(ctx, opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = handler(tx)\n\tif err != nil {\n\n\t\tthr := tx.Rollback()\n\t\tif thr != nil && driver.HasObserver() {\n\t\t\tthr = errors.Wrap(thr, \"makroud: trying to rollback transaction\")\n\t\t\tdriver.Observer().OnRollback(thr, nil)\n\t\t}\n\n\t\treturn err\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *PetStore) Transaction(callback func(*PetStore) error) error {\n\tif callback == nil {\n\t\treturn kallax.ErrInvalidTxCallback\n\t}\n\n\treturn s.Store.Transaction(func(store *kallax.Store) error {\n\t\treturn callback(&PetStore{store})\n\t})\n}", "func (_PlasmaFramework *PlasmaFrameworkTransactor) RegisterVault(opts *bind.TransactOpts, _vaultId *big.Int, _vaultAddress common.Address) (*types.Transaction, error) {\n\treturn _PlasmaFramework.contract.Transact(opts, \"registerVault\", _vaultId, _vaultAddress)\n}", "func WithTx(db *sql.DB, query func(*sql.Tx) error) error {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Rollback()\n\terr = query(tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}", "func (m AgeMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func withTransaction(db *sql.DB, fn func(txn *sql.Tx) error) (err error) {\n\ttxn, err := db.Begin()\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\ttxn.Rollback()\n\t\t\tpanic(r)\n\t\t} else if err != nil {\n\t\t\ttxn.Rollback()\n\t\t} else {\n\t\t\terr = txn.Commit()\n\t\t}\n\t}()\n\terr = fn(txn)\n\treturn\n}", "func Register(ext *sqlite.ExtensionApi, opt *options.Options) (_ sqlite.ErrorCode, err error) {\n\t// register virtual table modules\n\tvar modules = map[string]sqlite.Module{\n\t\t\"commits\": &LogModule{Locator: opt.Locator, Context: opt.Context},\n\t\t\"refs\": &RefModule{Locator: opt.Locator, Context: opt.Context},\n\t\t\"stats\": native.NewStatsModule(opt.Locator, opt.Context),\n\t\t\"files\": native.NewFilesModule(opt.Locator, opt.Context),\n\t\t\"blame\": native.NewBlameModule(opt.Locator, opt.Context),\n\t}\n\n\tfor name, mod := range modules {\n\t\tif err = ext.CreateModule(name, mod); err != nil {\n\t\t\treturn sqlite.SQLITE_ERROR, errors.Wrapf(err, \"failed to register %q module\", name)\n\t\t}\n\t}\n\n\tvar fns = map[string]sqlite.Function{\n\t\t\"commit_from_tag\": &CommitFromTagFn{},\n\t}\n\n\tfor name, fn := range fns {\n\t\tif err = ext.CreateFunction(name, fn); err != nil {\n\t\t\treturn sqlite.SQLITE_ERROR, errors.Wrapf(err, \"failed to register %q function\", name)\n\t\t}\n\t}\n\n\treturn sqlite.SQLITE_OK, nil\n}", "func (m RobberMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m IntervalMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m RestaurantMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m RestaurantMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m HexMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m StreetMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m BloodtypeMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func RegisterTxHandlers(mux *http.ServeMux, gateway *daemon.Gateway) {\n\t// get set of pending transactions\n\tmux.HandleFunc(\"/pendingTxs\", getPendingTxs(gateway))\n\t// get latest confirmed transactions\n\tmux.HandleFunc(\"/lastTxs\", getLastTxs(gateway))\n\t// get txn by txid\n\tmux.HandleFunc(\"/transaction\", getTransactionByID(gateway))\n\t//inject a transaction into network\n\tmux.HandleFunc(\"/injectTransaction\", injectTransaction(gateway))\n\tmux.HandleFunc(\"/resendUnconfirmedTxns\", resendUnconfirmedTxns(gateway))\n\t// get raw tx by txid.\n\tmux.HandleFunc(\"/rawtx\", getRawTx(gateway))\n}", "func (m BarGroupMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}" ]
[ "0.6274189", "0.6211087", "0.6139333", "0.61136764", "0.61018455", "0.6091702", "0.6074261", "0.6053163", "0.6053163", "0.6019075", "0.6001216", "0.5968726", "0.59503096", "0.59449434", "0.5939692", "0.5934833", "0.5924858", "0.5907003", "0.59001046", "0.5847809", "0.5808601", "0.58057183", "0.57678246", "0.57521385", "0.57298934", "0.5723418", "0.56890404", "0.5686981", "0.5682871", "0.56789476", "0.56754917", "0.5669826", "0.5666833", "0.56366825", "0.5630492", "0.5623383", "0.56181926", "0.5609718", "0.56075746", "0.55959666", "0.5594622", "0.5593809", "0.558488", "0.55811334", "0.5580892", "0.5573819", "0.5570477", "0.5565422", "0.55588746", "0.5558231", "0.5556222", "0.5548939", "0.5548236", "0.55463326", "0.55455434", "0.5545094", "0.5538741", "0.5538221", "0.55315137", "0.552274", "0.5512343", "0.5487771", "0.5486829", "0.54835147", "0.5483118", "0.5481372", "0.5478997", "0.54788065", "0.54774946", "0.54774946", "0.54640216", "0.54635143", "0.5459946", "0.5458405", "0.54575187", "0.54568124", "0.545679", "0.5454698", "0.5443165", "0.5442465", "0.5431117", "0.54172456", "0.54128116", "0.54123956", "0.54115444", "0.5410089", "0.54045856", "0.5403393", "0.540323", "0.540245", "0.540213", "0.539376", "0.5391048", "0.5390724", "0.5390724", "0.5388489", "0.53811234", "0.5376541", "0.53723437", "0.53618026" ]
0.7387559
0
RegisteredMigrations returns currently registered Migrations.
func RegisteredMigrations() []*Migration { return DefaultCollection.Migrations() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m Migrator) RunMigrations() error {\n\t// Run everything in a transaction. In case of error, we can roll it back\n\ttx, err := m.Connection.Database.Begin()\n\tif err != nil {\n\t\t// Connection could not be started\n\t\treturn err\n\t}\n\n\t// First check if the database db_migrations exists\n\tres := tx.QueryRow(`SELECT EXISTS(\n\t\tSELECT *\n\t\tFROM information_schema.tables\n\t\tWHERE\n\t\t\ttable_schema = 'public' AND\n\t\t\ttable_name = 'db_migrations'\n\t)`)\n\n\tvar migTablePresent bool\n\terr = res.Scan(&migTablePresent)\n\tif err != nil {\n\t\t// result was invalid\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\talreadyRunMigrations := make(map[string]bool)\n\tif !migTablePresent {\n\t\t_, err = tx.Query(`\n\t\t\tCREATE TABLE db_migrations (version VARCHAR(50) NOT NULL, executed_at TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(version))\n\t\t`)\n\t\tif err != nil {\n\t\t\t// could not create db_migration table\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tversionRows, err := tx.Query(`\n\t\t\tSELECT version FROM db_migrations\n\t\t`)\n\t\tif err != nil {\n\t\t\t// could not fetch the list of executed migrations\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t\tfor versionRows.Next() {\n\t\t\tvar version string\n\t\t\terr = versionRows.Scan(&version)\n\t\t\tif err != nil {\n\t\t\t\t// A version number could not be parsed\n\t\t\t\ttx.Rollback()\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\talreadyRunMigrations[version] = true\n\t\t}\n\t}\n\n\tavailableMigrations, err := m.checkAvailableMigrations()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\tvar migrationsToRun []string\n\tfor version := range availableMigrations {\n\t\tif _, ok := alreadyRunMigrations[version]; !ok {\n\t\t\tmigrationsToRun = append(migrationsToRun, version)\n\t\t}\n\t}\n\tfor version := range alreadyRunMigrations {\n\t\tif _, ok := availableMigrations[version]; !ok {\n\t\t\t// Warn there is a present migration with no corresponding file\n\t\t}\n\t}\n\n\tfor _, version := range migrationsToRun {\n\t\tmigrationByteContent, err := migration.Asset(fmt.Sprintf(\"%s_up.sql\", version))\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t\tmigrationContent := string(migrationByteContent)\n\n\t\t_, err = tx.Query(migrationContent)\n\t\tif err != nil {\n\t\t\t// There was an error running the migration\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.Query(`INSERT INTO db_migrations (version) VALUES ($1)`, version)\n\t\tif err != nil {\n\t\t\t// There was an error running the migration\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttx.Commit()\n\n\treturn nil\n}", "func Migrations() *Migrate {\n\tif migrations == nil {\n\t\tmigrations = &Migrate{\n\t\t\tdb: nil,\n\t\t\tprepared: false,\n\t\t\tmigrations: map[string]*gormigrate.Migration{},\n\t\t}\n\t}\n\n\treturn migrations\n}", "func RegisteredVersions() (versions []int64) {\n\tmigrations := pgmigrations.DefaultCollection.Migrations()\n\tfor _, m := range migrations {\n\t\tversions = append(versions, m.Version)\n\t}\n\treturn\n}", "func GetMigrations(configuration MigrationConfiguration) Migrations {\n\tm := Migrations{}\n\n\t// Version 0\n\tm = append(m, steps{ExecuteSQLFile(\"000-bootstrap.sql\")})\n\n\t// Version 1\n\tm = append(m, steps{ExecuteSQLFile(\"001-identities-users.sql\")})\n\n\t// Version 2\n\tm = append(m, steps{ExecuteSQLFile(\"002-oauth-states.sql\")})\n\n\t// Version 3\n\tm = append(m, steps{ExecuteSQLFile(\"003-space-resources.sql\")})\n\n\t// Version 4\n\tm = append(m, steps{ExecuteSQLFile(\"004-unique-resource-space.sql\")})\n\n\t// Version 5\n\tm = append(m, steps{ExecuteSQLFile(\"005-authorization.sql\")})\n\n\t// Version 6\n\tm = append(m, steps{ExecuteSQLFile(\"006-external-provider.sql\")})\n\n\t// Version 7\n\tm = append(m, steps{ExecuteSQLFile(\"007-external-provider-id-index.sql\")})\n\n\t// Version 8\n\tm = append(m, steps{ExecuteSQLFile(\"008-rename-token-table.sql\")})\n\n\t// Version 9\n\tm = append(m, steps{ExecuteSQLFile(\"009-external-token-hard-delete.sql\")})\n\n\t// Version 10\n\tdefaultCluster := configuration.GetOpenShiftClientApiUrl()\n\tm = append(m, steps{ExecuteSQLFile(\"010-add-cluster-to-user.sql\", defaultCluster)})\n\n\t// Version 11\n\tm = append(m, steps{ExecuteSQLFile(\"011-add-username-to-external-token.sql\")})\n\n\t// Version 12\n\tm = append(m, steps{ExecuteSQLFile(\"012-hide-email.sql\")})\n\n\t// Version 13\n\tm = append(m, steps{ExecuteSQLFile(\"013-add-email-verified.sql\")})\n\n\t// Version 14\n\tm = append(m, steps{ExecuteSQLFile(\"014-add-user-feature-level.sql\")})\n\n\t// Version 15\n\tm = append(m, steps{ExecuteSQLFile(\"015-clear-resources-create-resource-types.sql\")})\n\n\t// Version 16\n\tm = append(m, steps{ExecuteSQLFile(\"016-add-state-to-auth-state-reference.sql\")})\n\n\t// Version 17\n\tm = append(m, steps{ExecuteSQLFile(\"017-feature-level-not-null.sql\")})\n\n\t// Version 18\n\tm = append(m, steps{ExecuteSQLFile(\"018-convert-user-feature-level.sql\")})\n\n\t// Version 19\n\tm = append(m, steps{ExecuteSQLFile(\"019-authorization-part-2.sql\")})\n\n\t// Version 20\n\tm = append(m, steps{ExecuteSQLFile(\"020-add-response-mode-to-auth-state-reference.sql\")})\n\n\t// Version 21\n\tm = append(m, steps{ExecuteSQLFile(\"021-organizations-list-create.sql\")})\n\n\t// Version 22\n\tm = append(m, steps{ExecuteSQLFile(\"022-add-deprovisioned-to-user.sql\")})\n\n\t// Version 23\n\tm = append(m, steps{ExecuteSQLFile(\"023-resource-type-index.sql\")})\n\n\t// Version 24\n\tm = append(m, steps{ExecuteSQLFile(\"024-role-mapping-and-team-and-group-identities.sql\")})\n\n\t// Version 25\n\tm = append(m, steps{ExecuteSQLFile(\"025-fix-feature-level.sql\")})\n\n\t// Version 26\n\tm = append(m, steps{ExecuteSQLFile(\"026-identities-users-indexes.sql\")})\n\n\t// Version 27\n\tm = append(m, steps{ExecuteSQLFile(\"027-invitations.sql\")})\n\n\t// Version 28\n\tm = append(m, steps{ExecuteSQLFile(\"028-make-organization-names-unique.sql\")})\n\n\t// Version 29\n\tm = append(m, steps{ExecuteSQLFile(\"029-add-space-resourcetype.sql\")})\n\n\t// Version 30\n\tm = append(m, steps{ExecuteSQLFile(\"030-add-team-admin-role.sql\")})\n\n\t// Version 31\n\tm = append(m, steps{ExecuteSQLFile(\"031-clean-up-roles-scopes.sql\")})\n\n\t// Version 32\n\tm = append(m, steps{ExecuteSQLFile(\"032-invitation-code.sql\")})\n\n\t// Version 33\n\tm = append(m, steps{ExecuteSQLFile(\"033-drop-space-resources.sql\")})\n\n\t// Version 34\n\tm = append(m, steps{ExecuteSQLFile(\"034-rename-token-table.sql\")})\n\n\t// Version 35\n\tm = append(m, steps{ExecuteSQLFile(\"035-unique_constraint_default_role_mapping.sql\")})\n\n\t// Version 36\n\tm = append(m, steps{ExecuteSQLFile(\"036-token-privileges.sql\")})\n\n\t// Version 37\n\tm = append(m, steps{ExecuteSQLFile(\"037-invitation-redirect-url.sql\")})\n\n\t// Version 38\n\tm = append(m, steps{ExecuteSQLFile(\"038-admin-console-resource.sql\")})\n\n\t// Version 39\n\tm = append(m, steps{ExecuteSQLFile(\"039-resource-type-alter.sql\")})\n\n\t// Version 40\n\tm = append(m, steps{ExecuteSQLFile(\"040-deferrable-constraints.sql\")})\n\n\t// Version 41\n\tm = append(m, steps{ExecuteSQLFile(\"041-identity-role-index.sql\")})\n\n\t// Version 42\n\tm = append(m, steps{ExecuteSQLFile(\"042-token-index.sql\")})\n\n\t// Version 43\n\tm = append(m, steps{ExecuteSQLFile(\"043-add-admin-console-resource.sql\")})\n\n\t// Version 44\n\tm = append(m, steps{ExecuteSQLFile(\"044-user-active.sql\")})\n\n\t// Version 45\n\tm = append(m, steps{ExecuteSQLFile(\"045-identity-last-active.sql\")})\n\n\t// Version 46\n\tm = append(m, steps{ExecuteSQLFile(\"046-identity-last-active-default.sql\")})\n\n\t// Version 47\n\tm = append(m, steps{ExecuteSQLFile(\"047-add-user-banned-column.sql\")})\n\n\t// Version 48\n\tm = append(m, steps{ExecuteSQLFile(\"048-identity-deactivation-notification.sql\")})\n\n\t// Version 49\n\tm = append(m, steps{ExecuteSQLFile(\"049-user-banned-index.sql\")})\n\n\t// Version 50\n\tm = append(m, steps{ExecuteSQLFile(\"050-worker-lock.sql\")})\n\n\t// Version 51\n\tm = append(m, steps{ExecuteSQLFile(\"051-identity-deactivation-scheduled.sql\")})\n\n\t// Version 52\n\tm = append(m, steps{ExecuteSQLFile(\"052-deferrable-constraints2.sql\")})\n\n\t// Version 53\n\tm = append(m, steps{ExecuteSQLFile(\"053-deactivation-indexes.sql\")})\n\n\t// Version 54\n\tm = append(m, steps{ExecuteSQLFile(\"054-cleanup-oauth-state-references.sql\")})\n\n\t// Version N\n\t//\n\t// In order to add an upgrade, simply append an array of MigrationFunc to the\n\t// the end of the \"migrations\" slice. The version numbers are determined by\n\t// the index in the array. The following code in comments show how you can\n\t// do a migration in 3 steps. If one of the steps fails, the others are not\n\t// executed.\n\t// If something goes wrong during the migration, all you need to do is return\n\t// an error that is not nil.\n\n\t/*\n\t\tm = append(m, steps{\n\t\t\tfunc(db *sql.Tx) error {\n\t\t\t\t// Execute random go code\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tExecuteSQLFile(\"YOUR_OWN_FILE.sql\"),\n\t\t\tfunc(db *sql.Tx) error {\n\t\t\t\t// Execute random go code\n\t\t\t\treturn nil\n\t\t\t},\n\t\t})\n\t*/\n\n\treturn m\n}", "func (s Service) Available() ([]*Migration, error) {\n\tfiles, _ := filepath.Glob(filepath.Join(s.env.Directory, \"*.sql\")) // The only possible error here is a pattern error\n\n\tvar migrations []*Migration\n\tfor _, file := range files {\n\t\tmigration, err := NewMigration(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmigrations = append(migrations, migration)\n\t}\n\n\tslice.Sort(migrations, func(i, j int) bool {\n\t\treturn migrations[i].Name < migrations[j].Name\n\t})\n\n\treturn migrations, nil\n}", "func (m *migrater) getNewMigrations() []migrationModel {\n\n\tvar names []string\n\tfor k, _ := range pool.migrations {\n\t\tnames = append(names, k)\n\t}\n\n\tsort.Strings(names)\n\n\tstep := 20 // limit\n\tresult := make([]migrationModel, 0)\n\texistMigrations := make(map[string]bool)\n\tfor i := 0; i < len(names); {\n\n\t\ti += step\n\t\tvar chunkNames []string\n\t\tif i <= len(names) {\n\t\t\tchunkNames = names[i-step : i]\n\t\t} else {\n\t\t\tchunkNames = names[i-step:]\n\t\t}\n\n\t\trows := make([]struct{ Name string }, 0)\n\t\tif err := m.db.Model(m.newMigrationModel()).\n\t\t\tWhere(\"name IN (?)\", chunkNames).\n\t\t\tScan(&rows).Error; err != nil {\n\n\t\t\tpanic(err)\n\t\t}\n\t\t\n\t\tfor _, row := range rows {\n\t\t\texistMigrations[row.Name] = true\n\t\t}\n\t}\n\n\tfor _, name := range names {\n\t\tif _, ok := existMigrations[name]; !ok {\n\t\t\tmodel := m.newMigrationModel()\n\t\t\tmodel.Name = name\n\t\t\tresult = append(result, model)\n\t\t}\n\t}\n\n\treturn result\n}", "func (d *SQLike) Migrations(tk *wanderer.Toolkit) ([]*wanderer.Migration, error) {\n\tif d.env.Migrations == nil || len(d.env.Migrations) == 0 {\n\t\treturn []*wanderer.Migration{}, nil\n\t}\n\n\treturn sqlike.LoadMigrations(filepath.Join(d.env.Migrations...))\n}", "func (m mysqlDialect) GetAppliedMigrations(ctx context.Context, tx Queryer, tableName string) (migrations []*AppliedMigration, err error) {\n\tmigrations = make([]*AppliedMigration, 0)\n\n\tquery := fmt.Sprintf(`\n\t\tSELECT id, checksum, execution_time_in_millis, applied_at\n\t\tFROM %s\n\t\tORDER BY id ASC`, tableName)\n\trows, err := tx.QueryContext(ctx, query)\n\tif err != nil {\n\t\treturn migrations, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tmigration := AppliedMigration{}\n\n\t\tvar appliedAt mysqlTime\n\t\terr = rows.Scan(&migration.ID, &migration.Checksum, &migration.ExecutionTimeInMillis, &appliedAt)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Failed to GetAppliedMigrations. Did somebody change the structure of the %s table?: %w\", tableName, err)\n\t\t\treturn migrations, err\n\t\t}\n\t\tmigration.AppliedAt = appliedAt.Value\n\t\tmigrations = append(migrations, &migration)\n\t}\n\n\treturn migrations, err\n}", "func getMigrations() *migrate.MemoryMigrationSource {\n\tsource := &migrate.MemoryMigrationSource{}\n\tfn := func(path string, f os.FileInfo, err error) error {\n\t\tif !f.IsDir() && strings.HasSuffix(f.Name(), \".sql\") {\n\t\t\tmigFile, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmig, err := migrate.ParseMigration(path, migFile)\n\t\t\tmigFile.Close()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsource.Migrations = append(source.Migrations, mig)\n\t\t}\n\t\treturn nil\n\t}\n\twd, _ := os.Getwd()\n\terr := filepath.Walk(filepath.Join(wd, \"migrations\"), fn)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t\treturn nil\n\t}\n\treturn source\n}", "func (s *SchemaEditor) PendingMigrations() (count int, err error) {\n\tif err = s.prepareSchemaMigrations(); err != nil {\n\t\treturn\n\t}\n\terr = s.pr.Do(func(plugin Pluginer) error {\n\t\tfor _, migration := range plugin.Migrations() {\n\t\t\tif isApplied, isError := s.IsAppliedMigration(migration, plugin); isError != nil {\n\t\t\t\treturn isError\n\t\t\t} else if isApplied == false {\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\treturn\n}", "func (p postgresDialect) GetAppliedMigrations(ctx context.Context, tx Queryer, tableName string) (migrations []*AppliedMigration, err error) {\n\tmigrations = make([]*AppliedMigration, 0)\n\n\tquery := fmt.Sprintf(`\n\t\tSELECT id, checksum, execution_time_in_millis, applied_at\n\t\tFROM %s ORDER BY id ASC\n\t`, tableName)\n\trows, err := tx.QueryContext(ctx, query)\n\tif err != nil {\n\t\treturn migrations, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tmigration := AppliedMigration{}\n\t\terr = rows.Scan(&migration.ID, &migration.Checksum, &migration.ExecutionTimeInMillis, &migration.AppliedAt)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"failed to GetAppliedMigrations. Did somebody change the structure of the %s table?: %w\", tableName, err)\n\t\t\treturn migrations, err\n\t\t}\n\t\tmigration.AppliedAt = migration.AppliedAt.In(time.Local)\n\t\tmigrations = append(migrations, &migration)\n\t}\n\n\treturn migrations, err\n}", "func ListMigrations() (migrationsList []*Migrations, err error) {\n\to := NewOrm()\n\tqs := o.QueryTable(new(Migrations))\n\tqs = qs.OrderBy(\"CreatedAt\")\n\t_, err = qs.All(&migrationsList)\n\tif err != nil {\n\t\terr = errors.Trace(err)\n\t\treturn\n\t}\n\treturn\n}", "func (f EmbedFileSystemMigrationSource) FindMigrations() ([]*migrate.Migration, error) {\n\treturn f.findMigrations()\n}", "func Register(up, down func(DB) error) error {\n\t_, file, _, _ := runtime.Caller(1)\n\tversion, err := extractVersion(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tallMigrations = append(allMigrations, Migration{\n\t\tVersion: version,\n\t\tUp: up,\n\t\tDown: down,\n\t})\n\treturn nil\n}", "func registerMigrations(ctx context.Context, db dbutil.DB, outOfBandMigrationRunner *oobmigration.Runner) error {\n\tmigrators := map[int]oobmigration.Migrator{\n\t\tmigration.DiagnosticsCountMigrationID: migration.NewDiagnosticsCountMigrator(services.lsifStore, config.DiagnosticsCountMigrationBatchSize),\n\t\tmigration.DefinitionsCountMigrationID: migration.NewLocationsCountMigrator(services.lsifStore, \"lsif_data_definitions\", config.DefinitionsCountMigrationBatchSize),\n\t\tmigration.ReferencesCountMigrationID: migration.NewLocationsCountMigrator(services.lsifStore, \"lsif_data_references\", config.ReferencesCountMigrationBatchSize),\n\t}\n\n\tfor id, migrator := range migrators {\n\t\tif err := outOfBandMigrationRunner.Register(id, migrator, oobmigration.MigratorOptions{Interval: time.Second}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func ApplyMigrations(config *config.Config, createConnector func(*config.Config) db.Connector, createLoader func(*config.Config) loader.Loader) []types.Migration {\n\tdiskMigrations := LoadDiskMigrations(config, createLoader)\n\tdbMigrations := LoadDBMigrations(config, createConnector)\n\tmigrationsToApply := migrations.ComputeMigrationsToApply(diskMigrations, dbMigrations)\n\n\tlog.Printf(\"Found [%d] migrations to apply ==> OK\", len(migrationsToApply))\n\tdoApplyMigrations(migrationsToApply, config, createConnector)\n\n\tnotifier := notifications.CreateNotifier(config)\n\ttext := fmt.Sprintf(\"Migrations applied: %d\", len(migrationsToApply))\n\tresp, err := notifier.Notify(text)\n\n\tif err != nil {\n\t\tlog.Printf(\"Notifier err: %q\", err)\n\t} else {\n\t\tlog.Printf(\"Notifier response: %q\", resp)\n\t}\n\n\treturn migrationsToApply\n}", "func (m *migrations) getMigrations() (Migrations, error) {\n\tnames := m.fs.Files()\n\tmm := make(map[int64]*Migration)\n\tfor _, name := range names {\n\t\tfields := parseScriptName(name)\n\t\tif len(fields) == 0 {\n\t\t\treturn nil, errors.Errorf(\"Invalid migration name '%s' should be like /path/to/M023_MyMigration.sql\", name)\n\t\t}\n\n\t\tid, err := strconv.ParseInt(fields[\"id\"], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Invalid migration id '%s' for '%s'\", fields[\"id\"], name)\n\t\t}\n\n\t\tif m, exists := mm[id]; exists {\n\t\t\treturn nil, errors.Errorf(\"Duplicate migration ids: '%s' and '%s' have the same id\", m.Name, fields[\"name\"])\n\t\t}\n\n\t\tcontents, err := m.loadScript(name)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Error loading script '%s'\", name)\n\t\t}\n\n\t\tmm[id] = &Migration{\n\t\t\tId: id,\n\t\t\tType: fields[\"type\"],\n\t\t\tName: fields[\"name\"],\n\t\t\tScript: string(contents),\n\t\t}\n\t}\n\tresult := getSortedMigrations(mm)\n\treturn result, nil\n}", "func (m *User) GetManagedAppRegistrations()([]ManagedAppRegistrationable) {\n return m.managedAppRegistrations\n}", "func LoadMigrations() ([]*Migration, error) {\n\tfiles, err := ioutil.ReadDir(migrateName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm := []*Migration{}\n\n\tfor _, fn := range files {\n\t\tg, err := ReadMigration(fn.Name())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tm = append(m, g)\n\t}\n\n\treturn m, nil\n}", "func all() (map[string]*Migration, error) {\n\tmigrations := map[string]*Migration{}\n\n\tdir, err := FS.Open(config.MigrationsPath)\n\tif err != nil {\n\t\treturn migrations, err\n\t}\n\n\tfiles, err := dir.Readdir(0)\n\tif err != nil {\n\t\treturn migrations, err\n\t}\n\n\tfor _, file := range files {\n\t\tif valid(file.Name()) {\n\t\t\tid := migrationID(file.Name())\n\t\t\tif _, ok := migrations[id]; !ok {\n\t\t\t\tmigrations[id] = &Migration{\n\t\t\t\t\tID: id,\n\t\t\t\t}\n\t\t\t}\n\t\t\tm := migrations[id]\n\t\t\tm.AddPath(path.Join(config.MigrationsPath, file.Name()))\n\t\t}\n\t}\n\n\treturn migrations, nil\n}", "func (s *MigrationService) ListMigrations(ctx context.Context, org string) ([]*Migration, *Response, error) {\n\tu := fmt.Sprintf(\"orgs/%v/migrations\", org)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// TODO: remove custom Accept header when this API fully launches.\n\treq.Header.Set(\"Accept\", mediaTypeMigrationsPreview)\n\n\tvar m []*Migration\n\tresp, err := s.client.Do(ctx, req, &m)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn m, resp, nil\n}", "func (o *Claims) GetMigrationsLog() map[string]string {\n\n\treturn o.MigrationsLog\n}", "func (pluginConfig *Plugin) GetMigrationsPaths() ([]string, error) {\n\tpaths := make(map[uint64]string)\n\thighestRank := -1\n\tfor name, transformer := range pluginConfig.Transformers {\n\t\trepo := transformer.RepositoryPath\n\t\tmig := transformer.MigrationPath\n\t\tpath := filepath.Join(\"$GOPATH/src\", pluginConfig.Home, \"vendor\", repo, mig)\n\t\tcleanPath, err := helpers.CleanPath(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// If there is a different path with the same rank then we have a conflict\n\t\t_, ok := paths[transformer.MigrationRank]\n\t\tif ok {\n\t\t\tconflictingPath := paths[transformer.MigrationRank]\n\t\t\tif conflictingPath != cleanPath {\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"transformer %s has the same migration rank (%d) as another transformer\", name, transformer.MigrationRank))\n\t\t\t}\n\t\t}\n\t\tpaths[transformer.MigrationRank] = cleanPath\n\t\tif int(transformer.MigrationRank) >= highestRank {\n\t\t\thighestRank = int(transformer.MigrationRank)\n\t\t}\n\t}\n\t// Check for gaps and duplicates\n\tif len(paths) != (highestRank + 1) {\n\t\treturn []string{}, errors.New(\"number of distinct ranks does not match number of distinct migration paths\")\n\t}\n\tif anyDupes(paths) {\n\t\treturn []string{}, errors.New(\"duplicate paths with different ranks present\")\n\t}\n\n\tsortedPaths := make([]string, len(paths))\n\tfor rank, path := range paths {\n\t\tsortedPaths[rank] = path\n\t}\n\n\treturn sortedPaths, nil\n}", "func AddMigrations(mg *Migrator) {\n\taddMigrationLogMigrations(mg)\n\taddCollectorMigration(mg)\n\taddCheckMigration(mg)\n\taddEndpointMigration(mg)\n\taddAlertSchedulerValueMigration(mg)\n\taddQuotaMigration(mg)\n}", "func LoadDBMigrations(config *config.Config, createConnector func(*config.Config) db.Connector) []types.MigrationDB {\n\tconnector := createConnector(config)\n\tconnector.Init()\n\tdefer connector.Dispose()\n\tdbMigrations := connector.GetMigrations()\n\tlog.Printf(\"Read [%d] DB migrations ==> OK\", len(dbMigrations))\n\treturn dbMigrations\n}", "func (fs FS) Migrations() []string {\n\tresult := []string{}\n\tfor filename, contents := range fs {\n\t\t// skip empty files (minimum valid statement is `--`, a comment)\n\t\tif len(contents) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif matched, _ := filepath.Match(\"*.up.sql\", filename); matched {\n\t\t\tresult = append(result, filename)\n\t\t}\n\t}\n\tsort.Strings(result)\n\treturn result\n}", "func GetAll(db gorp.SqlExecutor) ([]sdk.Migration, error) {\n\tvar migs []sdk.Migration\n\n\tif _, err := db.Select(&migs, \"SELECT cds_migration.* FROM cds_migration\"); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, sdk.WrapError(err, \"Cannot get migrations\")\n\t}\n\n\treturn migs, nil\n}", "func Registered() map[string]driver.UpdaterSetFactory {\n\tpkg.Lock()\n\tdefer pkg.Unlock()\n\tr := make(map[string]driver.UpdaterSetFactory, len(pkg.fs))\n\tfor k, v := range pkg.fs {\n\t\tr[k] = v\n\t}\n\treturn r\n}", "func Register(namespace string, migration Migration) {\n\tif _, ok := namespacedMigrations[namespace]; !ok {\n\t\tnamespacedMigrations[namespace] = make(Migrations)\n\t}\n\n\tnamespacedMigrations[namespace][migration.Version] = migration\n}", "func (db *Database) RunMigrations(ctx context.Context) error {\n\tlogger := logging.FromContext(ctx)\n\tm := gormigrate.New(db.db, gormigrate.DefaultOptions, []*gormigrate.Migration{\n\t\t{\n\t\t\tID: \"00001-CreateUsers\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating users table\")\n\t\t\t\treturn tx.AutoMigrate(&User{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"users\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00002-CreateVerificationCodes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating verification codes table\")\n\t\t\t\treturn tx.AutoMigrate(&VerificationCode{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"verification_codes\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00003-CreateAuthorizedApps\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating authorized apps table\")\n\t\t\t\treturn tx.AutoMigrate(&AuthorizedApp{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"authorized_apps\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00004-CreateTokens\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating tokens table\")\n\t\t\t\treturn tx.AutoMigrate(&Token{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"tokens\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00005-CreateCleanups\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating cleanup status table\")\n\t\t\t\tif err := tx.AutoMigrate(&CleanupStatus{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// Seed database w/ cleanup record.\n\t\t\t\tif err := tx.Create(&CleanupStatus{Type: \"cleanup\", Generation: 1, NotBefore: time.Now()}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"cleanup_statuses\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00006-AddIndexes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: add users purge index\")\n\t\t\t\tif err := tx.Model(&User{}).AddIndex(\"users_purge_index\", \"disabled\", \"updated_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: add verification code purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).AddIndex(\"ver_code_purge_index\", \"expires_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: add tokens purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).AddIndex(\"token_purge_index\", \"expires_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: drop users purge index\")\n\t\t\t\tif err := tx.Model(&User{}).RemoveIndex(\"users_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: drop verification code purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).RemoveIndex(\"ver_code_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: drop tokens purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).RemoveIndex(\"token_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00007-AddSymptomOnset\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Info(\"db migrations: rename test_date to symptom_date\")\n\t\t\t\t// AutoMigrate will add missing fields.\n\t\t\t\tif err := tx.AutoMigrate(&VerificationCode{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// If not upgrading from an old version, this column will have never been created.\n\t\t\t\tif tx.NewScope(&VerificationCode{}).HasColumn(\"test_date\") {\n\t\t\t\t\tif err := tx.Model(&VerificationCode{}).DropColumn(\"test_date\").Error; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err := tx.AutoMigrate(&Token{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// If not upgrading from an old version, this column will have never been created.\n\t\t\t\tif tx.NewScope(&Token{}).HasColumn(\"test_date\") {\n\t\t\t\t\tif err := tx.Model(&Token{}).DropColumn(\"test_date\").Error; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Info(\"db migrations: rename symptom_date to test_date\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).DropColumn(\"symptom_date\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := tx.Model(&Token{}).DropColumn(\"symptom_date\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00008-AddKeyTypes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: upgrading authorized_apps table.\")\n\t\t\t\treturn tx.AutoMigrate(&AuthorizedApp{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"admin_key\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00009-AddIssuerColumns\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: adding issuer columns to issued codes\")\n\t\t\t\treturn tx.AutoMigrate(&VerificationCode{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"issuing_user\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"issuing_app\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00010-AddSMSConfig\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: adding sms_configs table\")\n\t\t\t\treturn tx.AutoMigrate(&SMSConfig{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"sms_configs\").Error\n\t\t\t},\n\t\t},\n\t})\n\n\tlogger.Infof(\"database migrations complete\")\n\n\treturn m.Migrate()\n}", "func (m *Mock) GetRegisteredPlugins() map[string]managerContracts.Plugin {\n\targs := m.Called()\n\treturn args.Get(0).(map[string]managerContracts.Plugin)\n}", "func findMigrations(c *cli.Context) (path string, err error) {\n\tif path = c.String(\"migrations\"); path != \"\" {\n\t\treturn path, nil\n\t}\n\n\tvar cwd string\n\tif cwd, err = os.Getwd(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdirs := make([]string, 0)\n\tif err = filepath.Walk(cwd, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif info.IsDir() {\n\t\t\tbasename := strings.ToLower(info.Name())\n\t\t\tif basename == \"migrations\" {\n\t\t\t\tdirs = append(dirs, path)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif strings.HasPrefix(basename, \".\") || strings.HasPrefix(basename, \"~\") {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tswitch len(dirs) {\n\tcase 0:\n\t\treturn filepath.Rel(cwd, cwd)\n\tcase 1:\n\t\treturn filepath.Rel(cwd, dirs[0])\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"discovered %d migrations directories, please specify which one to use\", len(dirs))\n\t}\n}", "func init() {\n\tMigrations = append(Migrations, addUserMigration0001)\n}", "func List(isJson bool) (complete MigrationCollection, remaining MigrationCollection) { // should explicitly be passed Opts.JsonList\n GetMigrationFiles(Opts.Migrations)\n\n for _, mig := range Migrations {\n var isComplete, err = mig.IsComplete()\n if (err != nil) {\n fmt.Printf(\"ERROR: error checking completion status of [%s]\\n%s\\n\\n\", mig.Name, err)\n return\n }\n\n if (isComplete == false) {\n remaining = append(remaining, mig)\n } else {\n complete = append(complete, mig)\n }\n }\n\n for _, mig := range complete {\n fmt.Printf(\"%5s %s\\n\", brush.Green(\"+\"), brush.Green(mig.Name))\n }\n for _, mig := range remaining {\n fmt.Printf(\"%5s %2s\\n\", brush.Red(\"-\"), brush.Red(mig.Name))\n }\n\n return complete, remaining\n}", "func RunMigrations(db *gorm.DB) {\n\tdb.AutoMigrate(&Todo{})\n\n\tfmt.Println(\"AutoMigrations completed.\")\n}", "func Registered() (names []string) {\n\tmux.Lock()\n\tdefer mux.Unlock()\n\n\tfor key := range pool {\n\t\tnames = append(names, key)\n\t}\n\treturn names\n}", "func (p *portalProxy) CanPerformMigrations() bool {\n\treturn canPerformMigrations\n}", "func (db *Database) RunMigrations(ctx context.Context) error {\n\tlogger := logging.FromContext(ctx)\n\tm := db.getMigrations(ctx)\n\tlogger.Infof(\"database migrations started\")\n\tif err := m.Migrate(); err != nil {\n\t\tlogger.Errorf(\"migrations failed: %v\", err)\n\t\treturn err\n\t}\n\tlogger.Infof(\"database migrations completed\")\n\treturn nil\n}", "func (s *storageVersionMigrationLister) StorageVersionMigrations(namespace string) StorageVersionMigrationNamespaceLister {\n\treturn storageVersionMigrationNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func (db *IndexerDb) runAvailableMigrations() (chan struct{}, error) {\n\tstate, err := db.getMigrationState()\n\tif err == idb.ErrorNotInitialized {\n\t\tstate = MigrationState{}\n\t} else if err != nil {\n\t\treturn nil, fmt.Errorf(\"runAvailableMigrations() err: %w\", err)\n\t}\n\n\t// Make migration tasks\n\tnextMigration := state.NextMigration\n\ttasks := make([]migration.Task, 0)\n\tfor nextMigration < len(migrations) {\n\t\ttasks = append(tasks, migration.Task{\n\t\t\tHandler: wrapPostgresHandler(migrations[nextMigration].migrate, db, &state),\n\t\t\tMigrationID: nextMigration,\n\t\t\tDescription: migrations[nextMigration].description,\n\t\t\tDBUnavailable: migrations[nextMigration].blocking,\n\t\t})\n\t\tnextMigration++\n\t}\n\n\tif len(tasks) > 0 {\n\t\t// Add a task to mark migrations as done instead of using a channel.\n\t\ttasks = append(tasks, migration.Task{\n\t\t\tMigrationID: 9999999,\n\t\t\tHandler: func() error {\n\t\t\t\treturn db.markMigrationsAsDone()\n\t\t\t},\n\t\t\tDescription: \"Mark migrations done\",\n\t\t})\n\t}\n\n\tdb.migration, err = migration.MakeMigration(tasks, db.log)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tch := db.migration.RunMigrations()\n\treturn ch, nil\n}", "func (o *SparseClaims) GetMigrationsLog() (out map[string]string) {\n\n\tif o.MigrationsLog == nil {\n\t\treturn\n\t}\n\n\treturn *o.MigrationsLog\n}", "func (s Settings) ValidateMigrations() (valid bool) {\n\tvalid = true\n\n\tif s.Database != nil {\n\t\tif !s.Database.ValidateDatabase() {\n\t\t\tvalid = false\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tvalid = false\n\t\treturn\n\t}\n\n\tif s.LogsFile == \"\" {\n\t\tvalid = false\n\t}\n\treturn\n}", "func Migrations(dir string) Option {\n\treturn optionFn(func(f Fataler, data *optionData) {\n\t\terr := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif filepath.Ext(path) != \".sql\" || info.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tdata.schemaPaths = append(data.schemaPaths, path)\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tf.Fatal(err)\n\t\t}\n\t})\n}", "func registerMigration(dir string) {\n\tmigrations.MustRegisterTx(func(db migrations.DB) error {\n\t\tpath := dir + \"/up.sql\"\n\t\tsql, err := loadMigrationFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = db.Exec(sql)\n\t\treturn err\n\t}, func(db migrations.DB) error {\n\t\tpath := dir + \"/down.sql\"\n\t\tsql, err := loadMigrationFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = db.Exec(sql)\n\t\treturn err\n\t})\n}", "func (s *SQLStore) RunMigrations() error {\n\tcurrentSchemaVersion, err := s.GetCurrentVersion()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to get the current schema version\")\n\t}\n\n\tif currentSchemaVersion.LT(LatestVersion()) {\n\t\tif err := s.Migrate(currentSchemaVersion); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to complete migrations\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (drv SQLiteDriver) SelectMigrations(db *sql.DB, limit int, project string) (map[string]bool, error) {\n\tquery := \"select version from schema_migrations where project = ? order by version desc\"\n\tif limit >= 0 {\n\t\tquery = fmt.Sprintf(\"%s limit %d\", query, limit)\n\t}\n\trows, err := db.Query(query, project)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer mustClose(rows)\n\n\tmigrations := map[string]bool{}\n\tfor rows.Next() {\n\t\tvar version string\n\t\tif err := rows.Scan(&version); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmigrations[version] = true\n\t}\n\n\treturn migrations, nil\n}", "func RunMigrations(db *pg.DB) {\n\tversion, err := migrations.Version(db)\n\n\tif err != nil {\n\t\t_, _, err := migrations.Run(db, \"init\")\n\t\tlogger.Info(\"[MIGRATION] Migration table created\")\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tlogger.Info(\"[MIGRATION] Current version: \", version)\n\t_, newVersion, err := migrations.Run(db, \"up\")\n\n\tif err != nil {\n\t\tlogger.Info(\"An error happend during migration\")\n\t\tpanic(err)\n\t}\n\n\tif newVersion != version {\n\t\tlogger.Info(\"[MIGRATION] Migrated from version %d to %d\\n\", version, newVersion)\n\t} else {\n\t\tlogger.Info(\"[MIGRATION] Up to date\")\n\t}\n}", "func (o *SSHAuthority) GetMigrationsLog() map[string]string {\n\n\treturn o.MigrationsLog\n}", "func RegisteredManagers() []string {\n\tmanagersLock.RLock()\n\tdefer managersLock.RUnlock()\n\n\tlist := make([]string, 0, len(managers))\n\tfor k := range managers {\n\t\tlist = append(list, k)\n\t}\n\tsort.Strings(list)\n\treturn list\n}", "func GetLastestMigrations(onlyUpdate ...bool) (migrations *Migrations, err error) {\n\to := NewOrm()\n\tmigrations = new(Migrations)\n\tqs := o.QueryTable(migrations)\n\n\tif !(len(onlyUpdate) > 0 && !onlyUpdate[0]) {\n\t\tqs = qs.Filter(\"Status\", MigrationsStatusUpdate)\n\t}\n\n\tqs = qs.OrderBy(\"-CreatedAt\").Limit(1)\n\terr = qs.One(migrations)\n\tif err == orm.ErrNoRows {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\terr = errors.Trace(err)\n\t\treturn\n\t}\n\treturn\n}", "func (s Service) Applied() ([]*Migration, error) {\n\tfiles, err := s.conn.GetApplied()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar migrations []*Migration\n\tfor _, file := range files {\n\t\tmigration, err := NewMigration(filepath.Join(s.env.Directory, file))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmigrations = append(migrations, migration)\n\t}\n\n\tslice.Sort(migrations, func(i, j int) bool {\n\t\treturn migrations[i].Name < migrations[j].Name\n\t})\n\n\treturn migrations, nil\n}", "func (drv ClickHouseDriver) SelectMigrations(db *sql.DB, limit int) (map[string]bool, error) {\n\tquery := \"select version from schema_migrations final where applied order by version desc\"\n\tif limit >= 0 {\n\t\tquery = fmt.Sprintf(\"%s limit %d\", query, limit)\n\t}\n\trows, err := db.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer mustClose(rows)\n\n\tmigrations := map[string]bool{}\n\tfor rows.Next() {\n\t\tvar version string\n\t\tif err := rows.Scan(&version); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmigrations[version] = true\n\t}\n\n\treturn migrations, nil\n}", "func (r *SqliteRunner) GetDBMutations() ([]*DbMutation, error) {\n\tvar (\n\t\tdb = r.db\n\t\tres = make([]*DbMutation, 0)\n\t\trows *sql.Rows\n\t\texists bool\n\t\terr error\n\t)\n\n\trow := db.QueryRow(`SELECT count(*) FROM sqlite_master WHERE type='table' AND name='_dmut_mutations';`)\n\tif err = row.Scan(&exists); err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn res, nil\n\t}\n\n\t// First, extract a list of already active mutations and check if they have to be downed because they're\n\t// either inexistant or their hash changed.\n\tif rows, err = db.Query(`\n\t\tselect\n\t\t\tjson_object(\n\t\t\t\t'hash', hash,\n\t\t\t\t'name', name,\n\t\t\t\t'up', up,\n\t\t\t\t'down', down,\n\t\t\t\t'children', children\n\t\t\t) as json\n\t\tfrom _dmut_mutations m order by date_applied`); err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\ttype intermediaryMut struct {\n\t\tHash string `json:\"hash\"`\n\t\tName string `json:\"name\"`\n\t\tUp string `json:\"up\"`\n\t\tDown string `json:\"down\"`\n\t\tChildren string `json:\"children\"`\n\t}\n\n\tfor rows.Next() {\n\t\tvar inter intermediaryMut\n\t\tvar jint string\n\t\tvar dbmut DbMutation\n\t\t// besoin peut être d'une string pour lire le json avant\n\t\tif err = rows.Scan(&jint); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err = json.Unmarshal([]byte(jint), &inter); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdbmut.Name = inter.Name\n\t\tdbmut.Hash = inter.Hash\n\t\tdbmut.Children = fromJsonArray(inter.Children)\n\t\tdbmut.Up = fromJsonArray(inter.Up)\n\t\tdbmut.Down = fromJsonArray(inter.Down)\n\t\tres = append(res, &dbmut)\n\t}\n\n\treturn res, nil\n}", "func RunMigrations(c config.Context) error {\n\treturn c.Db.AutoMigrate(&Plot{})\n}", "func (mm *Meta) GetUpPlan() *Migrations {\n\treturn mm.getUpPlan().RemoveDuplicates()\n}", "func SaveAllMigrations(db gorp.SqlExecutor) error {\n\tfor _, migration := range migrations {\n\t\tmigration.Done = time.Now()\n\t\tmigration.Status = sdk.MigrationStatusDone\n\t\tmigration.Progress = \"Done because it was a fresh installation\"\n\t\tif err := Insert(db, &migration); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (m *SqlxMigrate) Migrate() error {\n\terr := m.createMigrationTable()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, migration := range m.migrations {\n\t\tvar found string\n\t\terr := m.db.Get(&found, \"SELECT id FROM migrations WHERE id=?\", migration.ID)\n\t\tswitch err {\n\t\tcase sql.ErrNoRows:\n\t\t\tlog.Printf(\"Running migration: %v\\n\", migration.ID)\n\t\t\t// we need to run the migration so we continue to code below\n\t\tcase nil:\n\t\t\tlog.Printf(\"Skipping migration: %v\\n\", migration.ID)\n\t\t\tcontinue\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"looking up migration by id: %w\", err)\n\t\t}\n\t\terr = m.runMigration(migration)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (drv *Driver) SelectMigrations(db *sql.DB, limit int) (map[string]bool, error) {\n\tquery := fmt.Sprintf(\"select version from %s order by version desc\", drv.quotedMigrationsTableName())\n\tif limit >= 0 {\n\t\tquery = fmt.Sprintf(\"%s limit %d\", query, limit)\n\t}\n\trows, err := db.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer dbutil.MustClose(rows)\n\n\tmigrations := map[string]bool{}\n\tfor rows.Next() {\n\t\tvar version string\n\t\tif err := rows.Scan(&version); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmigrations[version] = true\n\t}\n\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn migrations, nil\n}", "func (d *Database) Migrations(libraryName string, migrations ...Migration) {\n\tif _, ok := d.byLibrary[libraryName]; ok {\n\t\td.errors = append(d.errors, errors.Errorf(\"duplicate library '%s' registered with a call to Database.Migrations()\", libraryName))\n\t\treturn\n\t}\n\td.libraries = append(d.libraries, libraryName)\n\tlibList := make([]Migration, len(migrations))\n\tfor i, migration := range migrations {\n\t\tmigration := migration.Copy()\n\t\tmigration.Base().Name.Library = libraryName\n\t\td.migrationIndex[migration.Base().Name] = migration\n\t\tlibList[i] = migration\n\t\tmigration.Base().order = len(d.migrations)\n\t\td.migrations = append(d.migrations, migration)\n\t}\n\td.byLibrary[libraryName] = libList\n}", "func (c CommitterProbe) GetMutations() CommitterMutations {\n\treturn c.mutations\n}", "func (o *SparseSSHAuthority) GetMigrationsLog() (out map[string]string) {\n\n\tif o.MigrationsLog == nil {\n\t\treturn\n\t}\n\n\treturn *o.MigrationsLog\n}", "func (s *SchemaEditor) Migrate() (err error) {\n\tglog.V(2).Infof(\"patrol: running migrate.\")\n\n\tvar count int\n\tif count, err = s.PendingMigrations(); err != nil {\n\t\treturn\n\t}\n\tif count == 0 {\n\t\treturn fmt.Errorf(\"no pending migrations\")\n\t}\n\n\tif err = s.prepareSchemaMigrations(); err != nil {\n\t\treturn\n\t}\n\n\tresolver := NewSchemaDependenciesResolver(s.pr)\n\titems, err := resolver.Resolve()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, item := range items {\n\t\tisApplied, errApplied := s.IsAppliedMigration(item.migration, item.plugin)\n\t\tif errApplied != nil {\n\t\t\treturn errApplied\n\t\t}\n\n\t\tfmt.Printf(\"migration %s:%s \", yellow(item.plugin.ID()), yellow(item.migration.ID()))\n\n\t\tif isApplied {\n\t\t\tfmt.Println(\"already applied.\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// process migration\n\t\tif err := s.ProcessMigration(item.migration, item.plugin); err != nil {\n\t\t\tfmt.Printf(red(\"... Error %s\\n\"), err.Error())\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(green(\"... OK\"))\n\n\t\tfmt.Printf(\" post migrate %s:%s \", item.plugin.ID(), item.migration.ID())\n\t\tif err := item.migration.PostMigrate(s.context); err != nil {\n\t\t\tfmt.Printf(red(\"...failed. %s\\n\"), err.Error())\n\t\t}\n\t\tfmt.Println(green(\"... OK\"))\n\t}\n\n\treturn nil\n}", "func (w *dbWrapper) appliedMigrationsData(order string) ([]*migrationData, error) {\n\trows, err := w.db.Query(fmt.Sprintf(\"SELECT version, applied_at FROM %s ORDER BY %s\", w.MigrationsTable, order))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"can't get applied migrations versions\")\n\t}\n\tdefer rows.Close()\n\n\tvar mds []*migrationData\n\tvar version, appliedAt string\n\tfor rows.Next() {\n\t\terr = rows.Scan(&version, &appliedAt)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"can't scan migrations table's row\")\n\t\t}\n\n\t\tmd := &migrationData{}\n\t\tmd.version, _ = time.Parse(TimestampFormat, version)\n\t\tmd.appliedAt, _ = time.Parse(TimestampFormat, appliedAt)\n\t\tmds = append(mds, md)\n\t}\n\treturn mds, nil\n}", "func GetMigrationManager(db *mgo.Database) MigrationManager {\n\treturn migrationManagerLayer{\n\t\tdb: db,\n\t}\n}", "func (m *MigrationService) GetCurrentMigration(args []string) error {\n\tif m.existMigration() {\n\t\tfolderToCreate, timeFolder := m.getCurrentFolder()\n\t\tfmt.Println(\"Current migration folder [ \"+folderToCreate+\" ] date -> [\", timeFolder, \"]\")\n\t} else {\n\t\tfmt.Println(\"doesn't exist migration. please run [fastshop migrations new] \")\n\t}\n\n\treturn nil\n}", "func (o *User) GetManagedAppRegistrations() []MicrosoftGraphManagedAppRegistration {\n\tif o == nil || o.ManagedAppRegistrations == nil {\n\t\tvar ret []MicrosoftGraphManagedAppRegistration\n\t\treturn ret\n\t}\n\treturn *o.ManagedAppRegistrations\n}", "func (r *RemoteRegistry) RegisteredModels() []KnownModel {\n\tvar models []KnownModel\n\tfor _, model := range r.modelByName {\n\t\tmodels = append(models, model)\n\t}\n\treturn models\n}", "func (c *Client) collectMigrations(dirpath string, current, target int64) (Migrations, error) {\n\tvar migrations Migrations\n\n\t// only load migrations from file if a path is explicitly provided\n\tif dirpath != \"\" {\n\t\t// extract the numeric component of each migration,\n\t\t// filter out any uninteresting files,\n\t\t// and ensure we only have one file per migration version.\n\t\tsqlMigrations, err := filepath.Glob(dirpath + \"/*.sql\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, file := range sqlMigrations {\n\t\t\tv, err := NumericComponent(file)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif versionFilter(v, current, target) {\n\t\t\t\tmigration := &Migration{Version: v, Next: -1, Previous: -1, Source: file}\n\t\t\t\tmigrations = append(migrations, migration)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, migration := range c.Migrations {\n\t\tv, err := NumericComponent(migration.Source)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif versionFilter(v, current, target) {\n\t\t\tmigrations = append(migrations, migration)\n\t\t}\n\t}\n\n\tmigrations = sortAndConnectMigrations(migrations)\n\n\treturn migrations, nil\n}", "func RunMigrations(db *gorm.DB) {\n\tdb.AutoMigrate(&models.Article{})\n\tdb.AutoMigrate(&models.Page{})\n}", "func (m *Manager) RegisteredDrivers() []string {\n\tdrivers := make([]string, 0)\n\n\tfor k := range m.drivers {\n\t\tdrivers = append(drivers, k)\n\t}\n\n\treturn drivers\n}", "func (c *Config) PendingVersions(ctx context.Context) ([]string, error) {\n\tmigratedVersions, err := c.existingVersions(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to query existing versions\")\n\t}\n\n\tmigrationFiles := c.migrationFiles\n\tsort.SliceStable(migrationFiles, func(i int, j int) bool {\n\t\treturn strings.Compare(migrationFiles[i].Name(), migrationFiles[j].Name()) == -1 // in ascending order\n\t})\n\n\tresult := []string{}\n\tfor i := range migrationFiles {\n\t\tcurrFile := migrationFiles[i]\n\t\tcurrName := currFile.Name()\n\t\tif !strings.HasSuffix(currName, \".up.sql\") {\n\t\t\tcontinue // skip if this isn't a `.up.sql`\n\t\t}\n\t\tcurrVer := strings.Split(currName, \"_\")[0]\n\t\tif _, found := migratedVersions.Find(currVer); found {\n\t\t\tcontinue // skip if we've migrated this version\n\t\t}\n\t\tresult = append(result, currVer)\n\t}\n\treturn result, nil\n}", "func (c Client) Migrations() migrations.Client {\n\treturn migrations.NewClient(c...)\n}", "func (w *dbWrapper) hasMigrationsTable() (bool, error) {\n\tvar table string\n\terr := w.db.QueryRow(w.setPlaceholders(w.provider.hasTableQuery()), w.MigrationsTable).Scan(&table)\n\tif err == sql.ErrNoRows {\n\t\treturn false, nil\n\t}\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func GetFabricManagers(ctx context.Context) ([]Plugin, error) {\n\tl.LogWithFields(ctx).Debugf(\"incoming GetFabricManagers request\")\n\tconn, err := GetDBConnectionFunc(common.OnDisk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeys, err := conn.GetAllDetails(\"Fabric\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar managers []Plugin\n\tfor _, key := range keys {\n\t\tvar fabric Fabric\n\t\tfabricData, err := conn.Read(\"Fabric\", key)\n\t\tif err != nil {\n\t\t\tl.LogWithFields(ctx).Warn(\"while trying to read DB contents for \" + key + \" in Fabric table, got \" + err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tif errs := JSONUnmarshalFunc([]byte(fabricData), &fabric); errs != nil {\n\t\t\tl.LogWithFields(ctx).Warn(\"while trying to unmarshal DB contents for \" + key + \" in Fabric table, got \" + err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tmanager, err := GetPluginDataFunc(fabric.PluginID)\n\t\tif err != nil {\n\t\t\tl.LogWithFields(ctx).Warn(\"while trying to collect DB contents for \" + fabric.PluginID + \" in Plugin table, got \" + err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tmanagers = append(managers, manager)\n\n\t}\n\treturn managers, nil\n}", "func (mm *Meta) GetDownPlan() *Migrations {\n\treturn mm.getDownPlan().RemoveDuplicates()\n}", "func Migrate() {\n\tlog.Info(\"Executing migrations...\")\n\tDb.AutoMigrate(&models.Repository{}, &models.Week{}, &models.Contributor{})\n}", "func runAllMigrations(db *sql.DB) {\n\tLogInfo(\"RUNNING ALL MIGRATIONS\\n\")\n\n\tcreateMigrationsTable(db)\n\n\tfilenamePattern := fmt.Sprintf(\"./*.sql\")\n\tfiles, err := filepath.Glob(filenamePattern)\n\tif err != nil {\n\t\tLogErr(\"%s\\n\", err)\n\t}\n\n\tfor _, filePath := range files {\n\t\tfilename := filepath.Base(filePath)\n\n\t\tif checkIfMigrated(filename, db) {\n\t\t\tLogNotice(\"SKIPPING %s\\n\", filename)\n\t\t\tcontinue\n\t\t}\n\n\t\tsqlQuery, fileErr := ioutil.ReadFile(fmt.Sprintf(\"./%s\", filename))\n\t\tif fileErr != nil {\n\t\t\tLogErr(\"%s\\n\", fileErr)\n\t\t}\n\n\t\texecQuery(db, string(sqlQuery))\n\t\texecQuery(db, \"INSERT INTO _migrations (migration) VALUES($1)\", filename)\n\t\tLogSuccess(\"%s MIGRATED\\n\", filename)\n\t}\n\n}", "func GetReactionsToRegister(oldRegisteredReactions []v040posts.Reaction) (reactionsToRegister []v040posts.Reaction) {\n\tfor _, reaction := range oldRegisteredReactions {\n\t\tif _, err := emoji.LookupEmojiByCode(reaction.ShortCode); err != nil {\n\t\t\treactionsToRegister = append(reactionsToRegister, reaction)\n\t\t}\n\t}\n\treturn reactionsToRegister\n}", "func (chain foreignKeyChain) GetUpdaters() []sql.ForeignKeyEditor {\n\tupdaters := make([]sql.ForeignKeyEditor, 0, len(chain.fkUpdate))\n\tfor _, updater := range chain.fkUpdate {\n\t\tupdaters = append(updaters, updater)\n\t}\n\treturn updaters\n}", "func (m *Application) GetAddIns()([]AddInable) {\n return m.addIns\n}", "func GetMiddleware() []mux.MiddlewareFunc{\n\n\t/*\n\t\tAdd all of the middleware you want active in the app to this array\n\t*/\n\tmws := []mux.MiddlewareFunc{\n\t\tGetAccessLogMiddleware(),\n\t}\n\n\treturn mws\n}", "func (s *Subscribe) GetAdmins() []*Subscriber {\n\tvar subs []*Subscriber\n\n\tfor _, sub := range s.Subscribers {\n\t\tif sub.Admin {\n\t\t\tsubs = append(subs, sub)\n\t\t}\n\t}\n\n\treturn subs\n}", "func (backend *Backend) DevicesRegistered() map[string]device.Interface {\n\treturn backend.devices\n}", "func (r *registry) RegisteredModels() []KnownModel {\n\tvar models []KnownModel\n\tfor _, model := range r.modelsByProtoName {\n\t\tmodels = append(models, model)\n\t}\n\treturn models\n}", "func (m *UserTeamwork) GetInstalledApps()([]UserScopeTeamsAppInstallationable) {\n val, err := m.GetBackingStore().Get(\"installedApps\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]UserScopeTeamsAppInstallationable)\n }\n return nil\n}", "func (s *storageVersionMigrationLister) List(selector labels.Selector) (ret []*v1alpha1.StorageVersionMigration, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.StorageVersionMigration))\n\t})\n\treturn ret, err\n}", "func (s *SegmentChangesWrapper) RegisteredSegmentNames() ([]string, error) {\n\tsegments, err := s.segmentCollection.FetchAll()\n\tif err != nil {\n\t\tlog.Error.Println(\"Error fetching segments from boldb\", err)\n\t\treturn nil, err\n\t}\n\n\ttoReturn := make([]string, 0)\n\tfor _, segment := range segments {\n\t\ttoReturn = append(toReturn, segment.Name)\n\t}\n\n\treturn toReturn, nil\n}", "func ApplyAll() error {\n\terr := assertMigrationTable()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmigrations, err := all()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tordered := SortMigrations(migrations, \"asc\")\n\n\tfor _, m := range ordered {\n\t\terr = m.Apply()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Sync(c *SQLConnection) (done []string, err error) {\n\tcount, err := migrate.ExecMax(c.db, c.dialect, c.source, migrate.Up, 0)\n\tif err != nil {\n\t\treturn\n\t}\n\tif count == 0 {\n\t\treturn\n\t}\n\n\trecords, err := migrate.GetMigrationRecords(c.db, c.dialect)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor i := len(records) - count; i < len(records); i++ {\n\t\tdone = append(done, records[i].Id)\n\t}\n\treturn\n}", "func (m *Migrator) filter(current int64, direction MigrationDirection) []*Migration {\n\tvar index = -1\n\tif current > 0 {\n\t\tfor index < len(m.migrations)-1 {\n\t\t\tindex++\n\t\t\tif m.migrations[index].Id == current {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif direction == Up {\n\t\treturn m.migrations[index+1:]\n\t}\n\n\tif index == -1 {\n\t\treturn []*Migration{}\n\t}\n\n\t// Add in reverse order\n\ttoApply := make([]*Migration, index+1)\n\tfor i := 0; i < index+1; i++ {\n\t\ttoApply[index-i] = m.migrations[i]\n\t}\n\treturn toApply\n}", "func (db *DB) InstalledExtensions() ([]Extension, error) {\n\tstatement := \"SELECT name, default_version, installed_version \" +\n\t\t\" FROM pg_available_extensions WHERE installed_version IS NOT NULL\"\n\n\trows, err := db.Query(statement)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\textensions := []Extension{}\n\tfor rows.Next() {\n\t\tvar name, defaultVersion, installedVersion sql.NullString\n\t\tif err := rows.Scan(&name, &defaultVersion, &installedVersion); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tx := Extension{\n\t\t\tName: name.String,\n\t\t\tDefaultVersion: defaultVersion.String,\n\t\t\tInstalledVersion: installedVersion.String,\n\t\t}\n\t\textensions = append(extensions, x)\n\t}\n\treturn extensions, nil\n}", "func RegisterLegacyMigrater(eventName string, migrationHandler func(t time.Time, data string) error) {\n\tregisteredMigraters[eventName] = migrationHandler\n\n\tlogrus.Debug(\"[scheduledEvents2] Registered migration handler for \", eventName)\n}", "func (o *StorageHitachiVolumeMigrationPair) GetRegisteredDevice() AssetDeviceRegistrationRelationship {\n\tif o == nil || o.RegisteredDevice == nil {\n\t\tvar ret AssetDeviceRegistrationRelationship\n\t\treturn ret\n\t}\n\treturn *o.RegisteredDevice\n}", "func RunOrderedMigrations(app *App, ctx sdk.Context, migrationOrder []moduleUpgradeVersion) (module.VersionMap, error) {\n\tctx.Logger().Info(fmt.Sprintf(\"Starting all module migrations in order: %v\", migrationOrder))\n\tupdatedVersionMap := make(module.VersionMap)\n\tfor _, moduleAndVersion := range migrationOrder {\n\t\tpartialVersionMap := make(module.VersionMap)\n\t\tpartialVersionMap[moduleAndVersion.ModuleName] = moduleAndVersion.FromVersion\n\t\tctx.Logger().Info(fmt.Sprintf(\"Run migration on module %v from starting version %v\", moduleAndVersion.ModuleName, partialVersionMap[moduleAndVersion.ModuleName]))\n\t\tmm := make(map[string]module.AppModule)\n\t\tmm[moduleAndVersion.ModuleName] = app.mm.Modules[moduleAndVersion.ModuleName]\n\t\t// create a special filtered module manager so we can control the library internal initialization process\n\t\t// that uses a non-deterministic map. The following still has a map but with only one element at a time.\n\t\tmgr := module.Manager{\n\t\t\tModules: mm,\n\t\t\tOrderBeginBlockers: app.mm.OrderBeginBlockers,\n\t\t\tOrderEndBlockers: app.mm.OrderEndBlockers,\n\t\t\tOrderExportGenesis: app.mm.OrderExportGenesis,\n\t\t\tOrderInitGenesis: app.mm.OrderInitGenesis,\n\t\t}\n\t\tmigratedVersionMap, err := mgr.RunMigrations(ctx, app.configurator, partialVersionMap)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tupdatedVersionMap[moduleAndVersion.ModuleName] = migratedVersionMap[moduleAndVersion.ModuleName]\n\t}\n\tctx.Logger().Info(fmt.Sprintf(\"Finished running all module migrations. Final versions: %v\", updatedVersionMap))\n\treturn updatedVersionMap, nil\n}", "func TestInitSchemaExistingMigrations(t *testing.T) {\n\tforEachDatabase(t, func(db *sqlx.DB) {\n\t\tm := New(db, DefaultOptions, migrations)\n\n\t\t// Migrate without initialisation\n\t\tassert.NoError(t, m.Migrate())\n\n\t\t// Then migrate again, this time with a non empty initialisation\n\t\t// This initialisation should not happen!\n\t\tm.InitSchema(func(tx *sqlx.DB) error {\n\t\t\tq := `CREATE TABLE \"cars\" (\"id\" serial,\"created_at\" timestamp with time zone,\"updated_at\" timestamp with time zone,\"deleted_at\" timestamp with time zone,\"name\" text , PRIMARY KEY (\"id\"))`\n\t\t\t_, err := tx.Exec(q)\n\t\t\treturn err\n\t\t})\n\t\tassert.NoError(t, m.Migrate())\n\n\t\tassert.False(t, m.hasTable(\"cars\"))\n\t\tassert.Equal(t, 2, tableCount(t, db, \"migrations\"))\n\t})\n}", "func (r *AccountDIDRegistry) GetAdmins() []DID {\n\treturn r.Admins\n}", "func (m *ManagementTemplateStep) GetVersions()([]ManagementTemplateStepVersionable) {\n val, err := m.GetBackingStore().Get(\"versions\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]ManagementTemplateStepVersionable)\n }\n return nil\n}", "func (s *SchemaEditor) IsAppliedMigration(migration Migrationer, plugin Pluginer) (result bool, err error) {\n\tqb := utils.QueryBuilder().\n\t\tSelect(\"COUNT(*)\").\n\t\tFrom(MIGRATIONS_DB_TABLE).\n\t\tWhere(\"id=? AND plugin_id=?\", migration.ID(), plugin.ID())\n\n\t// prepare variables\n\tvar args []interface{}\n\tvar count int\n\tvar query string\n\n\tquery, args, err = qb.ToSql()\n\tif err = s.context.DB.QueryRowx(query, args...).Scan(&count); err != nil {\n\t\tresult = false\n\t} else {\n\t\tresult = count > 0\n\t}\n\treturn\n}", "func (dm *DMMasterClient) GetRegisteredMembers() ([]string, []string, error) {\n\tquery := \"?master=true&worker=true\"\n\tendpoints := dm.getEndpoints(dmMembersURI + query)\n\tmemberResp, err := dm.getMember(endpoints)\n\n\tvar (\n\t\tregisteredMasters []string\n\t\tregisteredWorkers []string\n\t)\n\n\tif err != nil {\n\t\tzap.L().Error(\"get dm master status failed\", zap.Error(err))\n\t\treturn registeredMasters, registeredWorkers, err\n\t}\n\n\tfor _, member := range memberResp.Members {\n\t\tif masters := member.GetMaster(); masters != nil {\n\t\t\tfor _, master := range masters.GetMasters() {\n\t\t\t\tregisteredMasters = append(registeredMasters, master.Name)\n\t\t\t}\n\t\t} else if workers := member.GetWorker(); workers != nil {\n\t\t\tfor _, worker := range workers.GetWorkers() {\n\t\t\t\tregisteredWorkers = append(registeredWorkers, worker.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn registeredMasters, registeredWorkers, nil\n}", "func (w *WorkflowTypeMigrator) Migrate() {\n\tfor _, dd := range w.DeprecatedWorkflowTypes {\n\t\tif w.isDeprecated(dd.Domain, dd.WorkflowType.Name, dd.WorkflowType.Version) {\n\t\t\tLog.Printf(\"action=migrate at=deprecate-workflow domain=%s workflow=%s version=%s status=previously-deprecated\", LS(dd.Domain), LS(dd.WorkflowType.Name), LS(dd.WorkflowType.Version))\n\t\t} else {\n\t\t\tw.deprecate(dd)\n\t\t\tLog.Printf(\"action=migrate at=deprecate-workflow domain=%s workflow=%s version=%s status=deprecate\", LS(dd.Domain), LS(dd.WorkflowType.Name), LS(dd.WorkflowType.Version))\n\t\t}\n\t}\n\tfor _, r := range w.RegisteredWorkflowTypes {\n\t\tif w.isRegisteredNotDeprecated(r) {\n\t\t\tLog.Printf(\"action=migrate at=register-workflow domain=%s workflow=%s version=%s status=previously-registered\", LS(r.Domain), LS(r.Name), LS(r.Version))\n\t\t} else {\n\t\t\tw.register(r)\n\t\t\tLog.Printf(\"action=migrate at=register-workflow domain=%s workflow=%s version=%s status=registered\", LS(r.Domain), LS(r.Name), LS(r.Version))\n\t\t}\n\t}\n}" ]
[ "0.59993494", "0.5917453", "0.5908439", "0.5828041", "0.56374675", "0.55805904", "0.5571452", "0.55068016", "0.5480716", "0.5442322", "0.54304135", "0.5336703", "0.533496", "0.5296084", "0.52461225", "0.5194173", "0.5160693", "0.51398253", "0.50593525", "0.49677986", "0.48873454", "0.48780444", "0.48538297", "0.48525122", "0.48496976", "0.48244476", "0.4820802", "0.47652262", "0.4760063", "0.47277007", "0.4718366", "0.46471155", "0.46328506", "0.46037924", "0.4549356", "0.45348892", "0.4524821", "0.45225462", "0.45221105", "0.45218152", "0.4502386", "0.45023558", "0.44895878", "0.44833872", "0.44822255", "0.44706428", "0.44651872", "0.44434738", "0.4443231", "0.44410935", "0.44360957", "0.4430734", "0.43373114", "0.42915526", "0.42789793", "0.42726037", "0.42691734", "0.42645115", "0.4242068", "0.42346755", "0.42311892", "0.4218628", "0.42092746", "0.41983178", "0.41512206", "0.41417617", "0.41375232", "0.4133954", "0.41308057", "0.4111775", "0.41031", "0.40942517", "0.4080817", "0.40733185", "0.40683225", "0.4067731", "0.4047216", "0.4046383", "0.40402517", "0.40290543", "0.40245983", "0.40226746", "0.4021536", "0.4019916", "0.40174714", "0.39864126", "0.3985785", "0.39764112", "0.39762166", "0.39596593", "0.3956507", "0.39379898", "0.39318618", "0.39278668", "0.392691", "0.3920873", "0.3915026", "0.391281", "0.39115787", "0.38986352" ]
0.7982301
0
Run runs command on the db. Supported commands are: up [target] runs all available migrations by default or up to target one if argument is provided. down reverts last migration. reset reverts all migrations. version prints current db version. set_version sets db version without running migrations.
func Run(db DB, a ...string) (oldVersion, newVersion int64, err error) { return DefaultCollection.Run(db, a...) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Migrate) Run(args []string) (exitCode int) {\n\tvar how bool\n\tctx := base.GetMigrationContext()\n\tcmdFlags := flag.NewFlagSet(\"migrate\", flag.ContinueOnError)\n\tcmdFlags.StringVar(&ctx.InspectorConnectionConfig.Key.Hostname, \"host\", \"127.0.0.1\", \"\")\n\tcmdFlags.IntVar(&ctx.InspectorConnectionConfig.Key.Port, \"port\", 3306, \"\")\n\tcmdFlags.StringVar(&ctx.DatabaseName, \"db\", \"\", \"\")\n\tcmdFlags.StringVar(&ctx.OriginalTableName, \"table\", \"\", \"\")\n\tcmdFlags.StringVar(&ctx.AlterStatement, \"alter\", \"\", \"\")\n\tcmdFlags.BoolVar(&how, \"how\", false, \"\")\n\tcmdFlags.BoolVar(&ctx.Noop, \"dryrun\", false, \"\")\n\tcmdFlags.StringVar(&ctx.CliUser, \"user\", \"root\", \"\")\n\tcmdFlags.StringVar(&ctx.CliPassword, \"pass\", \"\", \"\")\n\tcmdFlags.Usage = func() { this.Ui.Output(this.Help()) }\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tif how {\n\t\tthis.printHowItWorks()\n\t\treturn\n\t}\n\n\tctx.AllowedRunningOnMaster = true\n\tctx.OkToDropTable = true\n\tctx.InitiallyDropOldTable = true\n\tctx.InitiallyDropGhostTable = true\n\tctx.ServeSocketFile = \"/tmp/dbc.migrate.sock\"\n\tctx.SetChunkSize(1000)\n\tctx.SetDMLBatchSize(100)\n\tctx.SetDefaultNumRetries(3)\n\tctx.ApplyCredentials()\n\n\tlog.SetLevel(log.DEBUG)\n\n\tlog.Infof(\"starting\")\n\n\t// a migrator contains a sql parser(parsing alter statement), an inspector, applier and binlog streamer.\n\t// migrator.onChangelogStateEvent\n\t// migrator.onApplyEventStruct\n\t// 1. change log table\n\t// 2. ghost table\n\t// 3. alter ghost table\n\tmigrator := logic.NewMigrator()\n\tif err := migrator.Migrate(); err != nil {\n\t\tmigrator.ExecOnFailureHook()\n\t\tlog.Fatale(err)\n\t}\n\tlog.Infof(\"OK %d rows copied, %s, %s\", ctx.GetTotalRowsCopied(), ctx.ElapsedRowCopyTime(), ctx.ElapsedTime())\n\n\treturn\n}", "func RunMigrations(command *string) {\n\tswitch *command {\n\tcase \"new\":\n\t\tmigrateNew()\n\t\tos.Exit(0)\n\tcase \"up\":\n\t\tmigrateUp(models.GetDB(), 0)\n\t\tos.Exit(0)\n\tcase \"down\":\n\t\tmigrateDown(models.GetDB(), 1)\n\t\tos.Exit(0)\n\tcase \"redo\":\n\t\tmigrateDown(models.GetDB(), 1)\n\t\tmigrateUp(models.GetDB(), 1)\n\t\tos.Exit(0)\n\tcase \"skip\":\n\tdefault:\n\t\tlog.Fatalf(\"Wrong migration flag %q, acceptable values: up, down\\n\", *command)\n\t}\n}", "func RunMigrations(db DB, migrations []Migration, a ...string) (oldVersion, newVersion int64, err error) {\n\tsortMigrations(migrations)\n\n\tvar cmd string\n\tif len(a) > 0 {\n\t\tcmd = a[0]\n\t}\n\n\terr = createTables(db)\n\tif err != nil {\n\t\treturn\n\t}\n\n\toldVersion, err = Version(db)\n\tif err != nil {\n\t\treturn\n\t}\n\tnewVersion = oldVersion\n\n\tswitch cmd {\n\tcase \"create\":\n\t\tif len(a) < 2 {\n\t\t\tfmt.Println(\"Please enter migration description\")\n\t\t\treturn\n\t\t}\n\n\t\tvar version int64\n\t\tif len(migrations) > 0 {\n\t\t\tversion = migrations[len(migrations)-1].Version\n\t\t}\n\n\t\tfilename := fmtMigrationFilename(version+1, strings.Join(a[1:], \"_\"))\n\t\terr = createMigrationFile(filename)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tfmt.Println(\"created migration\", filename)\n\t\treturn\n\tcase \"version\":\n\t\treturn\n\tcase \"up\", \"\":\n\t\tfor i := range migrations {\n\t\t\tm := &migrations[i]\n\t\t\tif m.Version <= oldVersion {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = m.Up(db)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnewVersion = m.Version\n\t\t\terr = SetVersion(db, newVersion)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\treturn\n\tcase \"down\":\n\t\tnewVersion, err = down(db, migrations, oldVersion)\n\t\treturn\n\tcase \"reset\":\n\t\tversion := oldVersion\n\t\tfor {\n\t\t\tnewVersion, err = down(db, migrations, version)\n\t\t\tif err != nil || newVersion == version {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tversion = newVersion\n\t\t}\n\tcase \"set_version\":\n\t\tif len(a) < 2 {\n\t\t\terr = fmt.Errorf(\"set_version requires version as 2nd arg, e.g. set_version 42\")\n\t\t\treturn\n\t\t}\n\n\t\tnewVersion, err = strconv.ParseInt(a[1], 10, 64)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = SetVersion(db, newVersion)\n\t\treturn\n\tdefault:\n\t\terr = fmt.Errorf(\"unsupported command: %q\", cmd)\n\t\treturn\n\t}\n}", "func Run(db DB, a ...string) (oldVersion, newVersion int64, err error) {\n\t// Make a copy so there are no side effects of sorting.\n\tmigrations := make([]Migration, len(allMigrations))\n\tcopy(migrations, allMigrations)\n\treturn RunMigrations(db, migrations, a...)\n}", "func Run(db pgmigrations.DB, a ...string) (oldVersion, newVersion int64, err error) {\n\treturn pgmigrations.Run(db, a...)\n}", "func (component *Database) MigrateDown() {\n\tlastVersion := component.MigrateLastVersion()\n\tm, has := component.config.MigrationDict[lastVersion]\n\tif !has {\n\t\tif lastVersion == \"\" {\n\t\t\tfmt.Println(\"no version can be down.\")\n\t\t} else {\n\t\t\tfmt.Println(\"not found \" + lastVersion + \"' struct\")\n\t\t}\n\t\treturn\n\t}\n\tfmt.Print(\"Do you want to down this version: \" + lastVersion + \" ?[Y/N]:\")\n\tinput := bufio.NewScanner(os.Stdin)\n\tif !input.Scan() {\n\t\treturn\n\t}\n\tstr := strings.ToLower(input.Text())\n\tif str != \"y\" {\n\t\treturn\n\t}\n\n\tm.Down()\n\tsqlList := m.GetSqlList()\n\n\tvar err error\n\tsession := component.NewSession()\n\terr = session.Begin()\n\tutils.Error.Panic(err)\n\tdefer func() {\n\t\tif rec := recover(); rec != nil {\n\t\t\t_ = session.Rollback()\n\t\t} else {\n\t\t\t_ = session.Commit()\n\t\t}\n\t}()\n\n\tfor _, sqlStr := range sqlList {\n\t\t_, err = session.Exec(sqlStr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t_, err = session.ID(lastVersion).Delete(tables.Migration{})\n\tutils.Error.Panic(err)\n\n\tfmt.Println(\"\\tdone.\")\n}", "func (m *Migrator) Down(ctx context.Context, step int) error {\n\tspan, ctx := m.startSpan(ctx, MigrationDownOpName)\n\tdefer span.End()\n\n\tc := m.Connection.WithContext(ctx)\n\treturn m.exec(ctx, func() error {\n\t\tmtn := m.sanitizedMigrationTableName(c)\n\t\tcount, err := c.Count(mtn)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"migration down: unable count existing migration\")\n\t\t}\n\t\tmfs := m.Migrations[\"down\"].SortAndFilter(c.Dialect.Name(), sort.Reverse)\n\t\t// skip all ran migration\n\t\tif len(mfs) > count {\n\t\t\tmfs = mfs[len(mfs)-count:]\n\t\t}\n\t\t// run only required steps\n\t\tif step > 0 && len(mfs) >= step {\n\t\t\tmfs = mfs[:step]\n\t\t}\n\t\tfor _, mi := range mfs {\n\t\t\texists, err := c.Where(\"version = ?\", mi.Version).Exists(mtn)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"problem checking for migration version %s\", mi.Version)\n\t\t\t}\n\n\t\t\tif !exists && len(mi.Version) > 14 {\n\t\t\t\tlegacyVersion := mi.Version[:14]\n\t\t\t\tlegacyVersionExists, err := c.Where(\"version = ?\", legacyVersion).Exists(mtn)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"problem checking for migration version %s\", mi.Version)\n\t\t\t\t}\n\n\t\t\t\tif !legacyVersionExists {\n\t\t\t\t\treturn errors.Wrapf(err, \"problem checking for migration version %s\", legacyVersion)\n\t\t\t\t}\n\t\t\t} else if !exists {\n\t\t\t\treturn errors.Errorf(\"migration version %s does not exist\", mi.Version)\n\t\t\t}\n\n\t\t\tif err := mi.Valid(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif mi.Runner != nil {\n\t\t\t\terr := m.isolatedTransaction(ctx, \"down\", func(conn *pop.Connection) error {\n\t\t\t\t\terr := mi.Runner(mi, conn, conn.TX)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\n\t\t\t\t\t// #nosec G201 - mtn is a system-wide const\n\t\t\t\t\tif err := conn.RawQuery(fmt.Sprintf(\"DELETE FROM %s WHERE version = ?\", mtn), mi.Version).Exec(); err != nil {\n\t\t\t\t\t\treturn errors.Wrapf(err, \"problem deleting migration version %s\", mi.Version)\n\t\t\t\t\t}\n\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr := mi.RunnerNoTx(mi, c)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// #nosec G201 - mtn is a system-wide const\n\t\t\t\tif err := c.RawQuery(fmt.Sprintf(\"DELETE FROM %s WHERE version = ?\", mtn), mi.Version).Exec(); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"problem deleting migration version %s. YOUR DATABASE MAY BE IN AN INCONSISTENT STATE! MANUAL INTERVENTION REQUIRED!\", mi.Version)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm.l.Debugf(\"< %s\", mi.Name)\n\t\t}\n\t\treturn nil\n\t})\n}", "func (c *generateMigrationCommand) Run(args []string) error {\n\tif len(args) < 1 || args[0] == \"\" {\n\t\treturn fmt.Errorf(\"no NAME given\")\n\t}\n\tname := args[0]\n\tif c.option.ORM == \"\" {\n\t\tc.option.ORM = defaultORM\n\t}\n\torm, exists := ORM[c.option.ORM]\n\tif !exists {\n\t\treturn fmt.Errorf(\"unsupported ORM: `%v'\", c.option.ORM)\n\t}\n\tnow := _time.Now().Format(\"20060102150405\")\n\tdata := map[string]interface{}{\n\t\t\"Name\": util.ToCamelCase(name),\n\t\t\"TimeStamp\": now,\n\t\t\"ImportPath\": orm.ImportPath(),\n\t\t\"TxType\": reflect.TypeOf(orm.TransactionType()).String(),\n\t}\n\tif err := util.CopyTemplate(\n\t\tfilepath.Join(skeletonDir(\"migration\"), \"migration.go\"+util.TemplateSuffix),\n\t\tfilepath.Join(\"db\", \"migration\", fmt.Sprintf(\"%v_%v.go\", now, util.ToSnakeCase(name))),\n\t\tdata,\n\t); err != nil {\n\t\treturn err\n\t}\n\tinitPath := filepath.Join(\"db\", \"migration\", \"init.go\")\n\tif _, err := os.Stat(initPath); os.IsNotExist(err) {\n\t\tappDir, err := util.FindAppDir()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := util.CopyTemplate(\n\t\t\tfilepath.Join(skeletonDir(\"migration\"), \"init.go\"+util.TemplateSuffix),\n\t\t\tinitPath, map[string]interface{}{\n\t\t\t\t\"typeName\": c.option.ORM,\n\t\t\t\t\"tx\": strings.TrimSpace(util.GoString(orm)),\n\t\t\t\t\"dbImportPath\": path.Join(appDir, \"db\"),\n\t\t\t},\n\t\t); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func RunMigrations(db *pg.DB) {\n\tversion, err := migrations.Version(db)\n\n\tif err != nil {\n\t\t_, _, err := migrations.Run(db, \"init\")\n\t\tlogger.Info(\"[MIGRATION] Migration table created\")\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tlogger.Info(\"[MIGRATION] Current version: \", version)\n\t_, newVersion, err := migrations.Run(db, \"up\")\n\n\tif err != nil {\n\t\tlogger.Info(\"An error happend during migration\")\n\t\tpanic(err)\n\t}\n\n\tif newVersion != version {\n\t\tlogger.Info(\"[MIGRATION] Migrated from version %d to %d\\n\", version, newVersion)\n\t} else {\n\t\tlogger.Info(\"[MIGRATION] Up to date\")\n\t}\n}", "func (s Sequence) MigrateDown(version int64) error {\n\tif s.cfg.Active && s.db != nil {\n\t\tif version == 0 {\n\t\t\tif err := goose.Down(s.db, s.cfg.Dir); err != nil {\n\t\t\t\treturn fmt.Errorf(errApplyMigration, err)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\n\t\tif err := goose.DownTo(s.db, s.cfg.Dir, version); err != nil {\n\t\t\treturn fmt.Errorf(errApplyMigration, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func Migrate(x *xorm.Engine) error {\n\tif err := x.Sync2(new(Version)); err != nil {\n\t\treturn fmt.Errorf(\"sync: %v\", err)\n\t}\n\n\tcurrentVersion := &Version{ID: 1}\n\thas, err := x.Get(currentVersion)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get: %v\", err)\n\t} else if !has {\n\t\t// If the version record does not exist we think\n\t\t// it is a fresh installation and we can skip all migrations.\n\t\tcurrentVersion.ID = 0\n\t\tcurrentVersion.Version = int64(_MIN_DB_VER + len(migrations))\n\n\t\tif _, err = x.InsertOne(currentVersion); err != nil {\n\t\t\treturn fmt.Errorf(\"insert: %v\", err)\n\t\t}\n\t}\n\n\tv := currentVersion.Version\n\tif _MIN_DB_VER > v {\n\t\tlog.Print(`\nQmoon can not auto-migration from your previously installed version.\n`)\n\t\treturn nil\n\t}\n\n\tif int(v-_MIN_DB_VER) > len(migrations) {\n\t\tcurrentVersion.Version = int64(len(migrations) + _MIN_DB_VER)\n\t\t_, err = x.ID(1).Update(currentVersion)\n\t\treturn err\n\t}\n\tfor i, m := range migrations[v-_MIN_DB_VER:] {\n\t\tif err = m.Migrate(x); err != nil {\n\t\t\treturn fmt.Errorf(\"do migrate: %v\", err)\n\t\t}\n\t\tcurrentVersion.Version = v + int64(i) + 1\n\t\tif _, err = x.ID(1).Update(currentVersion); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Migrate(cfg *config.Config, logger log.Logger, command string) error {\n\tdb, err := sql.Open(\"mysql\", cfg.DB.Dsn)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\tpath, err := os.Getwd()\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\n\tmigrationPath := fmt.Sprintf(\"file://%s/migration\", path)\n\tlogger.Infof(\"migrationPath : %s\", migrationPath)\n\n\tdriver, err := mysql.WithInstance(db, &mysql.Config{})\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\tm, err := migrater.NewWithDatabaseInstance(\n\t\tmigrationPath,\n\t\t\"mysql\",\n\t\tdriver,\n\t)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\tif command == \"up\" {\n\t\tlogger.Info(\"Migrate up\")\n\t\tif err := m.Up(); err != nil && err != migrater.ErrNoChange {\n\t\t\tlogger.Errorf(\"An error occurred while syncing the database.. %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif command == \"down\" {\n\t\tlogger.Info(\"Migrate down\")\n\t\tif err := m.Down(); err != nil && err != migrater.ErrNoChange {\n\t\t\tlogger.Errorf(\"An error occurred while syncing the database.. %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\n\tlogger.Info(\"Migrate complete\")\n\treturn nil\n}", "func runMigrate() {\n\tif err := opts.validateAndDefault(); err != nil {\n\t\tklog.Fatalf(\"%v\", err)\n\t}\n\tcopyBinaries()\n\n\ttarget := &EtcdVersionPair{\n\t\tversion: MustParseEtcdVersion(opts.targetVersion),\n\t\tstorageVersion: MustParseEtcdStorageVersion(opts.targetStorage),\n\t}\n\n\tmigrate(\n\t\topts.name, opts.port, opts.peerListenUrls, opts.peerAdvertiseUrls, opts.clientListenUrls,\n\t\topts.binDir, opts.dataDir, opts.etcdDataPrefix, opts.ttlKeysDirectory, opts.initialCluster,\n\t\ttarget, opts.supportedVersions, opts.etcdServerArgs)\n}", "func (s Sequence) MigrateDown(version int64) error {\n\tif s.cfg.Active && s.db != nil {\n\t\tif version == 0 {\n\t\t\treturn goose.Down(s.db, s.cfg.Dir)\n\t\t}\n\n\t\treturn goose.DownTo(s.db, s.cfg.Dir, version)\n\t}\n\n\treturn nil\n}", "func (mu *Command) RunDown() error {\n\tpop.SetLogger(mu.Log)\n\tconn := pop.Connections[mu.connectionName]\n\tif conn == nil {\n\t\treturn ErrCouldNotFindConnection\n\t}\n\n\tmig, err := pop.NewMigrationBox(mu.migrations, conn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif mu.steps == 0 {\n\t\tmu.steps = 1\n\t}\n\n\treturn mig.Down(mu.steps)\n}", "func (c *Config) MigrateDown(ctx context.Context, txOpts *sql.TxOptions, logFilename func(string), downStep int) error {\n\tmigratedVersions, err := c.existingVersions(ctx)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"unable to query existing versions\")\n\t}\n\n\ttx, err := c.adapter.BeginTx(ctx, c.db, txOpts)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"unable to create transaction\")\n\t}\n\tdefer tx.Rollback() // ok to fail rollback if we did `tx.Commit`\n\n\tmigrationFiles := c.migrationFiles\n\tsort.SliceStable(migrationFiles, func(i int, j int) bool {\n\t\treturn strings.Compare(migrationFiles[i].Name(), migrationFiles[j].Name()) == 1 // descending order\n\t})\n\n\tcounted := 0\n\tfor i := range migrationFiles {\n\t\tcurrFile := migrationFiles[i]\n\t\tcurrName := currFile.Name()\n\t\tif !strings.HasSuffix(currName, \".down.sql\") {\n\t\t\tcontinue // skip if this isn't a `.down.sql`\n\t\t}\n\t\tcurrVer := strings.Split(currName, \"_\")[0]\n\t\tif _, found := migratedVersions.Find(currVer); !found {\n\t\t\tcontinue // skip if we've NOT migrated this version\n\t\t}\n\t\tcounted++\n\t\tif counted > downStep {\n\t\t\tbreak // time to stop\n\t\t}\n\n\t\t// read the file, run the sql and delete row from `dbmigrate_versions`\n\t\tfilecontent, err := c.fileContent(currName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, currName)\n\t\t}\n\n\t\tif len(bytes.TrimSpace(filecontent)) == 0 {\n\t\t\t// treat empty file as success; don't run it\n\t\t} else if _, err := tx.ExecContext(ctx, string(filecontent)); err != nil {\n\t\t\treturn errors.Wrapf(err, currName)\n\t\t}\n\t\tif _, err := tx.ExecContext(ctx, c.adapter.DeleteOldVersion, currVer); err != nil {\n\t\t\treturn errors.Wrapf(err, \"fail to unregister version %q\", currVer)\n\t\t}\n\t\tlogFilename(currName)\n\t}\n\treturn tx.Commit()\n}", "func runGoMigration(conf *DBConf, path string, version int64, direction int) error {\n\n\t// everything gets written to a temp dir, and zapped afterwards\n\td, e := ioutil.TempDir(\"\", \"goose\")\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n\tdefer os.RemoveAll(d)\n\n\tdirectionStr := \"Down\"\n\tif direction == 1 {\n\t\tdirectionStr = \"Up\"\n\t}\n\n\ttd := &TemplateData{\n\t\tVersion: version,\n\t\tDBDriver: conf.Driver,\n\t\tDBOpen: conf.OpenStr,\n\t\tDirection: direction,\n\t\tFunc: fmt.Sprintf(\"%v_%v\", directionStr, version),\n\t}\n\tmain, e := writeTemplateToFile(filepath.Join(d, \"goose_main.go\"), goMigrationTmpl, td)\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n\n\toutpath := filepath.Join(d, filepath.Base(path))\n\tif _, e = copyFile(outpath, path); e != nil {\n\t\tlog.Fatal(e)\n\t}\n\n\tcmd := exec.Command(\"go\", \"run\", main, outpath)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif e = cmd.Run(); e != nil {\n\t\tlog.Fatal(\"`go run` failed: \", e)\n\t}\n\n\treturn nil\n}", "func (m *Migrate) Down(n int) error {\n\tcurrentVersion, _, err := m.Version()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n <= 0 || n > len(m.migrations) {\n\t\tn = len(m.migrations)\n\t}\n\tmigrationSort(m.migrations)\n\n\tfor i, p := len(m.migrations)-1, 0; i >= 0 && p < n; i-- {\n\t\tmigration := m.migrations[i]\n\t\tif migration.Version > currentVersion || migration.Down == nil {\n\t\t\tcontinue\n\t\t}\n\t\tp++\n\t\tif err := migration.Down(m.db); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar prevMigration Migration\n\t\tif i == 0 {\n\t\t\tprevMigration = Migration{Version: 0}\n\t\t} else {\n\t\t\tprevMigration = m.migrations[i-1]\n\t\t}\n\t\tif err := m.SetVersion(prevMigration.Version, prevMigration.Description); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func RunMigrations(db *gorm.DB) {\n\tdb.AutoMigrate(&Todo{})\n\n\tfmt.Println(\"AutoMigrations completed.\")\n}", "func runFirstMigration() error {\n\tsourceDriver, sourceDriverErr := source.Open(\"file:\" + dbMigrationsDir)\n\tif sourceDriverErr != nil {\n\t\treturn fmt.Errorf(\"opening the migration source driver: \" + sourceDriverErr.Error())\n\t}\n\tdbDriver, dbDriverErr := database.Open(connectionString)\n\tif dbDriverErr != nil {\n\t\treturn fmt.Errorf(\"opening the dbdriver: \" + dbDriverErr.Error())\n\t}\n\tfirstMigration, firstMigrationName, migrationReadErr := sourceDriver.ReadUp(firstMigrationTimestamp)\n\tif migrationReadErr != nil {\n\t\treturn fmt.Errorf(\"reading migration %s: %w\", firstMigrationName, migrationReadErr)\n\t}\n\tif setDirtyVersionErr := dbDriver.SetVersion(int(firstMigrationTimestamp), true); setDirtyVersionErr != nil {\n\t\treturn fmt.Errorf(\"setting the dirty version: %w\", setDirtyVersionErr)\n\t}\n\tif migrateErr := dbDriver.Run(firstMigration); migrateErr != nil {\n\t\treturn fmt.Errorf(\"running the migration: %w\", migrateErr)\n\t}\n\tif setVersionErr := dbDriver.SetVersion(int(firstMigrationTimestamp), false); setVersionErr != nil {\n\t\treturn fmt.Errorf(\"setting the version after successfully running the migration: %w\", setVersionErr)\n\t}\n\treturn nil\n}", "func (m *Migrate) Up(n int) error {\n\tcurrentVersion, _, err := m.Version()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n <= 0 || n > len(m.migrations) {\n\t\tn = len(m.migrations)\n\t}\n\tmigrationSort(m.migrations)\n\n\tfor i, p := 0, 0; i < len(m.migrations) && p < n; i++ {\n\t\tmigration := m.migrations[i]\n\t\tif migration.Version <= currentVersion || migration.Up == nil {\n\t\t\tcontinue\n\t\t}\n\t\tp++\n\t\tif err := migration.Up(m.db); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := m.SetVersion(migration.Version, migration.Description); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Migrate() error {\n\n\toldVersion, newVersion, err := migrations.Run(database.DB, \"init\")\n\toldVersion, newVersion, err = migrations.Run(database.DB)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif newVersion != oldVersion {\n\t\tlog.Printf(\"migrated from version %d to %d\\n\", oldVersion, newVersion)\n\t}\n\t// else {\n\t// \tlog.Printf(\"version is %d\\n\", oldVersion)\n\t// }\n\treturn nil\n}", "func main() {\n\tvar (\n\t\terr error\n\t\tdbConn db.DB\n\t)\n\n\tfmt.Println(internal.VersionVerbose())\n\n\tutil.InitConfig()\n\n\terr = util.Retry(10, 250*time.Millisecond, func() error {\n\t\tdbConn, err = db.GetConnection()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).WithField(\"service\", \"auth\").Warning(\"Error connecting to db, retrying\")\n\t\t}\n\t\treturn err\n\t})\n\tif err != nil {\n\t\tlog.WithError(err).WithField(\"service\", \"auth\").Warning(\"Unable to connect to db, exiting\")\n\t\tos.Exit(1)\n\t}\n\n\terr = model.Migrate(dbConn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(\"Migrate succeeded\")\n}", "func Down() error {\n\tdb, err := db()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs, err := versions(db, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, v := range vs {\n\t\tfmt.Println(\"reverting\", v)\n\t\tcontents, err := ioutil.ReadFile(filepath.Join(DirName, v+\".down.sql\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = db.Exec(string(contents))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(vs) == 0 {\n\t\tfmt.Println(\"nothing to do\")\n\t}\n\n\treturn nil\n}", "func (s *Suite) Run(db *Db, up bool, maxSteps int) (int, int, error) {\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\tif l := len(s.Migrations); l == 0 {\n\t\treturn -1, 0, errors.New(\"cannot run suite, no migrations set\")\n\t}\n\terr := db.Query(s.Stmts.CreateTableSQL).Run()\n\tif err != nil {\n\t\treturn -1, 0, err\n\t}\n\tvar row struct {\n\t\tVersion int\n\t}\n\trow.Version = -1\n\terr = db.Query(s.Stmts.SelectVersionSQL).Rows(&row)\n\tif err != nil {\n\t\treturn -1, 0, err\n\t}\n\tstep := 0\n\tstepsApplied := 0\n\tcurrent := row.Version\n\tfor _, m := range s.buildList(up, row.Version) {\n\t\tif step++; maxSteps > 0 && step > maxSteps {\n\t\t\tbreak\n\t\t}\n\n\t\ttxn, err := db.DB.Begin()\n\t\tif err != nil {\n\t\t\treturn current, stepsApplied, err\n\t\t}\n\n\t\tnext := m.id\n\t\tif up {\n\t\t\t_, err = txn.Exec(m.Up)\n\t\t} else {\n\t\t\tnext--\n\t\t\t_, err = txn.Exec(m.Down)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn current, stepsApplied, err\n\t\t}\n\n\t\tif current == -1 {\n\t\t\t_, err = txn.Exec(s.Stmts.InsertVersionSQL, next)\n\t\t} else {\n\t\t\t_, err = txn.Exec(s.Stmts.UpdateVersionSQL, next, current)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn current, stepsApplied, err\n\t\t}\n\n\t\tif err := txn.Commit(); err != nil {\n\t\t\treturn current, stepsApplied, err\n\t\t}\n\t\tcurrent = next\n\t\tstepsApplied++\n\t}\n\treturn current, stepsApplied, nil\n}", "func runVersion(cmd *cmd.Cmd, args []string) error {\n\tif len(args) != 0 {\n\t\treturn errVersionArgs\n\t}\n\n\tfmt.Printf(\"Gorot %s\\n\", gorot.Version)\n\n\treturn nil\n}", "func RunMigrationsOnDb(conf *DBConf, migrationsDir string, target int64, db *sql.DB) (err error) {\n\tcurrent, err := EnsureDBVersion(conf, db)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmigrations, err := goose.CollectMigrations(migrationsDir, current, target)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(migrations) == 0 {\n\t\tfmt.Printf(\"goose: no migrations to run. current version: %d\\n\", current)\n\t\treturn nil\n\t}\n\n\tms := migrationSorter(migrations)\n\tdirection := current < target\n\tms.Sort(direction)\n\n\tfmt.Printf(\"goose: migrating db environment '%v', current version: %d, target: %d\\n\",\n\t\tconf.Env, current, target)\n\n\tfor _, m := range ms {\n\n\t\tswitch filepath.Ext(m.Source) {\n\t\tcase \".sql\":\n\t\t\terr = runSQLMigration(conf, db, m.Source, m.Version, direction)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"FAIL %w, quitting migration\", err)\n\t\t}\n\n\t\tfmt.Println(\"OK \", filepath.Base(m.Source))\n\t}\n\n\treturn nil\n}", "func Migrate(x *xorm.Engine, db *gorm.DB) error {\n\tif err := x.Sync(new(Version)); err != nil {\n\t\treturn fmt.Errorf(\"sync: %v\", err)\n\t}\n\n\tcurrentVersion := &Version{ID: 1}\n\thas, err := x.Get(currentVersion)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"get: %v\", err)\n\t} else if !has {\n\t\t// If the version record does not exist we think\n\t\t// it is a fresh installation and we can skip all migrations.\n\t\tcurrentVersion.ID = 0\n\t\tcurrentVersion.Version = int64(minDBVersion + len(migrations))\n\n\t\tif _, err = x.InsertOne(currentVersion); err != nil {\n\t\t\treturn fmt.Errorf(\"insert: %v\", err)\n\t\t}\n\t}\n\n\tv := currentVersion.Version\n\tif minDBVersion > v {\n\t\tlog.Fatal(`\nHi there, thank you for using Gogs for so long!\nHowever, Gogs has stopped supporting auto-migration from your previously installed version.\nBut the good news is, it's very easy to fix this problem!\nYou can migrate your older database using a previous release, then you can upgrade to the newest version.\n\nPlease save following instructions to somewhere and start working:\n\n- If you were using below 0.6.0 (e.g. 0.5.x), download last supported archive from following link:\n\thttps://gogs.io/gogs/releases/tag/v0.7.33\n- If you were using below 0.7.0 (e.g. 0.6.x), download last supported archive from following link:\n\thttps://gogs.io/gogs/releases/tag/v0.9.141\n- If you were using below 0.11.55 (e.g. 0.9.141), download last supported archive from following link:\n\thttps://gogs.io/gogs/releases/tag/v0.12.0\n\nOnce finished downloading:\n\n1. Extract the archive and to upgrade steps as usual.\n2. Run it once. To verify, you should see some migration traces.\n3. Once it starts web server successfully, stop it.\n4. Now it's time to put back the release archive you originally intent to upgrade.\n5. Enjoy!\n\nIn case you're stilling getting this notice, go through instructions again until it disappears.`)\n\t\treturn nil\n\t}\n\n\tif int(v-minDBVersion) > len(migrations) {\n\t\t// User downgraded Gogs.\n\t\tcurrentVersion.Version = int64(len(migrations) + minDBVersion)\n\t\t_, err = x.Id(1).Update(currentVersion)\n\t\treturn err\n\t}\n\tfor i, m := range migrations[v-minDBVersion:] {\n\t\tlog.Info(\"Migration: %s\", m.Description())\n\t\tif err = m.Migrate(db); err != nil {\n\t\t\treturn fmt.Errorf(\"do migrate: %v\", err)\n\t\t}\n\t\tcurrentVersion.Version = v + int64(i) + 1\n\t\tif _, err = x.Id(1).Update(currentVersion); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (v *VersionCommand) runVersion() error {\n\tapiClient := v.cli.Client()\n\n\tresult, err := apiClient.SystemVersion()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get system version: %v\", err)\n\t}\n\n\tv.cli.Print(result)\n\treturn nil\n}", "func (c *MigrationsCmd) Run(cmd *cobra.Command, args []string) {\n\tc.menu.Create().MountMenu().RunMenu(args)\n}", "func (c *Config) MigrateUp(ctx context.Context, txOpts *sql.TxOptions, logFilename func(string)) error {\n\tmigratedVersions, err := c.existingVersions(ctx)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"unable to query existing versions\")\n\t}\n\n\ttx, err := c.adapter.BeginTx(ctx, c.db, txOpts)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"unable to create transaction\")\n\t}\n\tdefer tx.Rollback() // ok to fail rollback if we did `tx.Commit`\n\n\tmigrationFiles := c.migrationFiles\n\tsort.SliceStable(migrationFiles, func(i int, j int) bool {\n\t\treturn strings.Compare(migrationFiles[i].Name(), migrationFiles[j].Name()) == -1 // in ascending order\n\t})\n\n\tfor i := range migrationFiles {\n\t\tcurrFile := migrationFiles[i]\n\t\tcurrName := currFile.Name()\n\t\tif !strings.HasSuffix(currName, \".up.sql\") {\n\t\t\tcontinue // skip if this isn't a `.up.sql`\n\t\t}\n\t\tcurrVer := strings.Split(currName, \"_\")[0]\n\t\tif _, found := migratedVersions.Find(currVer); found {\n\t\t\tcontinue // skip if we've migrated this version\n\t\t}\n\n\t\t// read the file, run the sql and insert a row into `dbmigrate_versions`\n\t\tfilecontent, err := c.fileContent(currName)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, currName)\n\t\t}\n\n\t\tif len(bytes.TrimSpace(filecontent)) == 0 {\n\t\t\t// treat empty file as success; don't run it\n\t\t} else if _, err := tx.ExecContext(ctx, string(filecontent)); err != nil {\n\t\t\treturn errors.Wrapf(err, currName)\n\t\t}\n\t\tif _, err := tx.ExecContext(ctx, c.adapter.InsertNewVersion, currVer); err != nil {\n\t\t\treturn errors.Wrapf(err, \"fail to register version %q\", currVer)\n\t\t}\n\t\tlogFilename(currName)\n\t}\n\treturn tx.Commit()\n}", "func (s Sequence) MigrateUp(version int64) error {\n\tif s.cfg.Active && s.db != nil {\n\t\tif version == 0 {\n\t\t\tif err := goose.Up(s.db, s.cfg.Dir); err != nil {\n\t\t\t\treturn fmt.Errorf(errApplyMigration, err)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\n\t\tif err := goose.UpTo(s.db, s.cfg.Dir, version); err != nil {\n\t\t\treturn fmt.Errorf(errApplyMigration, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m Migrator) RunMigrations() error {\n\t// Run everything in a transaction. In case of error, we can roll it back\n\ttx, err := m.Connection.Database.Begin()\n\tif err != nil {\n\t\t// Connection could not be started\n\t\treturn err\n\t}\n\n\t// First check if the database db_migrations exists\n\tres := tx.QueryRow(`SELECT EXISTS(\n\t\tSELECT *\n\t\tFROM information_schema.tables\n\t\tWHERE\n\t\t\ttable_schema = 'public' AND\n\t\t\ttable_name = 'db_migrations'\n\t)`)\n\n\tvar migTablePresent bool\n\terr = res.Scan(&migTablePresent)\n\tif err != nil {\n\t\t// result was invalid\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\talreadyRunMigrations := make(map[string]bool)\n\tif !migTablePresent {\n\t\t_, err = tx.Query(`\n\t\t\tCREATE TABLE db_migrations (version VARCHAR(50) NOT NULL, executed_at TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(version))\n\t\t`)\n\t\tif err != nil {\n\t\t\t// could not create db_migration table\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tversionRows, err := tx.Query(`\n\t\t\tSELECT version FROM db_migrations\n\t\t`)\n\t\tif err != nil {\n\t\t\t// could not fetch the list of executed migrations\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t\tfor versionRows.Next() {\n\t\t\tvar version string\n\t\t\terr = versionRows.Scan(&version)\n\t\t\tif err != nil {\n\t\t\t\t// A version number could not be parsed\n\t\t\t\ttx.Rollback()\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\talreadyRunMigrations[version] = true\n\t\t}\n\t}\n\n\tavailableMigrations, err := m.checkAvailableMigrations()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\tvar migrationsToRun []string\n\tfor version := range availableMigrations {\n\t\tif _, ok := alreadyRunMigrations[version]; !ok {\n\t\t\tmigrationsToRun = append(migrationsToRun, version)\n\t\t}\n\t}\n\tfor version := range alreadyRunMigrations {\n\t\tif _, ok := availableMigrations[version]; !ok {\n\t\t\t// Warn there is a present migration with no corresponding file\n\t\t}\n\t}\n\n\tfor _, version := range migrationsToRun {\n\t\tmigrationByteContent, err := migration.Asset(fmt.Sprintf(\"%s_up.sql\", version))\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t\tmigrationContent := string(migrationByteContent)\n\n\t\t_, err = tx.Query(migrationContent)\n\t\tif err != nil {\n\t\t\t// There was an error running the migration\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.Query(`INSERT INTO db_migrations (version) VALUES ($1)`, version)\n\t\tif err != nil {\n\t\t\t// There was an error running the migration\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttx.Commit()\n\n\treturn nil\n}", "func migrateDown(config *MigrationConfig) error {\n\tfmt.Println(\"Migrating down database ...\")\n\tdriver, errDriver := mysql.WithInstance(config.db, &mysql.Config{})\n\tif errDriver != nil {\n\t\treturn errDriver\n\t}\n\n\tmigrationDatabase, errMigrate := migrate.NewWithDatabaseInstance(\n\t\tfmt.Sprintf(\"file://%s\", config.MigrationDir),\n\t\tconfig.Dialect, driver)\n\tif errMigrate != nil {\n\t\treturn errMigrate\n\t}\n\n\terr := migrationDatabase.Down()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Migration done ...\")\n\n\t//get latest version\n\tversion, dirty, errVersion := migrationDatabase.Version()\n\tif errVersion != nil {\n\t\t//ignore error in this line. Skip the version check\n\t\treturn errVersion\n\t}\n\n\tif dirty {\n\t\tfmt.Println(\"dirty migration. Please clean up database\")\n\t}\n\n\tfmt.Printf(\"latest version is %d \\n\", version)\n\treturn nil\n}", "func RunDBMigrate() error {\n\t// Add your custom code\n\tfmt.Println(\"RunDBMigrate: not implemented yet!\")\n\treturn nil\n}", "func migrateUp(config *MigrationConfig) error {\n\tfmt.Println(\"Migrating up database ...\")\n\tdriver, errDriver := mysql.WithInstance(config.db, &mysql.Config{})\n\tif errDriver != nil {\n\t\treturn errDriver\n\t}\n\n\tmigrateDatabase, err := migrate.NewWithDatabaseInstance(\n\t\tfmt.Sprintf(\"file://%s\", config.MigrationDir),\n\t\tconfig.Dialect, driver)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = migrateDatabase.Up()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Migration done ...\")\n\n\t//get latest version\n\tversion, dirty, errVersion := migrateDatabase.Version()\n\t//ignore error in this line. Skip the version check\n\tif errVersion != nil {\n\t\treturn errVersion\n\t}\n\n\tif dirty {\n\t\tfmt.Println(\"dirty migration. Please clean up database\")\n\t}\n\n\tfmt.Printf(\"latest version is %d \\n\", version)\n\treturn nil\n}", "func (m *MigrationRunner) Up(ctx context.Context) error {\n\treturn m.perform(ctx, \"up\")\n}", "func (db *Database) RunMigrations(ctx context.Context) error {\n\tlogger := logging.FromContext(ctx)\n\tm := gormigrate.New(db.db, gormigrate.DefaultOptions, []*gormigrate.Migration{\n\t\t{\n\t\t\tID: \"00001-CreateUsers\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating users table\")\n\t\t\t\treturn tx.AutoMigrate(&User{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"users\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00002-CreateVerificationCodes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating verification codes table\")\n\t\t\t\treturn tx.AutoMigrate(&VerificationCode{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"verification_codes\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00003-CreateAuthorizedApps\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating authorized apps table\")\n\t\t\t\treturn tx.AutoMigrate(&AuthorizedApp{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"authorized_apps\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00004-CreateTokens\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating tokens table\")\n\t\t\t\treturn tx.AutoMigrate(&Token{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"tokens\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00005-CreateCleanups\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating cleanup status table\")\n\t\t\t\tif err := tx.AutoMigrate(&CleanupStatus{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// Seed database w/ cleanup record.\n\t\t\t\tif err := tx.Create(&CleanupStatus{Type: \"cleanup\", Generation: 1, NotBefore: time.Now()}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"cleanup_statuses\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00006-AddIndexes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: add users purge index\")\n\t\t\t\tif err := tx.Model(&User{}).AddIndex(\"users_purge_index\", \"disabled\", \"updated_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: add verification code purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).AddIndex(\"ver_code_purge_index\", \"expires_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: add tokens purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).AddIndex(\"token_purge_index\", \"expires_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: drop users purge index\")\n\t\t\t\tif err := tx.Model(&User{}).RemoveIndex(\"users_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: drop verification code purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).RemoveIndex(\"ver_code_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: drop tokens purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).RemoveIndex(\"token_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00007-AddSymptomOnset\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Info(\"db migrations: rename test_date to symptom_date\")\n\t\t\t\t// AutoMigrate will add missing fields.\n\t\t\t\tif err := tx.AutoMigrate(&VerificationCode{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// If not upgrading from an old version, this column will have never been created.\n\t\t\t\tif tx.NewScope(&VerificationCode{}).HasColumn(\"test_date\") {\n\t\t\t\t\tif err := tx.Model(&VerificationCode{}).DropColumn(\"test_date\").Error; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err := tx.AutoMigrate(&Token{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// If not upgrading from an old version, this column will have never been created.\n\t\t\t\tif tx.NewScope(&Token{}).HasColumn(\"test_date\") {\n\t\t\t\t\tif err := tx.Model(&Token{}).DropColumn(\"test_date\").Error; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Info(\"db migrations: rename symptom_date to test_date\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).DropColumn(\"symptom_date\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := tx.Model(&Token{}).DropColumn(\"symptom_date\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00008-AddKeyTypes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: upgrading authorized_apps table.\")\n\t\t\t\treturn tx.AutoMigrate(&AuthorizedApp{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"admin_key\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00009-AddIssuerColumns\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: adding issuer columns to issued codes\")\n\t\t\t\treturn tx.AutoMigrate(&VerificationCode{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"issuing_user\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"issuing_app\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00010-AddSMSConfig\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: adding sms_configs table\")\n\t\t\t\treturn tx.AutoMigrate(&SMSConfig{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"sms_configs\").Error\n\t\t\t},\n\t\t},\n\t})\n\n\tlogger.Infof(\"database migrations complete\")\n\n\treturn m.Migrate()\n}", "func (v *VersionCommand) Run(args []string) {\n\tapiClient := v.cli.Client()\n\n\tresult, err := apiClient.SystemVersion()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to get system version: %v\\n\", err)\n\t\treturn\n\t}\n\n\tv.cli.Print(result)\n}", "func (s Sequence) MigrateUp(version int64) error {\n\tif s.cfg.Active && s.db != nil {\n\t\tif version == 0 {\n\t\t\treturn goose.Up(s.db, s.cfg.Dir)\n\t\t}\n\n\t\treturn goose.UpTo(s.db, s.cfg.Dir, version)\n\t}\n\n\treturn nil\n}", "func (m *MigrationRunner) Down(ctx context.Context) error {\n\treturn m.perform(ctx, \"down\")\n}", "func RunMigrations(db *gorm.DB) {\n\tdb.Set(\"gorm:table_options\", \"ENGINE=InnoDB\")\n\tdb.Set(\"gorm:table_options\", \"collation_connection=utf8_general_ci\")\n\tdb.AutoMigrate(&model.User{}, &model.Todo{})\n}", "func RunMigrationsUp(gormdb *gorm.DB) {\n\tgormdb.AutoMigrate(&entities.Tag{})\n\tgormdb.AutoMigrate(&entities.RecordType{})\n\tgormdb.AutoMigrate(&entities.Record{})\n\tgormdb.Model(&entities.Record{}).AddForeignKey(\"record_type_id\", \"record_types(id)\", \"RESTRICT\", \"RESTRICT\")\n}", "func Up() error {\n\tdb, err := db()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs, err := versions(db, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfiles, err := filepath.Glob(filepath.Join(DirName, \"*.up.sql\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trun := []string{}\n\tfor _, f := range files {\n\t\tname := filepath.Base(f[:len(f)-7])\n\t\texists := false\n\t\tfor _, v := range vs {\n\t\t\tif name == v {\n\t\t\t\texists = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !exists {\n\t\t\trun = append(run, name)\n\t\t}\n\t}\n\n\tfor _, r := range run {\n\t\tfmt.Println(\"running\", r)\n\t\tcontents, err := ioutil.ReadFile(filepath.Join(DirName, r+\".up.sql\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = db.Exec(string(contents))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(run) == 0 {\n\t\tfmt.Println(\"nothing to run\")\n\t}\n\n\treturn nil\n}", "func main() {\n\tcontainer := server.BuildContainer()\n\n\terr := container.Invoke(func(db *sql.DB) {\n\t\tdefer db.Close()\n\n\t\tmigration := &CreateUsersTable01{db}\n\n\t\tres, err := migration.Up()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfmt.Println(res)\n\t})\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (db *Database) RunMigrations(ctx context.Context) error {\n\tlogger := logging.FromContext(ctx)\n\tm := db.getMigrations(ctx)\n\tlogger.Infof(\"database migrations started\")\n\tif err := m.Migrate(); err != nil {\n\t\tlogger.Errorf(\"migrations failed: %v\", err)\n\t\treturn err\n\t}\n\tlogger.Infof(\"database migrations completed\")\n\treturn nil\n}", "func UpByOne(cfg *config) error {\n\tmigrations, err := CollectMigrations(cfg, minVersion, maxVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcurrentVersion, err := GetDBVersion(cfg.db)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnext, err := migrations.Next(currentVersion)\n\tif err != nil {\n\t\tif err == ErrNoNextVersion {\n\t\t\tlog.Printf(\"goose: no migrations to run. current version: %d\\n\", currentVersion)\n\t\t}\n\t\treturn err\n\t}\n\n\tif err = next.Up(cfg); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func migrateNew() {\n\tif len(flag.Args()) == 0 {\n\t\tlog.Fatalf(\"ERROR: Migration's name not specified\\n\")\n\t\treturn\n\t}\n\twd, _ := os.Getwd()\n\tname := path.Join(wd, \"migrations\", fmt.Sprintf(\"%d_%s.sql\", time.Now().Unix(), flag.Arg(0)))\n\tfile, err := os.Create(name)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: %s\\n\", err)\n\t\treturn\n\t}\n\tfmt.Fprintf(file, \"-- +migrate Up\\n\")\n\tfmt.Fprintf(file, \"-- SQL in section 'Up' is executed when this migration is applied\\n\\n\\n\")\n\tfmt.Fprintf(file, \"-- +migrate Down\\n\")\n\tfmt.Fprintf(file, \"-- SQL in section 'Down' is executed when this migration is rolled back\\n\\n\\n\")\n\terr = file.Close()\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: %s\\n\", err)\n\t} else {\n\t\tlog.Printf(\"INFO: File %s has been successfully created\\n\", name)\n\t}\n}", "func (c *Migrate) Execute() error {\n\n\tseed, err := inject.Migrate(c.ProjectPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := os.Chdir(c.ProjectPath); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"💾 Running migrations...\")\n\terr = seed()\n\tif err1 := os.Chdir(wd); err1 != nil && err == nil {\n\t\terr = err1\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"✅ Database migrated!\")\n\n\treturn nil\n}", "func (component *Database) MigrateUp() {\n\tfmt.Println(\"Migrate up start.\")\n\n\tlastVersion := component.MigrateLastVersion()\n\tvar err error\n\tfor version, m := range component.config.MigrationDict {\n\t\tif version <= lastVersion {\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Print(\"\\tup version: \" + version + \" ...\")\n\n\t\tm.Up()\n\t\tsqlList := m.GetSqlList()\n\n\t\tsession := component.NewSession()\n\t\terr = session.Begin()\n\t\tutils.Error.Panic(err)\n\n\t\tfor _, sqlStr := range sqlList {\n\t\t\t_, err = session.Exec(sqlStr)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t\tmigration := new(tables.Migration)\n\t\tmigration.Version = version\n\t\t_, err := session.Insert(migration)\n\t\tif err != nil {\n\t\t\t_ = session.Rollback()\n\t\t\tutils.Error.Panic(err)\n\t\t} else {\n\t\t\terr = session.Commit()\n\t\t\tutils.Error.Panic(err)\n\t\t}\n\n\t\tfmt.Println(\" done.\")\n\t}\n\tfmt.Println(\"Migrate up finished.\")\n}", "func (base *DatabaseImplementation) ExecuteMigration(schema string, command string) error {\n\t_, err1 := base.DB.Exec(base.mq.SetSchemaSQL(schema))\n\tif err1 != nil {\n\t\treturn err1\n\t}\n\t_, err2 := base.DB.Exec(command)\n\treturn err2\n\n}", "func (d *commandSyncDb) Run() error {\n\tvar drops []string\n\tvar err error\n\tif d.force {\n\t\tdrops, err = defaultModelCache.getDbDropSQL(d.al)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tdb := d.al.DB\n\n\tif d.force && len(drops) > 0 {\n\t\tfor i, mi := range defaultModelCache.allOrdered() {\n\t\t\tquery := drops[i]\n\t\t\tif !d.noInfo {\n\t\t\t\tfmt.Printf(\"drop table `%s`\\n\", mi.table)\n\t\t\t}\n\t\t\t_, err := db.Exec(query)\n\t\t\tif d.verbose {\n\t\t\t\tfmt.Printf(\" %s\\n\\n\", query)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tif d.rtOnError {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\" %s\\n\", err.Error())\n\t\t\t}\n\t\t}\n\t}\n\n\tcreateQueries, indexes, err := defaultModelCache.getDbCreateSQL(d.al)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttables, err := d.al.DbBaser.GetTables(db)\n\tif err != nil {\n\t\tif d.rtOnError {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\" %s\\n\", err.Error())\n\t}\n\n\tctx := context.Background()\n\tfor i, mi := range defaultModelCache.allOrdered() {\n\n\t\tif !isApplicableTableForDB(mi.addrField, d.al.Name) {\n\t\t\tfmt.Printf(\"table `%s` is not applicable to database '%s'\\n\", mi.table, d.al.Name)\n\t\t\tcontinue\n\t\t}\n\n\t\tif tables[mi.table] {\n\t\t\tif !d.noInfo {\n\t\t\t\tfmt.Printf(\"table `%s` already exists, skip\\n\", mi.table)\n\t\t\t}\n\n\t\t\tvar fields []*fieldInfo\n\t\t\tcolumns, err := d.al.DbBaser.GetColumns(ctx, db, mi.table)\n\t\t\tif err != nil {\n\t\t\t\tif d.rtOnError {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\" %s\\n\", err.Error())\n\t\t\t}\n\n\t\t\tfor _, fi := range mi.fields.fieldsDB {\n\t\t\t\tif _, ok := columns[fi.column]; !ok {\n\t\t\t\t\tfields = append(fields, fi)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, fi := range fields {\n\t\t\t\tquery := getColumnAddQuery(d.al, fi)\n\n\t\t\t\tif !d.noInfo {\n\t\t\t\t\tfmt.Printf(\"add column `%s` for table `%s`\\n\", fi.fullName, mi.table)\n\t\t\t\t}\n\n\t\t\t\t_, err := db.Exec(query)\n\t\t\t\tif d.verbose {\n\t\t\t\t\tfmt.Printf(\" %s\\n\", query)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\tif d.rtOnError {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Printf(\" %s\\n\", err.Error())\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, idx := range indexes[mi.table] {\n\t\t\t\tif !d.al.DbBaser.IndexExists(ctx, db, idx.Table, idx.Name) {\n\t\t\t\t\tif !d.noInfo {\n\t\t\t\t\t\tfmt.Printf(\"create index `%s` for table `%s`\\n\", idx.Name, idx.Table)\n\t\t\t\t\t}\n\n\t\t\t\t\tquery := idx.SQL\n\t\t\t\t\t_, err := db.Exec(query)\n\t\t\t\t\tif d.verbose {\n\t\t\t\t\t\tfmt.Printf(\" %s\\n\", query)\n\t\t\t\t\t}\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif d.rtOnError {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfmt.Printf(\" %s\\n\", err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif !d.noInfo {\n\t\t\tfmt.Printf(\"create table `%s` \\n\", mi.table)\n\t\t}\n\n\t\tqueries := []string{createQueries[i]}\n\t\tfor _, idx := range indexes[mi.table] {\n\t\t\tqueries = append(queries, idx.SQL)\n\t\t}\n\n\t\tfor _, query := range queries {\n\t\t\t_, err := db.Exec(query)\n\t\t\tif d.verbose {\n\t\t\t\tquery = \" \" + strings.Join(strings.Split(query, \"\\n\"), \"\\n \")\n\t\t\t\tfmt.Println(query)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tif d.rtOnError {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\" %s\\n\", err.Error())\n\t\t\t}\n\t\t}\n\t\tif d.verbose {\n\t\t\tfmt.Println(\"\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func testDBVersioning(t *testing.T, vdb *database.VersionedDB) {\n\t// get the DB version\n\tdbVersion, err := vdb.DBVersion()\n\tassert.Nil(t, err)\n\tmaxVersion := vdb.MaxDBVersion()\n\n\t// downgrade to 0\n\terr = vdb.Migrate(0)\n\tassert.Nil(t, err)\n\tdbVersion, err = vdb.DBVersion()\n\tassert.Nil(t, err)\n\tassert.Equal(t, 0, dbVersion)\n\n\t// upgrade the the latest version\n\terr = vdb.Migrate(maxVersion)\n\tassert.Nil(t, err)\n\tdbVersion, err = vdb.DBVersion()\n\tassert.Nil(t, err)\n\tassert.Equal(t, maxVersion, dbVersion)\n}", "func UpTo(cfg *config, version int64) error {\n\tmigrations, err := CollectMigrations(cfg, minVersion, version)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\tcurrent, err := GetDBVersion(cfg.db)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnext, err := migrations.Next(current)\n\t\tif err != nil {\n\t\t\tif err == ErrNoNextVersion {\n\t\t\t\tlog.Printf(\"goose: no migrations to run. current version: %d\\n\", current)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\tif err = next.Up(cfg); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (f *fsmUpdateEngine) RunCommand(ctx context.Context, runner fsm.RemoteRunner, server storage.Server, p fsm.Params) error {\n\targs := []string{\"upgrade\", \"--phase\", p.PhaseID, fmt.Sprintf(\"--force=%v\", p.Force)}\n\treturn runner.Run(ctx, server, args...)\n}", "func (svc *Service) Up() (int64, int64, error) {\n\treturn migrations.Run(svc.database, \"up\")\n}", "func autoMigrate(db *gorm.DB) {\n\tif os.Getenv(\"DROP_TABLES\") == \"yes\" {\n\t\t_ = db.Migrator().DropTable(&models.User{})\n\t\t_ = db.Migrator().DropTable(&models.Date{})\n\t\t_ = db.Migrator().DropTable(&models.DailyText{})\n\t}\n\n\tif os.Getenv(\"CREATE_TABLE\") == \"yes\" {\n\t\tif err := db.AutoMigrate(&models.User{}); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tif err := db.AutoMigrate(&models.Date{}); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tif err := db.AutoMigrate(&models.DailyText{}); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n\n}", "func (m *SQLLiteMigrator) Up(ctx context.Context, migrations migrations.Migrations) error {\n\ttx, err := m.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar commitErr error\n\tdefer func() {\n\t\tif commitErr == nil {\n\t\t\treturn\n\t\t}\n\t\tlogrus.WithError(commitErr).Warningf(\"tx commit failed\")\n\t\tif err := tx.Rollback(); err != nil {\n\t\t\tlogrus.WithError(err).Warningf(\"couldn't rollback after failed commit\")\n\t\t}\n\t}()\n\n\tif err := m.ensureMigrationTable(ctx, tx); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, migration := range migrations {\n\t\tcurrent_version, err := m.version(ctx, tx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif migration.Id != current_version+1 {\n\t\t\treturn fmt.Errorf(\"migration applied out of order\")\n\t\t}\n\n\t\tif err := migration.Up(ctx, tx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := m.setVersion(ctx, tx, migration.Id); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tcommitErr = tx.Commit()\n\treturn commitErr\n}", "func (s *SQLStore) RunMigrations() error {\n\tcurrentSchemaVersion, err := s.GetCurrentVersion()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to get the current schema version\")\n\t}\n\n\tif currentSchemaVersion.LT(LatestVersion()) {\n\t\tif err := s.Migrate(currentSchemaVersion); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to complete migrations\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func setupTestDB(t *testing.T, version int64) *sql.DB {\n\tis := is.New(t)\n\tdb, err := newDockerDB(t)\n\tis.NoErr(err)\n\n\t// Create goose table.\n\tcurrent, err := in.EnsureDBVersion(db)\n\tis.NoErr(err)\n\tis.True(current == int64(0))\n\t// Collect first 5 migrations.\n\tmigrations, err := in.CollectMigrations(migrationsDir, 0, version)\n\tis.NoErr(err)\n\tis.True(int64(len(migrations)) == version)\n\t// Apply n migrations manually.\n\tfor _, m := range migrations {\n\t\terr := m.Up(db)\n\t\tis.NoErr(err)\n\t}\n\t// Verify the current DB version is the Nth migration. This will only\n\t// work for sqeuentially applied migrations.\n\tcurrent, err = in.GetDBVersion(db)\n\tis.NoErr(err)\n\tis.True(current == int64(version))\n\n\treturn db\n}", "func forward(c *cli.Context, name string) error {\n\tdb, err := pomegranate.Connect(c.String(\"dburl\"))\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tdir := c.String(\"dir\")\n\tallMigrations, err := pomegranate.ReadMigrationFiles(dir)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\terr = pomegranate.MigrateForwardTo(name, db, allMigrations, true)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tfmt.Println(\"Done\")\n\treturn nil\n}", "func Migrate() {\n\tif err := Migrations().Migrate(); err != nil {\n\t\tlog.Fatalf(\"Could not migrate: %v\", err)\n\t}\n\n\tlog.Printf(\"Migration did run successfully\")\n}", "func RunMigrations(db *gorm.DB) {\n\tdb.AutoMigrate(&models.Article{})\n\tdb.AutoMigrate(&models.Page{})\n}", "func MigrateToNextVersion(tx *sql.Tx, nextVersion *int64, m Migrations, catalog string) error {\n\t// Obtain exclusive transaction level advisory that doesn't depend on any table.\n\t// Once obtained, the lock is held for the remainder of the current transaction.\n\t// (There is no UNLOCK TABLE command; locks are always released at transaction end.)\n\tif _, err := tx.Exec(\"SELECT pg_advisory_xact_lock($1)\", AdvisoryLockID); err != nil {\n\t\treturn errs.Errorf(\"Failed to acquire lock: %s\\n\", err)\n\t}\n\n\t// Determine current version and adjust the outmost loop\n\t// iterator variable \"version\"\n\tcurrentVersion, err := getCurrentVersion(tx, catalog)\n\tif err != nil {\n\t\treturn errs.WithStack(err)\n\t}\n\t*nextVersion = currentVersion + 1\n\tif *nextVersion >= int64(len(m)) {\n\t\t// No further updates to apply (this is NOT an error)\n\t\tlog.Info(nil, map[string]interface{}{\n\t\t\t\"next_version\": *nextVersion,\n\t\t\t\"current_version\": currentVersion,\n\t\t}, \"Current version %d. Nothing to update.\", currentVersion)\n\t\treturn nil\n\t}\n\n\tlog.Info(nil, map[string]interface{}{\n\t\t\"next_version\": *nextVersion,\n\t\t\"current_version\": currentVersion,\n\t}, \"Attempt to update DB to version %v\", *nextVersion)\n\n\t// Apply all the updates of the next version\n\tfor j := range m[*nextVersion] {\n\t\tif err := m[*nextVersion][j](tx); err != nil {\n\t\t\treturn errs.Errorf(\"Failed to execute migration of step %d of version %d: %s\\n\", j, *nextVersion, err)\n\t\t}\n\t}\n\n\tif _, err := tx.Exec(\"INSERT INTO version(version) VALUES($1)\", *nextVersion); err != nil {\n\t\treturn errs.Errorf(\"Failed to update DB to version %d: %s\\n\", *nextVersion, err)\n\t}\n\n\tlog.Info(nil, map[string]interface{}{\n\t\t\"next_version\": *nextVersion,\n\t\t\"current_version\": currentVersion,\n\t}, \"Successfully updated DB to version %v\", *nextVersion)\n\n\treturn nil\n}", "func MigrateDB(db *sql.DB) {\n\tmigrationSource := &migrate.PackrMigrationSource{\n\t\tBox: packr.NewBox(\"../migrations\"),\n\t}\n\n\tfmt.Printf(\"[migration] Begin migration...\\n\\n\")\n\n\ti, err := migrate.Exec(db, \"mysql\", migrationSource, migrate.Up)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tmigrations, _ := migrationSource.FindMigrations()\n\n\tif len(migrations) > 0 {\n\t\tfmt.Printf(\"[migration] Last migration id: %s\\n\\n\", migrations[len(migrations)-1].Id)\n\t}\n\n\tif i > 0 {\n\t\tfmt.Printf(\"[migration] %d migrations executed\\n\\n\", i)\n\t} else {\n\t\tfmt.Printf(\"[migration] There is no new migration\\n\\n\")\n\t}\n\n\tfmt.Printf(\"[migration] Migration finished\\n\\n\")\n}", "func main() {\n\terr := cmd.Execute(version)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func versionRun(cmd *cobra.Command, args []string) {\n\tprintKeyValue(\"Version: \", version)\n\tprintKeyValue(\"Commit: \", commit)\n\tprintKeyValue(\"Date: \", date)\n\tprintKeyValue(\"Author: \", author)\n\tprintKeyValue(\"Website: \", website)\n}", "func RunUp(_ *context.ExecuteContext, t *Task) error {\n\tt.logger().Info(\"project up\")\n\treturn t.execCompose(\"up\", \"-d\")\n}", "func (c *VersionCommand) Run(ctx context.Context, args []string) (err error) {\n\tfs := flag.NewFlagSet(\"litestream-version\", flag.ContinueOnError)\n\tfs.Usage = c.Usage\n\tif err := fs.Parse(args); err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(Version)\n\n\treturn nil\n}", "func Migrate(db *sql.DB, catalog string, configuration MigrationConfiguration) error {\n\n\tvar err error\n\tif db == nil {\n\t\treturn errs.Errorf(\"Database handle is nil\\n\")\n\t}\n\n\tm := GetMigrations(configuration)\n\n\tvar tx *sql.Tx\n\tfor nextVersion := int64(0); nextVersion < int64(len(m)) && err == nil; nextVersion++ {\n\n\t\ttx, err = db.Begin()\n\t\tif err != nil {\n\t\t\treturn errs.Errorf(\"Failed to start transaction: %s\\n\", err)\n\t\t}\n\n\t\terr = MigrateToNextVersion(tx, &nextVersion, m, catalog)\n\n\t\tif err != nil {\n\t\t\toldErr := err\n\t\t\tlog.Info(nil, map[string]interface{}{\n\t\t\t\t\"next_version\": nextVersion,\n\t\t\t\t\"migrations\": m,\n\t\t\t\t\"err\": err,\n\t\t\t}, \"Rolling back transaction due to: %v\", err)\n\n\t\t\tif err = tx.Rollback(); err != nil {\n\t\t\t\tlog.Error(nil, map[string]interface{}{\n\t\t\t\t\t\"next_version\": nextVersion,\n\t\t\t\t\t\"migrations\": m,\n\t\t\t\t\t\"err\": err,\n\t\t\t\t}, \"error while rolling back transaction\")\n\t\t\t\treturn errs.Errorf(\"Error while rolling back transaction: %s\\n\", err)\n\t\t\t}\n\t\t\treturn oldErr\n\t\t}\n\n\t\tif err = tx.Commit(); err != nil {\n\t\t\tlog.Error(nil, map[string]interface{}{\n\t\t\t\t\"migrations\": m,\n\t\t\t\t\"err\": err,\n\t\t\t}, \"error during transaction commit: %v\", err)\n\t\t\treturn errs.Errorf(\"Error during transaction commit: %s\\n\", err)\n\t\t}\n\n\t}\n\n\tif err != nil {\n\t\tlog.Error(nil, map[string]interface{}{\n\t\t\t\"migrations\": m,\n\t\t\t\"err\": err,\n\t\t}, \"migration failed with error: %v\", err)\n\t\treturn errs.Errorf(\"Migration failed with error: %s\\n\", err)\n\t}\n\n\treturn nil\n}", "func (s Service) Reverse(migration *Migration, save bool) error {\n\tif migration == nil {\n\t\treturn ErrNilMigration\n\t}\n\n\tfor _, statement := range migration.Down() {\n\t\tif s.dryRun {\n\t\t\tlogger.Info(\"statement: %s\", statement)\n\t\t\tcontinue\n\t\t}\n\n\t\terr := s.conn.Execute(statement)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to reverse migration %s: %s\\n%s\", migration.Name, err, statement)\n\t\t}\n\t}\n\n\tif s.dryRun {\n\t\treturn nil\n\t}\n\n\tif !save {\n\t\treturn nil\n\t}\n\n\terr := s.conn.RemoveApplied(migration.Name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to mark migration %s as not applied: %s\", migration.Name, err)\n\t}\n\n\treturn nil\n}", "func Migrate(db *sql.DB, migrations migrate.MigrationSource, dir MigrateDir, count int) (int, error) {\n\tswitch dir {\n\tcase MigrateUp:\n\t\treturn migrate.ExecMax(db, \"postgres\", migrations, migrate.Up, count)\n\tcase MigrateDown:\n\t\treturn migrate.ExecMax(db, \"postgres\", migrations, migrate.Down, count)\n\tcase MigrateRedo:\n\n\t\tif count == 0 {\n\t\t\tcount = 1\n\t\t}\n\n\t\tdown, err := migrate.ExecMax(db, \"postgres\", migrations, migrate.Down, count)\n\t\tif err != nil {\n\t\t\treturn down, err\n\t\t}\n\n\t\treturn migrate.ExecMax(db, \"postgres\", migrations, migrate.Up, down)\n\tdefault:\n\t\treturn 0, errors.New(\"Invalid migration direction\")\n\t}\n}", "func (ctrl *MigrateController) Run(c *gin.Context) {\n\tmigrations.Run()\n\n\tc.String(http.StatusOK, \"complete \"+time.Now().Format(\"2006-01-02 15:04:05\"))\n}", "func (self PostgresDatabase) setDBVersion(version int) (err error) {\n log.Println(\"set db version to\", version)\n _, err = self.conn.Exec(\"DELETE FROM Settings WHERE name = $1\", \"version\")\n _, err = self.conn.Exec(\"INSERT INTO Settings(name, value) VALUES($1, $2)\", \"version\", fmt.Sprintf(\"%d\", version))\n return\n}", "func Migrate() {\n\tlog.Info(\"Executing migrations...\")\n\tDb.AutoMigrate(&models.Repository{}, &models.Week{}, &models.Contributor{})\n}", "func MainCommand() *cobra.Command {\n\tvar rootCommand = &cobra.Command{\n\t\tUse: \"db\",\n\t\tShort: \"Database tooling\",\n\t}\n\n\trootCommand.AddCommand(&cobra.Command{\n\t\tUse: \"migrate\",\n\t\tShort: \"Performs database migrations or read migration info\",\n\t\tRun: performMigrations,\n\t})\n\treturn rootCommand\n}", "func MigrateDown(conf config.Config, max int) (int, error) {\n\tctx := context.Background()\n\n\topenDBCtx, cancel := context.WithTimeout(ctx, 30*time.Second)\n\tdefer cancel()\n\tdb, err := glsql.OpenDB(openDBCtx, conf.DB)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"sql open: %v\", err)\n\t}\n\tdefer db.Close()\n\n\tmigrationSet := migrate.MigrationSet{\n\t\tTableName: migrations.MigrationTableName,\n\t}\n\n\treturn migrationSet.ExecMax(db, sqlMigrateDialect, migrationSource(), migrate.Down, max)\n}", "func Test_ExecuteVersion(t *testing.T) {\n\tfor _, v := range versiontests {\n\t\tt.Run(v.desc, func(t *testing.T) {\n\t\t\t// fakeout the output for the tests\n\t\t\tout := &testhelpers.FakeOut{}\n\t\t\tcommonOpts := opts.NewCommonOptionsWithTerm(clients.NewFactory(), os.Stdin, out, os.Stderr)\n\n\t\t\t// Set batchmode to true for tests\n\t\t\tcommonOpts.BatchMode = true\n\t\t\tcommand := version.NewCmdVersion(commonOpts)\n\n\t\t\tswitch v.short {\n\t\t\tcase true:\n\t\t\t\tcommand.SetArgs([]string{\"--short\"})\n\t\t\t\terr := command.Execute()\n\t\t\t\tassert.NoError(t, err, \"could not execute version\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Version\")\n\t\t\t\tassert.NotContains(t, out.GetOutput(), \"Commit\")\n\t\t\t\tassert.NotContains(t, out.GetOutput(), \"Build date\")\n\t\t\t\tassert.NotContains(t, out.GetOutput(), \"Go version\")\n\t\t\t\tassert.NotContains(t, out.GetOutput(), \"Git tree state\")\n\t\t\tdefault:\n\t\t\t\terr := command.Execute()\n\t\t\t\tassert.NoError(t, err, \"could not execute version\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Version\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Commit\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Build date\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Go version\")\n\t\t\t\tassert.Contains(t, out.GetOutput(), \"Git tree state\")\n\t\t\t}\n\t\t})\n\t}\n}", "func (svc *Service) Down() (int64, int64, error) {\n\treturn migrations.Run(svc.database, \"down\")\n}", "func doDatabaseMigrations(db *WowDB, env *Env, blizzard Blizzard) {\n\n\tif ! db.HasTable(&Race{}) {\n\t\tlog.Debug(\"Migrating race\")\n\t\tdb.AutoMigrate(&Race{})\n\t\terr := UpdateRacesFromBlizzard(env, blizzard)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Could not update races: %v\", err)\n\t\t}\n\t}\n\n\tif ! db.HasTable(&ToonClass{}) {\n\t\tlog.Println(\"Migrating classes\")\n\t\tdb.AutoMigrate(&ToonClass{})\n\t\terr := UpdateClassesFromBlizzard(env, blizzard)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Could not update classes: %v\", err)\n\t\t}\n\t}\n\n\tdb.AutoMigrate(&Stat{})\n\tdb.AutoMigrate(&Toon{})\n\n\tif ! db.HasTable(&ClassColor{}) {\n\t\tdb.AutoMigrate(&ClassColor{})\n\t\tdb.Model(&ClassColor{}).AddForeignKey(\"toon_class_id\", \"toon_classes(id)\", \"RESTRICT\", \"RESTRICT\")\n\t\tvar tColor = ClassColor{ToonClassID: 1, Color: \"#C79C63\"}\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 2\n\t\ttColor.Color = \"#F58CBA\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 3\n\t\ttColor.Color = \"#ABD473\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 4\n\t\ttColor.Color = \"#FFF569\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 5\n\t\ttColor.Color = \"#F0EBE0\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 6\n\t\ttColor.Color = \"#C41F3B\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 7\n\t\ttColor.Color = \"#0070DE\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 8\n\t\ttColor.Color = \"#69CCF0\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 9\n\t\ttColor.Color = \"#9482C9\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 10\n\t\ttColor.Color = \"#00FF96\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 11\n\t\ttColor.Color = \"#FF7D0A\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 12\n\t\ttColor.Color = \"#A330C9\"\n\t\tdb.Create(&tColor)\n\t}\n\n\tdb.Model(&Toon{}).AddForeignKey(\"race_id\", \"races(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&Toon{}).AddForeignKey(\"class_id\", \"toon_classes(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&Stat{}).AddForeignKey(\"toon_id\", \"toons(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&Stat{}).AddUniqueIndex(\"idx_toon_id_create_date\", \"toon_id\", \"insert_date\")\n}", "func RunMigrationsDown(gormdb *gorm.DB) {\n\tgormdb.DropTable(\"record_tags\")\n\tgormdb.DropTable(&entities.Record{})\n\tgormdb.DropTable(&entities.RecordType{})\n\tgormdb.DropTable(&entities.Tag{})\n}", "func RunMigrations(c config.Context) error {\n\treturn c.Db.AutoMigrate(&Plot{})\n}", "func RunDown(_ *context.ExecuteContext, t *Task) error {\n\tt.logger().Info(\"project down\")\n\treturn t.execCompose(\"down\")\n}", "func main() {\n\tlog.SetFlags(log.LstdFlags | log.Lshortfile)\n\tos.Exit(commands.Run(versionString()))\n}", "func Command(app *kingpin.Application) {\n\tcmd := new(cmdVersion)\n\tapp.Command(\"version\", fmt.Sprintf(\"Prints %s version\", app.Name)).Action(cmd.run)\n}", "func Rollback() {\n\tif err := Migrations().RollbackLast(); err != nil {\n\t\tlog.Fatalf(\"Could not rollback: %v\", err)\n\t}\n\n\tlog.Printf(\"Rollback did run successfully\")\n}", "func (driver *Driver) Migrate(migration *m.PlannedMigration) error {\n\t// Note: Driver does not support DDL statements in a transaction. If DDL statements are\n\t// executed in a transaction, it is an implicit commit.\n\t// See: http://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html\n\tvar migrationStatements *parser.ParsedMigration\n\n\tif migration.Direction == m.Up {\n\t\tmigrationStatements = migration.Up\n\t} else if migration.Direction == m.Down {\n\t\tmigrationStatements = migration.Down\n\t}\n\n\tfor _, sqlStmt := range migrationStatements.Statements {\n\t\tif len(strings.TrimSpace(sqlStmt)) > 0 {\n\t\t\tif _, err := driver.db.Exec(sqlStmt); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error executing statement: %s\\n%s\", err, sqlStmt)\n\t\t\t}\n\t\t}\n\t}\n\n\tif migration.Direction == m.Up {\n\t\tif _, err := driver.db.Exec(\"INSERT INTO \"+mysqlTableName+\" (version) VALUES (?)\", migration.ID); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif _, err := driver.db.Exec(\"DELETE FROM \"+mysqlTableName+\" WHERE version=?\", migration.ID); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (sl SQLiteStruct) ProcessNow(lm m.Migration, mig m.UpDown, updown string, force bool) {\n\tif updown == \"up\" {\n\t\tif force == false && lm.ID <= sl.GetLastMigrationNo() {\n\t\t\treturn\n\t\t}\n\t\tif force == true && checkMigrationExecutedForID(lm.ID) {\n\t\t\tfmt.Println(lm.ID + \" -> Its already executed.\")\n\t\t\treturn\n\t\t}\n\t}\n\tlocalUpDown = updown\n\n\tworkingVersion = lm.ID\n\tnid, _ := strconv.Atoi(lm.ID)\n\tif nid != 0 {\n\t\tfmt.Println(\"Executing ID : \", lm.ID)\n\t\tfor _, v := range mig.AddColumn {\n\t\t\tfor _, vv := range v.Columns {\n\t\t\t\taddColumn(bTQ+v.TableName+bTQ, bTQ+vv.FieldName+bTQ+\" \", dataTypeConversion(vv.DataType))\n\t\t\t}\n\t\t}\n\t\tfor _, v := range mig.AddIndex {\n\t\t\tvar fieldNameArray []string\n\t\t\tfor _, vv := range v.Columns {\n\t\t\t\tfieldNameArray = append(fieldNameArray, bTQ+vv.FieldName+bTQ+\" \")\n\t\t\t}\n\t\t\taddIndex(bTQ+v.TableName+bTQ, v.IndexType, fieldNameArray)\n\t\t}\n\t\tfor _, v := range mig.CreateTable {\n\t\t\tvar valuesArray []string\n\t\t\tfor _, vv := range v.Columns {\n\t\t\t\tvaluesArray = append(valuesArray, bTQ+vv.FieldName+bTQ+\" \"+dataTypeConversion(vv.DataType))\n\t\t\t}\n\t\t\tcreateTable(bTQ+v.TableName+bTQ, valuesArray)\n\t\t}\n\t\tfor _, v := range mig.DropColumn {\n\t\t\tfor _, vv := range v.Columns {\n\t\t\t\tdropColumn(bTQ+v.TableName+bTQ, bTQ+vv.FieldName+bTQ+\" \")\n\t\t\t}\n\t\t}\n\t\tfor _, v := range mig.DropIndex {\n\t\t\tvar fieldNameArray []string\n\t\t\tfor _, vv := range v.Columns {\n\t\t\t\tfieldNameArray = append(fieldNameArray, bTQ+vv.FieldName+bTQ+\" \")\n\t\t\t}\n\t\t\tdropIndex(bTQ+v.TableName+bTQ, v.IndexType, fieldNameArray)\n\t\t}\n\t\tfor _, v := range mig.DropTable {\n\t\t\tdropTable(bTQ + v.TableName + bTQ)\n\t\t}\n\t\tfor _, v := range mig.RenameTable {\n\t\t\trenameTable(bTQ+v.OldTableName+bTQ, bTQ+v.NewTableName+bTQ)\n\t\t}\n\t\tif mig.Sql != \"\" {\n\t\t\tdirectSQL(mig.Sql)\n\t\t}\n\t\tupdateMigrationTable()\n\t}\n}", "func Migrate(logger logger.Logger, db *sqlx.DB) {\n\tlogger.Info().Msg(\"Starting database migration\")\n\n\tdbInstance, err := postgres.WithInstance(db.DB, &postgres.Config{})\n\tif err != nil {\n\t\tlogger.Fatal().Err(err).Msg(\"Failed to create migrate database instance\")\n\t}\n\n\tsrcInstance, err := httpfs.New(pkger.Dir(\"/migrate/migrations\"), \"\")\n\tif err != nil {\n\t\tlogger.Fatal().Err(err).Msg(\"Failed to create migrate source instance\")\n\t}\n\n\tms, err := migrate.NewWithInstance(\"httpfs\", srcInstance, \"postgres\", dbInstance)\n\tif err != nil {\n\t\tlogger.Fatal().Err(err).Msg(\"Failed to create migration service\")\n\t}\n\n\tversion, _, err := ms.Version()\n\tif err != nil {\n\t\tif err == migrate.ErrNilVersion {\n\t\t\tlogger.Info().Msg(\"No migrations have been applied yet\")\n\t\t} else {\n\t\t\tlogger.Fatal().Err(err).Msg(\"Failed to get migration version\")\n\t\t}\n\t} else {\n\t\tlogger.Info().Uint(\"migrationVersion\", version).Send()\n\t}\n\n\tif err := ms.Up(); err != nil {\n\t\tif err == migrate.ErrNoChange {\n\t\t\tlogger.Info().Msg(\"No new migrations to apply\")\n\t\t} else {\n\t\t\tlogger.Fatal().Err(err).Msg(\"Failed to apply migrations\")\n\t\t}\n\t}\n\n\tlogger.Info().Msg(\"Database migration complete\")\n}", "func (c command) run() error {\n\tc.FlagSet.Parse(flag.Args()[1:])\n\treturn c.f(c.FlagSet)\n}", "func (m *Migrator) Up(ctx context.Context) error {\n\t_, err := m.UpTo(ctx, 0)\n\treturn err\n}", "func RunMigrations(c *datastore.Client, ns string, migratable interface{}) {\n\n\tfmt.Println(\"Running Unison\")\n\n\t// Get the timestamp of the last applied migration\n\tlastAppliedMigrationTS := getLastAppliedMigrationTimeStamp(c, ns)\n\n\ttMigratable := reflect.TypeOf(migratable)\n\n\tmigrationMetaSet, err := generateMigrationMetaSet(tMigratable)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsort.Sort(migrationMetaSet)\n\n\tvMigratable := reflect.ValueOf(migratable)\n\n\tfor _, migration := range migrationMetaSet.set {\n\n\t\tif migration.Timestamp <= lastAppliedMigrationTS {\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Printf(\"Applying migration %d ... \", migration.Timestamp)\n\n\t\ttx, _ := c.NewTransaction(context.Background())\n\n\t\tmethod := vMigratable.MethodByName(migration.Name)\n\n\t\trtx := reflect.ValueOf(tx)\n\t\trns := reflect.ValueOf(ns)\n\n\t\tvalues := method.Call([]reflect.Value{rtx, rns})\n\n\t\tvalue := values[0]\n\n\t\tif !value.IsNil() {\n\t\t\te, _ := value.Interface().(error)\n\n\t\t\tfmt.Printf(\"Failed. Cause: %s\\n\", e.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttxkey := &datastore.Key{Kind: UnisonMigrationMetaKind, Name: migration.Name, Namespace: ns}\n\t\tmigration.AppliedAt = time.Now()\n\n\t\ttx.Put(txkey, &migration)\n\n\t\t_, err := tx.Commit()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfmt.Printf(\"Done\\n\")\n\t}\n\n\tfmt.Printf(\"We are done !!\\n\")\n}", "func (a *App) downgradeMigration(name string, timestamp int64) error {\n\tfile, err := ioutil.ReadFile(fmt.Sprintf(\"%s/%s/down.sql\", a.path, name))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to read down.sql\")\n\t}\n\tmigr, err := a.db.GetMigrationByTheVersion(timestamp)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unable to get migration record\")\n\t}\n\tif !migr.Applied {\n\t\treturn nil\n\t}\n\tif err := a.db.ExecuteCommand(string(file)); err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"migration %d is not applied\", timestamp))\n\t}\n\n\tif err := a.db.UpdateMigration(migr.ID, false, db.RejectedStatus); err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"migration %d is not applied\", timestamp))\n\t}\n\treturn nil\n}", "func usage(flags *flag.FlagSet) func() {\n\treturn func() {\n\n\t\tusagePrefix := `\ndb [flags] command\n\t`\n\n\t\tusageCommands := `\nCommands:\n up \tMigrate the DB to the most recent version available\n up-by-one \tMigrate the DB up by 1\n up-to VERSION \tMigrate the DB to a specific VERSION\n down \tRoll back the version by 1\n down-to VERSION \tRoll back to a specific VERSION\n redo \tRe-run the latest migration\n reset \tRoll back all migrations\n status \tDump the migration status for the current DB\n version \tPrint the current version of the database\n create NAME [sql|go] \tCreates new migration file with the current timestamp\n fix \tApply sequential ordering to migrations\n\t`\n\t\tfmt.Println(usagePrefix)\n\t\tfmt.Println(\"Flags:\")\n\t\tflags.PrintDefaults()\n\t\tfmt.Println(usageCommands)\n\t}\n}", "func main() {\n\tcmd.Execute(version, gitCommit, buildDate)\n}", "func (m *Migrator) UpTo(ctx context.Context, step int) (applied int, err error) {\n\tspan, ctx := m.startSpan(ctx, MigrationUpOpName)\n\tdefer span.End()\n\n\tc := m.Connection.WithContext(ctx)\n\terr = m.exec(ctx, func() error {\n\t\tmtn := m.sanitizedMigrationTableName(c)\n\t\tmfs := m.Migrations[\"up\"].SortAndFilter(c.Dialect.Name())\n\t\tfor _, mi := range mfs {\n\t\t\tl := m.l.WithField(\"version\", mi.Version).WithField(\"migration_name\", mi.Name).WithField(\"migration_file\", mi.Path)\n\n\t\t\texists, err := c.Where(\"version = ?\", mi.Version).Exists(mtn)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"problem checking for migration version %s\", mi.Version)\n\t\t\t}\n\n\t\t\tif exists {\n\t\t\t\tl.Debug(\"Migration has already been applied, skipping.\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif len(mi.Version) > 14 {\n\t\t\t\tl.Debug(\"Migration has not been applied but it might be a legacy migration, investigating.\")\n\n\t\t\t\tlegacyVersion := mi.Version[:14]\n\t\t\t\texists, err = c.Where(\"version = ?\", legacyVersion).Exists(mtn)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"problem checking for migration version %s\", mi.Version)\n\t\t\t\t}\n\n\t\t\t\tif exists {\n\t\t\t\t\tl.WithField(\"legacy_version\", legacyVersion).WithField(\"migration_table\", mtn).Debug(\"Migration has already been applied in a legacy migration run. Updating version in migration table.\")\n\t\t\t\t\tif err := m.isolatedTransaction(ctx, \"init-migrate\", func(conn *pop.Connection) error {\n\t\t\t\t\t\t// We do not want to remove the legacy migration version or subsequent migrations might be applied twice.\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// Do not activate the following - it is just for reference.\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// if _, err := tx.Store.Exec(fmt.Sprintf(\"DELETE FROM %s WHERE version = ?\", mtn), legacyVersion); err != nil {\n\t\t\t\t\t\t//\treturn errors.Wrapf(err, \"problem removing legacy version %s\", mi.Version)\n\t\t\t\t\t\t// }\n\n\t\t\t\t\t\t// #nosec G201 - mtn is a system-wide const\n\t\t\t\t\t\terr := conn.RawQuery(fmt.Sprintf(\"INSERT INTO %s (version) VALUES (?)\", mtn), mi.Version).Exec()\n\t\t\t\t\t\treturn errors.Wrapf(err, \"problem inserting migration version %s\", mi.Version)\n\t\t\t\t\t}); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tl.Info(\"Migration has not yet been applied, running migration.\")\n\n\t\t\tif err := mi.Valid(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif mi.Runner != nil {\n\t\t\t\terr := m.isolatedTransaction(ctx, \"up\", func(conn *pop.Connection) error {\n\t\t\t\t\tif err := mi.Runner(mi, conn, conn.TX); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\n\t\t\t\t\t// #nosec G201 - mtn is a system-wide const\n\t\t\t\t\tif err := conn.RawQuery(fmt.Sprintf(\"INSERT INTO %s (version) VALUES (?)\", mtn), mi.Version).Exec(); err != nil {\n\t\t\t\t\t\treturn errors.Wrapf(err, \"problem inserting migration version %s\", mi.Version)\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tl.Warn(\"Migration has requested running outside a transaction. Proceed with caution.\")\n\t\t\t\tif err := mi.RunnerNoTx(mi, c); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t// #nosec G201 - mtn is a system-wide const\n\t\t\t\tif err := c.RawQuery(fmt.Sprintf(\"INSERT INTO %s (version) VALUES (?)\", mtn), mi.Version).Exec(); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"problem inserting migration version %s. YOUR DATABASE MAY BE IN AN INCONSISTENT STATE! MANUAL INTERVENTION REQUIRED!\", mi.Version)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tl.Infof(\"> %s applied successfully\", mi.Name)\n\t\t\tapplied++\n\t\t\tif step > 0 && applied >= step {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif applied == 0 {\n\t\t\tm.l.Debugf(\"Migrations already up to date, nothing to apply\")\n\t\t} else {\n\t\t\tm.l.Debugf(\"Successfully applied %d migrations.\", applied)\n\t\t}\n\t\treturn nil\n\t})\n\treturn\n}", "func (d *SQLike) Migrate(tk *wanderer.Toolkit, migration *wanderer.Migration) error {\n\tif d.env.Migrations == nil || len(d.env.Migrations) == 0 {\n\t\treturn nil\n\t}\n\n\treturn sqlike.RunMigration(d.env.DB, filepath.Join(d.env.Migrations...), migration)\n}", "func migrate() {\n\n}", "func (o *UpgradePlatformOptions) Run() error {\n\tns := o.Namespace\n\tversion := o.Version\n\terr := o.runCommand(\"helm\", \"repo\", \"update\")\n\tif err != nil {\n\t\treturn err\n\t}\n\targs := []string{\"upgrade\"}\n\tif version != \"\" {\n\t\targs = append(args, \"--version\", version)\n\t}\n\tif ns != \"\" {\n\t\targs = append(args, \"--namespace\", ns)\n\t}\n\targs = append(args, o.ReleaseName, o.Chart)\n\treturn o.runCommand(\"helm\", args...)\n}", "func (db *DB) UpgradeToV1(migrations []migrate.Migration) (err error) {\n\t// Begin Tx\n\ttx, err := db.Beginx()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"begin tx\")\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t_ = tx.Rollback()\n\t\t\treturn\n\t\t}\n\t\terr = tx.Commit()\n\t}()\n\n\t// Remove the uniqueness constraint from md5\n\tq := `ALTER TABLE meta DROP INDEX md5`\n\tif _, err = tx.Exec(q); err != nil {\n\t\terr = errors.Wrap(err, \"remove md5 unique\")\n\t\treturn\n\t}\n\n\t// Add a content column to record the exact migration that ran\n\t// alongside the md5, insert the appropriate data, then set not null\n\tq = `ALTER TABLE meta ADD COLUMN content TEXT`\n\tif _, err = tx.Exec(q); err != nil {\n\t\terr = errors.Wrap(err, \"add content column\")\n\t\treturn\n\t}\n\tfor _, m := range migrations {\n\t\tq = `UPDATE meta SET content=? WHERE filename=?`\n\t\tif _, err = tx.Exec(q, m.Content, m.Filename); err != nil {\n\t\t\terr = errors.Wrap(err, \"update meta content\")\n\t\t\treturn\n\t\t}\n\t}\n\tq = `ALTER TABLE meta MODIFY COLUMN content TEXT NOT NULL`\n\tif _, err = tx.Exec(q); err != nil {\n\t\terr = errors.Wrap(err, \"update meta content not null\")\n\t\treturn\n\t}\n\n\t// Add the content column to metacheckpoints\n\tq = `\n\tALTER TABLE metacheckpoints\n\tADD COLUMN content TEXT NOT NULL`\n\t_, err = tx.Exec(q)\n\tif err != nil {\n\t\t// Ignore duplicate column errors\n\t\tif !strings.Contains(err.Error(), \"Duplicate column name\") {\n\t\t\terr = errors.Wrap(err, \"add metacheckpoints content\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tq = `\n\tCREATE TABLE IF NOT EXISTS metaversion (version INTEGER NOT NULL)`\n\tif _, err = tx.Exec(q); err != nil {\n\t\terr = errors.Wrap(err, \"create metaversion table\")\n\t\treturn\n\t}\n\tq = `DELETE FROM metaversion`\n\tif _, err = tx.Exec(q); err != nil {\n\t\terr = errors.Wrap(err, \"delete metaversion\")\n\t\treturn\n\t}\n\tq = `INSERT INTO metaversion (version) VALUES (1)`\n\tif _, err = tx.Exec(q); err != nil {\n\t\terr = errors.Wrap(err, \"insert metaversion\")\n\t\treturn\n\t}\n\treturn nil\n}" ]
[ "0.6652172", "0.66128784", "0.6590393", "0.621843", "0.6063731", "0.6010058", "0.59896505", "0.59123516", "0.5906943", "0.5897017", "0.5849042", "0.582094", "0.58018357", "0.5794039", "0.57828474", "0.5777766", "0.5741259", "0.5738055", "0.57363296", "0.5735054", "0.57171345", "0.5705435", "0.56978583", "0.566184", "0.5576943", "0.55724317", "0.55545694", "0.5529461", "0.55294603", "0.5519572", "0.5493162", "0.5492597", "0.54855007", "0.5475467", "0.5462604", "0.5443976", "0.5441709", "0.5434061", "0.5418784", "0.5409168", "0.53916395", "0.5384483", "0.53764063", "0.53716403", "0.53702843", "0.53420424", "0.53012234", "0.5295429", "0.5295027", "0.5291172", "0.52790993", "0.5262878", "0.52413505", "0.52272594", "0.521553", "0.5209858", "0.5207289", "0.52020997", "0.5178025", "0.51724267", "0.5160601", "0.5155633", "0.5154424", "0.5142339", "0.512978", "0.5122336", "0.5112774", "0.5110785", "0.5106805", "0.5085356", "0.50796664", "0.5063715", "0.5049658", "0.5027274", "0.50160056", "0.50157464", "0.50120425", "0.49828327", "0.49811307", "0.49792492", "0.49707517", "0.4968269", "0.4959299", "0.49551117", "0.4948405", "0.49460727", "0.4941784", "0.49407384", "0.493714", "0.49327973", "0.49310255", "0.4929043", "0.49276304", "0.49231842", "0.49181375", "0.49146235", "0.48989674", "0.48859176", "0.48734444", "0.48707566" ]
0.5071458
71
Read MeasurementsGET sends measurements json response
func MeasurementsGET(w http.ResponseWriter, r *http.Request) { // Get condition GET parameter condition := r.URL.Query().Get("condition") // Validate condition reg, errReg := regexp.Compile("^(\\w+[<>=]+\\w+(\\s(and|or)\\s?)?)*$") if errReg != nil { log.Println(errReg) response.SendError(w, http.StatusInternalServerError, friendlyError) return } if !reg.MatchString(condition) { log.Println("Wrong condition statement: " + condition) response.SendError(w, http.StatusInternalServerError, itemsNotFound) return } // Get all items data, err := feinstaub.ReadMeasurements(condition) if err != nil { log.Println(err) response.SendError(w, http.StatusInternalServerError, friendlyError) return } // Send json data if len(data) == 0 { response.Send(w, http.StatusOK, itemsNotFound, 0, nil) } else { response.Send(w, http.StatusOK, itemsFound, len(data), data) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (a *UnsupportedApiService) MeasurementsGET(ctx context.Context, measurementConfigId string) (MeasurementConfig, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue MeasurementConfig\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/measurements/{measurementConfigId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"measurementConfigId\"+\"}\", fmt.Sprintf(\"%v\", measurementConfigId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\tif err == nil {\n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v MeasurementConfig\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 401 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 406 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 429 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (a *UnsupportedApiService) MeasurementLinkListMeasurementsGET(ctx context.Context) (MeasurementConfigLinkList, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue MeasurementConfigLinkList\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/measurements\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\tif err == nil {\n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v MeasurementConfigLinkList\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 401 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 406 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 429 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (s *MeasurementService) GetMeasurements(ctx context.Context, opt *MeasurementCollectionOptions) (*MeasurementCollection, *Response, error) {\n\tdata := new(MeasurementCollection)\n\tresp, err := s.client.SendRequest(ctx, RequestOptions{\n\t\tMethod: \"GET\",\n\t\tPath: \"measurement/measurements\",\n\t\tQuery: opt,\n\t\tResponseData: data,\n\t})\n\treturn data, resp, err\n}", "func (r *UnitOfMeasureRequest) Get(ctx context.Context) (resObj *UnitOfMeasure, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}", "func (a *UnsupportedApiService) MeasurementsPOST(ctx context.Context, body MeasurementConfig) (MeasurementConfig, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Post\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue MeasurementConfig\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/measurements\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\tif err == nil {\n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 201 {\n\t\t\tvar v MeasurementConfig\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 401 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 406 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 415 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 422 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 429 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func GetMeasurements(deviceEUI string, start *time.Time, end *time.Time, config config.Database) ([]structs.Measurement, error) {\n\n\tdeviceEUIBytes, err := hex.DecodeString(deviceEUI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb, err := openConnection(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer db.Close()\n\n\tvar data structs.Measurement\n\tvar dataString string\n\tvar time time.Time\n\n\trows, err := db.Query(sqlStatementGetMeasurements, deviceEUIBytes, start, end)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar measurements []structs.Measurement\n\n\tfor rows.Next() {\n\t\tdata = structs.Measurement{}\n\t\trows.Scan(&dataString, &time)\n\n\t\tjson.Unmarshal([]byte(dataString), &data)\n\t\t// Channels contains the same fields gain, probably filter for only capital letters\n\t\tjson.Unmarshal([]byte(dataString), &data.Channels)\n\n\t\tdata.Time = time\n\t\t// This is a workaround: removes entries that start lowercease, since channels all start uppercase\n\t\tfor key := range data.Channels {\n\t\t\tif !unicode.IsUpper(rune(key[0])) {\n\t\t\t\tdelete(data.Channels, key)\n\t\t\t}\n\t\t}\n\n\t\t// If there are measurements, add it to the list\n\t\tif len(data.Channels) > 0 {\n\t\t\tmeasurements = append(measurements, data)\n\t\t}\n\n\t}\n\n\treturn measurements, nil\n}", "func GetTempMeasurements(c *gin.Context) {\n\tdeviceName := c.Param(\"device_name\")\n\tstartTime, endTime := helpers.ParamReader(c.Param(\"start_time\"),\n\t\tc.Param(\"end_time\"))\n\ttempMeasurement, err := database.GetTempMeasurements(c, deviceName,\n\t\tstartTime, endTime)\n\tif err != nil {\n\t\tc.Status(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, tempMeasurement)\n\t}\n}", "func (s *MeasurementService) GetMeasurement(ctx context.Context, ID string) (*Measurement, *Response, error) {\n\tdata := new(Measurement)\n\tresp, err := s.client.SendRequest(ctx, RequestOptions{\n\t\tMethod: \"GET\",\n\t\tPath: \"measurement/measurements/\" + ID,\n\t\tResponseData: data,\n\t})\n\treturn data, resp, err\n}", "func (c *HTTPClient) Metrics(timeout time.Duration) ([]string, error) {\n // temporary struct for parsing JSON response\n var respData struct {\n Names []string `json:\"results\"`\n }\n\n err := c.backend.Call(\"GET\", c.url+\"/api/v1/metricnames\", nil,\n timeout, http.StatusOK, &respData)\n if err != nil {\n return nil, err\n }\n\n glog.V(3).Infof(\"metric names: %+v\", respData.Names)\n return respData.Names, nil\n}", "func (a *Client) GetMeasuresByDeviceUsingGET(params *GetMeasuresByDeviceUsingGETParams, authInfo runtime.ClientAuthInfoWriter) (*GetMeasuresByDeviceUsingGETOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetMeasuresByDeviceUsingGETParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getMeasuresByDeviceUsingGET\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v1/tenant/{tenantId}/devices/{deviceId}/measures\",\n\t\tProducesMediaTypes: []string{\"*/*\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetMeasuresByDeviceUsingGETReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetMeasuresByDeviceUsingGETOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for getMeasuresByDeviceUsingGET: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func getApplicationMeasurement() endpointHandler {\n\treturn func(httpWriter http.ResponseWriter, httpRequest *http.Request) error {\n\t\tlog.Trace(\"resource/measure:getApplicationMeasurement() Entering\")\n\t\tdefer log.Trace(\"resource/measure:getApplicationMeasurement() Leaving\")\n\n\t\tlog.Debugf(\"resource/measure:getApplicationMeasurement() Request: %s\", httpRequest.URL.Path)\n\n\t\tcontentType := httpRequest.Header.Get(\"Content-Type\")\n\t\tif contentType != \"application/xml\" {\n\t\t\tlog.Errorf(\"resource/measure:getApplicationMeasurement() %s - Invalid content-type '%s'\", message.InvalidInputBadParam, contentType)\n\t\t\treturn &endpointError{Message: \"Invalid content-type\", StatusCode: http.StatusBadRequest}\n\t\t}\n\n\t\t// receive a manifest from hvs in the request body\n\t\tmanifestXml, err := ioutil.ReadAll(httpRequest.Body)\n\t\tif err != nil {\n\t\t\tseclog.WithError(err).Errorf(\"resource/measure:getApplicationMeasurement() %s - Error reading manifest xml\", message.InvalidInputBadParam)\n\t\t\treturn &endpointError{Message: \"Error reading manifest xml\", StatusCode: http.StatusBadRequest}\n\t\t}\n\n\t\t// make sure the xml is well formed, all other validation will be\n\t\t// peformed by 'measure' cmd line below\n\t\terr = xml.Unmarshal(manifestXml, new(interface{}))\n\t\tif err != nil {\n\t\t\tsecLog.WithError(err).Errorf(\"resource/measure:getApplicationMeasurement() %s - Invalid xml format\", message.InvalidInputBadParam)\n\t\t\treturn &endpointError{Message: \"Error: Invalid XML format\", StatusCode: http.StatusBadRequest}\n\t\t}\n\n\t\t// this should probably be done in wml --> if the wml log file is not yet created,\n\t\t// 'measure' will fail. for now, create the file before calling 'measure'.\n\t\tif _, err := os.Stat(WML_LOG_FILE); os.IsNotExist(err) {\n\t\t\t_, err = os.OpenFile(WML_LOG_FILE, os.O_RDONLY|os.O_CREATE, 0600)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).Errorf(\"resource/measure:getApplicationMeasurement() - Unable to open file\")\n\t\t\t\treturn &endpointError{Message: \"Error: Unable to open log file\", StatusCode: http.StatusInternalServerError}\n\t\t\t}\n\t\t}\n\n\t\t// make sure 'measure' is not a symbolic link before executing it\n\t\tmeasureExecutable, err := os.Lstat(constants.TBootXmMeasurePath)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Errorf(\"resource/measure:getApplicationMeasurement() - Unable to stat tboot path\")\n\t\t\treturn &endpointError{Message: \"Error: Unable to stat tboot path\", StatusCode: http.StatusInternalServerError}\n\t\t}\n\t\tif measureExecutable.Mode()&os.ModeSymlink == os.ModeSymlink {\n\t\t\tsecLog.WithError(err).Errorf(\"resource/measure:getApplicationMeasurement() %s - 'measure' is a symbolic link\", message.InvalidInputBadParam)\n\t\t\treturn &endpointError{Message: \"Error: Invalid 'measure' file\", StatusCode: http.StatusInternalServerError}\n\t\t}\n\n\t\t// call /opt/tbootxml/bin/measure and return the xml from stdout\n\t\t// 'measure <manifestxml> /'\n\t\tcmd := exec.Command(constants.TBootXmMeasurePath, string(manifestXml), \"/\")\n\t\tcmd.Env = append(os.Environ(), \"WML_LOG_FILE=\"+WML_LOG_FILE)\n\n\t\tstdout, err := cmd.StdoutPipe()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Errorf(\"resource/measure:getApplicationMeasurement() %s - Error getting measure output\", message.AppRuntimeErr)\n\t\t\treturn &endpointError{Message: \"Error processing request\", StatusCode: http.StatusInternalServerError}\n\t\t}\n\n\t\terr = cmd.Start()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Errorf(\"resource/measure:getApplicationMeasurement() %s - Failed to run: %s\", message.AppRuntimeErr, constants.TBootXmMeasurePath)\n\t\t\treturn &endpointError{Message: \"Error processing request\", StatusCode: http.StatusInternalServerError}\n\n\t\t}\n\n\t\tmeasureBytes, _ := ioutil.ReadAll(stdout)\n\t\terr = cmd.Wait()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Errorf(\"resource/measure:getApplicationMeasurement() %s - %s returned '%s'\", message.AppRuntimeErr, constants.TBootXmMeasurePath, string(measureBytes))\n\t\t\treturn &endpointError{Message: \"Error processing request\", StatusCode: http.StatusInternalServerError}\n\t\t}\n\n\t\t// make sure we got valid xml from measure\n\t\terr = xml.Unmarshal(measureBytes, new(interface{}))\n\t\tif err != nil {\n\t\t\tseclog.WithError(err).Errorf(\"resource/measure:getApplicationMeasurement() %s - Invalid measurement xml %s: %s\", message.AppRuntimeErr, httpRequest.URL.Path, string(measureBytes))\n\t\t\treturn &endpointError{Message: \"Error processing request\", StatusCode: http.StatusInternalServerError}\n\t\t}\n\n\t\thttpWriter.WriteHeader(http.StatusOK)\n\t\t_, _ = bytes.NewBuffer(measureBytes).WriteTo(httpWriter)\n\t\treturn nil\n\t}\n}", "func (s *sendClient) readMetrics() ([]byte, error) {\n\tresp, err := http.Get(s.readURL.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\t_, _ = io.Copy(io.Discard, resp.Body)\n\t\t_ = resp.Body.Close()\n\t}()\n\n\treturn body, nil\n}", "func (loadTimer *workersPool) GetMeasurements(rawurl string, nrOfTries int, thumbnailsDir string) (*PageMeasurements, error) {\n\t_, err := url.ParseRequestURI(rawurl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif nrOfTries < 1 {\n\t\treturn nil, fmt.Errorf(\"You have to specify at least one try to get any result\")\n\t}\n\n\tphantom, err := try(nrOfTries, (*loadTimer).getPhantom)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer (*loadTimer).releasePhantom(phantom)\n\n\tperformance, err := getMeasurementsInternal(phantom, rawurl, thumbnailsDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn performance, nil\n}", "func httpGetMetrics(t *testing.T) []string {\n\tresp, err := http.Get(fmt.Sprintf(\"http://localhost%v%v\", addr, endpoint))\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn []string{}\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn []string{}\n\t}\n\tlines := strings.Split(string(body), \"\\n\")\n\tif len(lines) == 0 {\n\t\tt.Error(\"httpGetMetrics returned empty response\")\n\t\treturn []string{}\n\t}\n\treturn lines\n}", "func GetData(w http.ResponseWriter, r *http.Request) {\n\tfrom := r.URL.Query().Get(\"from\")\n\tif from == \"\" {\n\t\tfrom = fmt.Sprintf(\"%d\", time.Now().Add(-10*time.Minute).UnixNano()/1000000000)\n\t}\n\tr.Body.Close()\n\tfromI, err := strconv.ParseInt(from, 10, 64)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"BAD 'from' parameter\"))\n\t\treturn\n\t}\n\twindow := r.URL.Query().Get(\"window\")\n\tif window == \"\" {\n\t\twindow = \"300\"\n\t}\n\twindowI, err := strconv.ParseInt(window, 10, 64)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"BAD 'window' parameter\"))\n\t\treturn\n\t}\n\trv, err := qei.GetData(time.Unix(fromI, 0), time.Duration(windowI)*time.Second)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(rv.JsonBytes())\n\tr.Body.Close()\n}", "func (s *sendClient) readMetrics() ([]byte, error) {\n\tresp, err := s.readClient.Get(s.readURL.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Read and close the rest of body.\n\t_, _ = io.Copy(io.Discard, resp.Body)\n\t_ = resp.Body.Close()\n\n\treturn body, nil\n}", "func (self *Client) ReadMetric(t MetricType, id string, o ...Modifier) ([]*Datapoint, error) {\n\to = prepend(o, self.Url(\"GET\", TypeEndpoint(t), SingleMetricEndpoint(id), DataEndpoint()))\n\n\tr, err := self.Send(o...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer r.Body.Close()\n\n\tif r.StatusCode == http.StatusOK {\n\t\tb, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Check for GaugeBucketpoint and so on for the rest.. uh\n\t\tdp := []*Datapoint{}\n\t\tif b != nil {\n\t\t\tif err = json.Unmarshal(b, &dp); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn dp, nil\n\t} else if r.StatusCode > 399 {\n\t\treturn nil, self.parseErrorResponse(r)\n\t}\n\n\treturn nil, nil\n}", "func (obj *GenericMeasure) GetMeasureRaw(ctx context.Context) (json.RawMessage, error) {\n\tresult := &struct {\n\t\tMeasure json.RawMessage `json:\"qMeasure\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetMeasure\", result)\n\treturn result.Measure, err\n}", "func (a *UnsupportedApiService) MeasurementsPUT(ctx context.Context, body MeasurementConfig, measurementConfigId string) (MeasurementConfig, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue MeasurementConfig\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/measurements/{measurementConfigId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"measurementConfigId\"+\"}\", fmt.Sprintf(\"%v\", measurementConfigId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\tif err == nil {\n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v MeasurementConfig\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 401 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 406 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 412 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 422 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 429 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (a *UnsupportedApiService) MeasurementsDELETE(ctx context.Context, measurementConfigId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/measurements/{measurementConfigId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"measurementConfigId\"+\"}\", fmt.Sprintf(\"%v\", measurementConfigId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/problem+json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 401 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHttpResponse, newErr\n\t\t}\n\n\t\tif localVarHttpResponse.StatusCode == 429 {\n\t\t\tvar v ProblemDetails\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHttpResponse, newErr\n\t\t}\n\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func getSensorData(w http.ResponseWriter, r *http.Request) {\n\tquery := r.URL.Query()\n\ts := query.Get(\"starttime\")\n\te := query.Get(\"endtime\")\n\tsensorType := query.Get(\"sensortype\")\n\tif s == \"\" || e == \"\" || sensorType == \"\" {\n\t\trespondWithError(w, http.StatusBadRequest, fmt.Errorf(\"empty parameters being passed\"))\n\t\treturn\n\t}\n\tstart, err := strconv.Atoi(s)\n\tif err != nil {\n\t\trespondWithError(w, http.StatusBadRequest, fmt.Errorf(\"check the value of parameters being passed\"))\n\t\treturn\n\t}\n\tend, err := strconv.Atoi(e)\n\tif err != nil {\n\t\trespondWithError(w, http.StatusBadRequest, fmt.Errorf(\"check the value of parameters being passed\"))\n\t\treturn\n\t}\n\tclaims := getClaims(w, r)\n\tvar st consts.BucketFilter\n\tkey := claims[\"key\"].(string)\n\tswitch strings.ToLower(sensorType) {\n\tcase \"humidity\":\n\t\tst = consts.Humidity\n\tcase \"temperature\":\n\t\tst = consts.Temperature\n\tcase \"waterlevel\":\n\t\tst = consts.WaterLevel\n\tcase \"ph\":\n\t\tst = consts.PH\n\tcase \"all\":\n\t\tst = consts.All\n\tdefault:\n\t\trespondWithError(w, http.StatusNotFound, fmt.Errorf(\"page not found\"))\n\t\treturn\n\t}\n\n\tdata, err := db.GetSensorData([]byte(key), st, int64(start), int64(end))\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tsendResponse(w, data)\n\treturn\n}", "func (dm *Datamuse) Get() (Results, error) {\n\tc := &http.Client{Timeout: 30 * time.Second}\n\n\tresp, err := c.Get(dm.apiURL.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar res Results\n\terr = json.NewDecoder(resp.Body).Decode(&res)\n\n\treturn res, err\n}", "func (c *Client) ReadMetric(t MetricType, id string, o ...Modifier) ([]*Datapoint, error) {\n\to = prepend(o, c.Url(\"GET\", TypeEndpoint(t), SingleMetricEndpoint(id), DataEndpoint()))\n\n\tr, err := c.Send(o...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer r.Body.Close()\n\n\tif r.StatusCode == http.StatusOK {\n\t\tb, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Check for GaugeBucketpoint and so on for the rest.. uh\n\t\tdp := []*Datapoint{}\n\t\tif b != nil {\n\t\t\tif err = json.Unmarshal(b, &dp); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn dp, nil\n\t} else if r.StatusCode > 399 {\n\t\treturn nil, c.parseErrorResponse(r)\n\t}\n\n\treturn nil, nil\n}", "func GetAllTempMeasurements(c *gin.Context) {\n\tstartTime, endTime := helpers.ParamReader(c.Param(\"start_time\"),\n\t\tc.Param(\"end_time\"))\n\ttempMeasurements, err := database.GetAllTempMeasurements(c,\n\t\tstartTime, endTime)\n\tif err != nil {\n\t\tc.Status(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, tempMeasurements)\n\t}\n}", "func (client ProxyMetricClient) GetData() (data []byte, err error) {\n\tconst generalScopeErr = \"error making a server request to get the metrics from remote endpoint\"\n\thttpClient := &http.Client{}\n\tvar resp *http.Response\n\t{\n\t\tsuccessResponse := false\n\t\tdefer func(startTime time.Time) {\n\t\t\tduration := time.Since(startTime).Seconds()\n\t\t\tlabels := []string{client.jobName, client.instanceName}\n\t\t\tif successResponse {\n\t\t\t\tclient.defFordwaderMetrics.FordwaderResponseDuration.WithLabelValues(labels...).Set(duration)\n\t\t\t}\n\t\t}(time.Now().UTC())\n\t\tif resp, err = httpClient.Do(client.req); err != nil {\n\t\t\tlog.WithFields(log.Fields{\"err\": err, \"req\": client.req}).Errorln(\"no success response\")\n\t\t\terrCause := fmt.Sprintln(\"can not do the request: \", err.Error())\n\t\t\treturn nil, util.ErrorFromThisScope(errCause, generalScopeErr)\n\t\t}\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\tlog.WithFields(log.Fields{\"status\": resp.Status, \"req\": client.req}).Errorln(\"no success response\")\n\t\t\terrCause := fmt.Sprintf(\"no success response, status %s\", resp.Status)\n\t\t\treturn nil, util.ErrorFromThisScope(errCause, generalScopeErr)\n\t\t}\n\t\tsuccessResponse = true\n\t}\n\tdefer resp.Body.Close()\n\tvar reader io.ReadCloser\n\tvar isGzipContent = false\n\tdefer func() {\n\t\tif isGzipContent {\n\t\t\treader.Close()\n\t\t}\n\t}()\n\tswitch resp.Header.Get(\"Content-Encoding\") {\n\tcase \"gzip\":\n\t\tisGzipContent = true\n\t\treader, err = gzip.NewReader(resp.Body)\n\t\tif err != nil {\n\t\t\terrCause := fmt.Sprintln(\"can not create gzip reader.\", err.Error())\n\t\t\treturn nil, util.ErrorFromThisScope(errCause, generalScopeErr)\n\t\t}\n\t\tdefer reader.Close()\n\tdefault:\n\t\treader = resp.Body\n\t}\n\t// FIXME(denisacostaq@gmail.com): write an integration test for plain text and compressed content\n\tif data, err = ioutil.ReadAll(reader); err != nil {\n\t\terrCause := fmt.Sprintln(\"can not read the body: \", err.Error())\n\t\treturn nil, util.ErrorFromThisScope(errCause, generalScopeErr)\n\t}\n\treturn data, nil\n}", "func queryMetrics(server string, env string, metricString string, ts datatypes.Timestamps, ps datatypes.PerformanceSignature) (datatypes.DynatraceMetricsResponse, error) {\n\turl := buildMetricsQueryURL(server, env, metricString, ts, ps)\n\n\t// Build the request object\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tlogging.LogError(datatypes.Logging{Message: fmt.Sprintf(\"Error creating request handler: %v.\", err)})\n\t\treturn datatypes.DynatraceMetricsResponse{}, err\n\t}\n\n\t// Set the API token\n\tapiTokenField := fmt.Sprintf(\"Api-Token %v\", ps.APIToken)\n\treq.Header.Add(\"Authorization\", apiTokenField)\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 10,\n\t}\n\n\t// Perform the request\n\tr, err := client.Do(req)\n\tif err != nil {\n\t\tlogging.LogError(datatypes.Logging{Message: fmt.Sprintf(\"Error reading metric data from Dynatrace: %v\", err)})\n\t\treturn datatypes.DynatraceMetricsResponse{}, err\n\t}\n\n\t// Read in the body\n\tb, err := ioutil.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\tlogging.LogError(datatypes.Logging{Message: fmt.Sprintf(\"Could not read response body from Dynatrace: %v\", err.Error())})\n\t\treturn datatypes.DynatraceMetricsResponse{}, fmt.Errorf(\"could not read response body from Dynatrace: %v\", err.Error())\n\t}\n\tlogging.LogDebug(datatypes.Logging{Message: fmt.Sprintf(\"Full response from Dynatrace is: %v.\", string(b))})\n\n\t// Check the status code\n\tif r.StatusCode != 200 {\n\t\tlogging.LogError(datatypes.Logging{Message: fmt.Sprintf(\"Invalid status code from Dynatrace: %v. Message is '%v'\", r.StatusCode, string(b))})\n\t\treturn datatypes.DynatraceMetricsResponse{}, fmt.Errorf(\"invalid status code from Dynatrace: %v\", r.StatusCode)\n\t}\n\n\t// Try to parse the response into MetricsResponses\n\tvar metricsResponse datatypes.DynatraceMetricsResponse\n\terr = json.Unmarshal(b, &metricsResponse)\n\tif err != nil {\n\t\treturn datatypes.DynatraceMetricsResponse{}, err\n\t}\n\n\treturn metricsResponse, nil\n}", "func (c *client) getAllTicketMetrics(endpoint string, in interface{}) ([]TicketMetric, error) {\n\tresult := make([]TicketMetric, 0)\n\tpayload, err := marshall(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theaders := map[string]string{}\n\tif in != nil {\n\t\theaders[\"Content-Type\"] = \"application/json\"\n\t}\n\n\tres, err := c.request(\"GET\", endpoint, headers, bytes.NewReader(payload))\n\tdataPerPage := new(APIPayload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiV2 := \"/api/v2/\"\n\tfieldName := strings.Split(endpoint[len(apiV2):], \".\")[0]\n\tdefer res.Body.Close()\n\n\terr = unmarshall(res, dataPerPage)\n\n\tapiStartIndex := strings.Index(dataPerPage.NextPage, apiV2)\n\tcurrentPage := endpoint\n\n\tvar totalWaitTime int64\n\tfor currentPage != \"\" {\n\t\t// if too many requests(res.StatusCode == 429), delay sending request\n\t\tif res.StatusCode == 429 {\n\t\t\tafter, err := strconv.ParseInt(res.Header.Get(\"Retry-After\"), 10, 64)\n\t\t\tlog.Printf(\"[zd_ticket_metrics_service][getAllTicketMetrics] too many requests. Wait for %v seconds\\n\", after)\n\t\t\ttotalWaitTime += after\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ttime.Sleep(time.Duration(after) * time.Second)\n\t\t} else {\n\t\t\tif fieldName == \"ticket_metrics\" {\n\t\t\t\tresult = append(result, dataPerPage.TicketMetrics...)\n\t\t\t}\n\t\t\tcurrentPage = dataPerPage.NextPage\n\t\t}\n\t\tres, _ = c.request(\"GET\", dataPerPage.NextPage[apiStartIndex:], headers, bytes.NewReader(payload))\n\t\tdataPerPage = new(APIPayload)\n\t\terr = unmarshall(res, dataPerPage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tlog.Printf(\"[zd_ticket_metrics_service][getAllTicketMetrics] number of records pulled: %v\\n\", len(result))\n\tlog.Printf(\"[zd_ticket_metrics_service][getAllTicketMetrics] total waiting time due to rate limit: %v\\n\", totalWaitTime)\n\n\treturn result, err\n}", "func (a *SatellitesApiService) ListMetrics(ctx _context.Context, cloud string, satellite string, pool string) ([]Metric, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []Metric\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/v1/satellites/{cloud}/{satellite}/{pool}/metrics\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"cloud\"+\"}\", _neturl.QueryEscape(parameterToString(cloud, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"satellite\"+\"}\", _neturl.QueryEscape(parameterToString(satellite, \"\")) , -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"pool\"+\"}\", _neturl.QueryEscape(parameterToString(pool, \"\")) , -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v []Metric\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func MetricsHttp(w http.ResponseWriter, r *http.Request) {\n\tvar allOut []string\n\ttotal := big.NewFloat(0)\n\tfor _, v := range allWatching {\n\t\tif v.Balance == \"\" {\n\t\t\tv.Balance = \"0\"\n\t\t}\n\t\tbal := big.NewFloat(0)\n\t\tbal.SetString(v.Balance)\n\t\ttotal.Add(total, bal)\n\t\tallOut = append(allOut, fmt.Sprintf(\"%veth_balance{name=\\\"%v\\\",address=\\\"%v\\\"} %v\", prefix, v.Name, v.Address, v.Balance))\n\t}\n\tallOut = append(allOut, fmt.Sprintf(\"%veth_balance_total %0.18f\", prefix, total))\n\tallOut = append(allOut, fmt.Sprintf(\"%veth_load_seconds %0.2f\", prefix, loadSeconds))\n\tallOut = append(allOut, fmt.Sprintf(\"%veth_loaded_addresses %v\", prefix, totalLoaded))\n\tallOut = append(allOut, fmt.Sprintf(\"%veth_total_addresses %v\", prefix, len(allWatching)))\n\tfmt.Fprintln(w, strings.Join(allOut, \"\\n\"))\n}", "func PollArtiMetricsRestEndpoint(artDetails *jfauth.ServiceDetails, intervalSecs int) {\n\tjflog.Info(fmt.Sprintf(\"Polling api/v1/metrics REST end point\"))\n\turl := \"api/v1/metrics\"\n\tfor {\n\t\tresp, err := getHttpResp(artDetails, url)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"GET HTTP failed for url : %s, resp = %s\\n\", url, resp)\n\t\t\tjflog.Error(fmt.Sprintf(\"GET HTTP failed for url : %s, resp = %s\", url, resp))\n\t\t}\n\t\ttime.Sleep(time.Duration(intervalSecs) * time.Second)\n\t}\n}", "func (this *MCP342X) GetMeasurement() (int, error) {\n\tlog.Print(\"Starting polling for the result.\")\n\tresult := make([]byte, 3)\n\n\tfor {\n\t\terr := this.i2c.Read(result)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tif (result[2] & MCP342X_START) == 0x00 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// TODO: support all resolutions, it is only for 12 bit\n\tmeasurement := ((int(result[0]) & 0x3F) << 8) | int(result[1])\n\n\tif measurement > 2048-1 {\n\t\tmeasurement = measurement - 4096 - 1\n\t}\n\n\treturn measurement, nil\n}", "func MetricsHttp(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, strings.Join(outData, \"\\n\"))\n}", "func GetBubMeasurements(c *gin.Context) {\n\tdeviceName := c.Param(\"device_name\")\n\tstartTime, endTime := helpers.ParamReader(c.Param(\"start_time\"),\n\t\tc.Param(\"end_time\"))\n\tbubMeasurement, err := database.GetBubMeasurements(c, deviceName,\n\t\tstartTime, endTime)\n\tif err != nil {\n\t\tc.Status(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, bubMeasurement)\n\t}\n}", "func (c *PromMetricsClient) GetMetrics() ([]*Metric, error) {\n\tres, err := http.Get(c.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.StatusCode != 200 {\n\t\treturn nil, ErrUnexpectedHTTPStatusCode\n\t}\n\n\tdefer res.Body.Close()\n\treturn Parse(res.Body)\n}", "func UnmarshalMeasure(b []byte) (Measure, error) {\n\tvar measure Measure\n\tif err := json.Unmarshal(b, &measure); err != nil {\n\t\treturn measure, err\n\t}\n\treturn measure, nil\n}", "func (obj *GenericMeasure) GetInfoRaw(ctx context.Context) (json.RawMessage, error) {\n\tresult := &struct {\n\t\tInfo json.RawMessage `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}", "func (a *AGI) GetData(name string, timeout int, maxdigits int) (digit string, err error) {\n\treturn a.Command(\"GET DATA\", name, strconv.Itoa(timeout), strconv.Itoa(maxdigits)).ResStr()\n}", "func (ds *dockServer) GetMetrics(context.Context, *pb.GetMetricsOpts) (*pb.GenericResponse, error) {\n\treturn nil, &model.NotImplementError{\"method GetMetrics has not been implemented yet\"}\n}", "func getDataSetStats(w http.ResponseWriter, r *http.Request) {\n\torgID := domain.GetOrganizationID(r)\n\tspec := chi.URLParam(r, \"spec\")\n\tlog.Printf(\"Get stats for spec %s\", domain.LogUserInput(spec))\n\tstats, err := models.CreateDataSetStats(r.Context(), string(orgID), spec)\n\tif err != nil {\n\t\tif err == storm.ErrNotFound {\n\t\t\trender.Error(w, r, err, &render.ErrorConfig{\n\t\t\t\tStatusCode: http.StatusNotFound,\n\t\t\t\tMessage: fmt.Sprintf(\"Unable to retrieve dataset: %s\", spec),\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\trender.Error(w, r, err, &render.ErrorConfig{\n\t\t\tStatusCode: http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"Unable to create dataset stats: %s\", spec),\n\t\t})\n\n\t\treturn\n\t}\n\n\trender.JSON(w, r, stats)\n}", "func OpMetrics(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\n\t// Get Results Object\n\tres, err := metrics.GetUsageCpuMem(refStr)\n\n\tif err != nil && err.Error() != \"not found\" {\n\t\terr := APIErrQueryDatastore()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\n\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func (h *testMetricsHandler) GetRawMetrics(apiClient kubernetes.Interface, namespace, functionName string) ([]byte, error) {\n\tsvc, err := apiClient.CoreV1().Services(namespace).Get(functionName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tb, err := http.Get(svc.SelfLink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer b.Body.Close()\n\treturn ioutil.ReadAll(b.Body)\n}", "func Read(\n\tctx context.Context,\n\tendpoint *url.URL,\n\ttp auth.TokenProvider,\n\tlabels []prompb.Label,\n\tago, latency time.Duration,\n\tm instr.Metrics,\n\tl log.Logger,\n\ttls options.TLS,\n) (int, error) {\n\tvar (\n\t\trt http.RoundTripper\n\t\terr error\n\t)\n\n\tif endpoint.Scheme == transport.HTTPS {\n\t\trt, err = transport.NewTLSTransport(l, tls)\n\t\tif err != nil {\n\t\t\treturn 0, errors.Wrap(err, \"create round tripper\")\n\t\t}\n\n\t\trt = auth.NewBearerTokenRoundTripper(l, tp, rt)\n\t} else {\n\t\trt = auth.NewBearerTokenRoundTripper(l, tp, nil)\n\t}\n\n\tclient, err := promapi.NewClient(promapi.Config{\n\t\tAddress: endpoint.String(),\n\t\tRoundTripper: rt,\n\t})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tlabelSelectors := make([]string, len(labels))\n\tfor i, label := range labels {\n\t\tlabelSelectors[i] = fmt.Sprintf(`%s=\"%s\"`, label.Name, label.Value)\n\t}\n\n\tquery := fmt.Sprintf(\"{%s}\", strings.Join(labelSelectors, \",\"))\n\tts := time.Now().Add(ago)\n\n\tvalue, httpCode, _, err := api.Query(ctx, client, query, ts, false)\n\tif err != nil {\n\t\treturn httpCode, errors.Wrap(err, \"query request failed\")\n\t}\n\n\tvec := value.(model.Vector)\n\tif len(vec) != 1 {\n\t\treturn httpCode, errors.Errorf(\"expected one metric, got %d\", len(vec))\n\t}\n\n\tt := time.Unix(int64(vec[0].Value/1000), 0)\n\n\tdiffSeconds := time.Since(t).Seconds()\n\n\tm.MetricValueDifference.Observe(diffSeconds)\n\n\tif diffSeconds > latency.Seconds() {\n\t\treturn httpCode, errors.Errorf(\"metric value is too old: %2.fs\", diffSeconds)\n\t}\n\n\treturn httpCode, nil\n}", "func TestGetMetrics(t *testing.T) {\n\t// set up test server and mocked LogStore\n\tmockLogStore := new(MockedLogStore)\n\tserver := newTestServer(mockLogStore)\n\ttestServer := httptest.NewServer(server.server.Handler)\n\tdefer testServer.Close()\n\tclient := testServer.Client()\n\n\t// Make a first call to a resource to make metrics middleware record some\n\t// stats. Prior to that, no stats will have been saved.\n\tresp, _ := client.Get(testServer.URL + \"/metrics\")\n\trequire.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected status code\")\n\trequire.Equalf(t, \"\", readBody(t, resp), \"expected first /metrics call to be empty\")\n\n\tresp, _ = client.Get(testServer.URL + \"/metrics\")\n\trequire.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected status code\")\n\trequire.Containsf(t, readBody(t, resp), `total_requests{method=\"GET\",path=\"/metrics\",statusCode=\"200\"} 1`, \"missing expected metric\")\n}", "func (d *Driver) Measure() error {\n\tif d.IsImporting() {\n\t\treturn errors.New(\"importing\")\n\t}\n\t// write measure request\n\treturn d.write(newMeasureRequest())\n}", "func GetTotalSupply(w http.ResponseWriter, r *http.Request) {\n\n\t// Add header so that received knows they're receiving JSON\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// Retrieving name of node from query request\n\tnodeName := r.URL.Query().Get(\"name\")\n\tconfirmation, socket := checkNodeName(nodeName)\n\tif confirmation == false {\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Node name requested doesn't exist\"})\n\t\treturn\n\t}\n\n\trecvHeight := r.URL.Query().Get(\"height\")\n\theight := checkHeight(recvHeight)\n\tif height == -1 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Unexepcted value found, height needs to be string of int!\"})\n\t\treturn\n\t}\n\n\t// Attempt to load connection with staking client\n\tconnection, so := loadStakingClient(socket)\n\n\t// Close connection once code underneath executes\n\tdefer connection.Close()\n\n\t// If null object was retrieved send response\n\tif so == nil {\n\n\t\t// Stop code here faild to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to establish connection using socket : \" + socket})\n\t\treturn\n\t}\n\n\t// Using Oasis API to return total supply of tokens at specific block height\n\ttotalSupply, err := so.TotalSupply(context.Background(), height)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to get TotalSupply!\"})\n\t\tlgr.Error.Println(\n\t\t\t\"Request at /api/staking/totalsupply failed to retrieve \"+\n\t\t\t\t\"totalsupply : \", err)\n\t\treturn\n\t}\n\n\tlgr.Info.Println(\"Request at /api/staking/totalsupply responding with \" +\n\t\t\"TotalSupply!\")\n\tjson.NewEncoder(w).Encode(responses.QuantityResponse{Quantity: totalSupply})\n}", "func (c *HTTPClient) Query(q *Query, timeout time.Duration) (\n res *QueryResponse, err error) {\n\n if q == nil {\n err = fmt.Errorf(\"kairosdb: nil query passed\")\n return\n }\n payload, err := json.Marshal(q)\n if err != nil {\n return\n }\n\n res = &QueryResponse{}\n glog.V(3).Infof(\"querying metric: %s\", string(payload))\n reader := ioutil.NopCloser(bytes.NewReader(payload))\n err = c.backend.Call(\"POST\", c.url+\"/api/v1/datapoints/query\", reader,\n timeout, http.StatusOK, res)\n if err != nil {\n return\n }\n\n glog.V(3).Infof(\"response from query: %+v\", res)\n return\n}", "func (d *Dao) ReadHumiture() (resp interface{}, err error) {\n\treq := SensorHumitureUnit.Request()\n\toutput, err := send(d, req.Bytes())\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn resp, err\n\t}\n\thumidity := binary.BigEndian.Uint16(output[1:3])\n\ttemperature := binary.BigEndian.Uint16(output[3:6])\n\tresp = []float64{dividedByTen(humidity), dividedByTen(temperature)}\n\treturn resp, nil\n}", "func (m Metric) GetMeasurements(start int64, end int64) (table *DataTable, err os.Error) {\n\n\ttables := []*DataTable{}\n\n\tnames := m.filenames(start*1000000000, end*1000000000)\n\tfor _, name := range names {\n\t\tfile, err := OpenFile(name)\n\t\tif err == nil {\n\t\t\tdefer file.Close()\n\t\t\tfullTable, err := file.ReadAggregatedDataTable(m)\n\t\t\tif err == nil {\n\t\t\t\t// todo: don't hardcode a 1 here\n\t\t\t\ttable := fullTable.Columnify(1)\n\t\t\t\ttables = append(tables, &table)\n\t\t\t}\n\t\t}\n\t}\n\tif len(tables) == 0 {\n\t\treturn nil, err\n\t}\n\tr := tables[0]\n\tfor i, t := range tables {\n\t\tif i > 0 {\n\t\t\tr, err = t.Append(r)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn r, nil\n}", "func (obj *GenericMeasure) GetInfo(ctx context.Context) (*NxInfo, error) {\n\tresult := &struct {\n\t\tInfo *NxInfo `json:\"qInfo\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetInfo\", result)\n\treturn result.Info, err\n}", "func getMetrics(_ string) []string {\n\tvar (\n\t\terr error\n\t\tsession *Session\n\t\tclient orchestrator.OrchestratorClient\n\t\tres *orchestrator.ListMetricsResponse\n\t)\n\n\tif session, err = ContinueSession(); err != nil {\n\t\tfmt.Printf(\"Error while retrieving the session. Please re-authenticate.\\n\")\n\t\treturn nil\n\t}\n\n\tclient = orchestrator.NewOrchestratorClient(session)\n\n\tif res, err = client.ListMetrics(context.Background(), &orchestrator.ListMetricsRequest{}); err != nil {\n\t\treturn []string{}\n\t}\n\n\tvar metrics []string\n\tfor _, v := range res.Metrics {\n\t\tmetrics = append(metrics, fmt.Sprintf(\"%s\\t%s: %s\", v.Id, v.Name, v.Description))\n\t}\n\n\treturn metrics\n}", "func (a *Client) GetResourcesIDMeasures(params *GetResourcesIDMeasuresParams) (*GetResourcesIDMeasuresOK, *GetResourcesIDMeasuresNoContent, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetResourcesIDMeasuresParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetResourcesIDMeasures\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/resources/{id}/measures\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetResourcesIDMeasuresReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tswitch value := result.(type) {\n\tcase *GetResourcesIDMeasuresOK:\n\t\treturn value, nil, nil\n\tcase *GetResourcesIDMeasuresNoContent:\n\t\treturn nil, value, nil\n\t}\n\treturn nil, nil, nil\n\n}", "func GetMeasurementOverviewDetails(deviceEUI string, config config.Database) (*structs.MeasurementOverviewDetails, error) {\n\n\tdeviceEUIBytes, err := hex.DecodeString(deviceEUI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb, err := openConnection(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer db.Close()\n\n\trows, err := db.Query(sqlStatementMeasurementOverviewDetails, deviceEUIBytes)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !rows.Next() {\n\t\t// no measurements found: return nil\n\t\treturn nil, nil\n\t}\n\n\tvar oldestMeasurementTime, newestMeasurementTime time.Time\n\tvar numberOfMeasurements int\n\terr = rows.Scan(&oldestMeasurementTime, &newestMeasurementTime, &numberOfMeasurements)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := structs.MeasurementOverviewDetails{\n\t\tOldestMeasurementTime: oldestMeasurementTime,\n\t\tNewestMeasurementTime: newestMeasurementTime,\n\t\tNumberOfMeasurements: numberOfMeasurements,\n\t}\n\n\treturn &result, nil\n}", "func (r *DeviceManagementReportsRequest) Get(ctx context.Context) (resObj *DeviceManagementReports, err error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\terr = r.JSONRequest(ctx, \"GET\", query, nil, &resObj)\n\treturn\n}", "func Metrics(cl client.Client) (*v1.Metrics, error) {\n\n\t// Get metrics\n\treq, err := http.NewRequest(\"GET\", cl.MetronomeUrl()+\"/v1/metrics\", nil)\n\tres, err := cl.DoRequest(req)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to fetch metrics due to \" + err.Error())\n\t}\n\n\t// Parse metrics\n\tvar metrics v1.Metrics\n\tif err = json.Unmarshal(res, &metrics); err != nil {\n\t\treturn nil, errors.New(\"failed to unmarshal JSON data due to \" + err.Error())\n\t}\n\n\treturn &metrics, nil\n}", "func getMetric(c *gin.Context) {\n\tparams, err := parseMetricParams(c)\n\n\tif err != nil {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\t// TODO: Allow string value comparisons as well!\n\tdocs, err := getDataOverRange(mongoSession, biModule.Rules[params.RuleIndex],\n\t\tparams.Granularity, params.Start, params.End, params.Value)\n\tif err != nil {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tc.JSON(200, docs)\n}", "func (obj *GenericMeasure) GetMeasure(ctx context.Context) (*NxLibraryMeasureDef, error) {\n\tresult := &struct {\n\t\tMeasure *NxLibraryMeasureDef `json:\"qMeasure\"`\n\t}{}\n\terr := obj.RPC(ctx, \"GetMeasure\", result)\n\treturn result.Measure, err\n}", "func (ds *MetricsDataSource) QueryData() (SolrStatisticData, error) {\n\tresp, err := http.Get(\"http://\" + ds.SolrUrl + \"admin/stats.jsp\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\treturn nil, nil\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := SolrResponse{}\n\terr = xml.Unmarshal(body, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := make(SolrStatisticData, len(response.SolrInfo.QueryHandler.QueryHandlerInfo)+len(response.SolrInfo.UpdateHandler.QueryHandlerInfo)+len(response.SolrInfo.CacheHandler.QueryHandlerInfo)+1)\n\tparseQueryHandlers(response.SolrInfo.QueryHandler.QueryHandlerInfo, data)\n\tparseQueryHandlers(response.SolrInfo.UpdateHandler.QueryHandlerInfo, data)\n\tparseQueryHandlers(response.SolrInfo.CacheHandler.QueryHandlerInfo, data)\n\n\tif stat, err := ds.QuerySystemData(); err == nil {\n\t\tdata[\"solr\"] = stat\n\t}\n\treturn data, nil\n}", "func (c *Container) GetClusterMetric(ctx echo.Context) error {\n metricsParam := strings.Split(ctx.QueryParam(\"metrics\"), \",\")\n clusterType := ctx.QueryParam(\"cluster_type\")\n nodeParam := ctx.QueryParam(\"node_name\")\n nodeList := []string{nodeParam}\n var err error = nil\n if nodeParam == \"\" {\n if clusterType == \"\" {\n nodeList, err = getNodes()\n } else if clusterType == \"PRIMARY\" {\n nodeList, err = getNodes(\"PRIMARY\")\n } else if clusterType == \"READ_REPLICA\" {\n nodeList, err = getNodes(\"READ_REPLICA\")\n }\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n }\n hostToUuid, err := helpers.GetHostToUuidMap(helpers.HOST)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n // in case of errors parsing start/end time, set default start = 1 hour ago, end = now\n startTime, err := strconv.ParseInt(ctx.QueryParam(\"start_time\"), 10, 64)\n if err != nil {\n now := time.Now()\n startTime = now.Unix()\n }\n endTime, err := strconv.ParseInt(ctx.QueryParam(\"end_time\"), 10, 64)\n if err != nil {\n now := time.Now()\n endTime = now.Unix() - 60*60\n }\n\n metricResponse := models.MetricResponse{\n Data: []models.MetricData{},\n StartTimestamp: startTime,\n EndTimestamp: endTime,\n }\n\n session, err := c.GetSession()\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n\n for _, metric := range metricsParam {\n // Read from the table.\n var ts int64\n var value int\n var details string\n // need node uuid\n switch metric {\n case \"READ_OPS_PER_SEC\":\n rawMetricValues, err := getRawMetricsForAllNodes(READ_COUNT_METRIC,\n nodeList, hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n rateMetrics := convertRawMetricsToRates(rawMetricValues)\n nodeMetricValues := reduceGranularityForAllNodes(startTime, endTime,\n rateMetrics, GRANULARITY_NUM_INTERVALS, true)\n metricValues := calculateCombinedMetric(nodeMetricValues, false)\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n case \"WRITE_OPS_PER_SEC\":\n rawMetricValues, err := getRawMetricsForAllNodes(WRITE_COUNT_METRIC,\n nodeList, hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n rateMetrics := convertRawMetricsToRates(rawMetricValues)\n nodeMetricValues := reduceGranularityForAllNodes(startTime, endTime,\n rateMetrics, GRANULARITY_NUM_INTERVALS, true)\n metricValues := calculateCombinedMetric(nodeMetricValues, false)\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n case \"CPU_USAGE_USER\":\n metricValues, err := getAveragePercentageMetricData(\"cpu_usage_user\",\n nodeList, hostToUuid, startTime, endTime, session, true)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n case \"CPU_USAGE_SYSTEM\":\n metricValues, err := getAveragePercentageMetricData(\"cpu_usage_system\",\n nodeList, hostToUuid, startTime, endTime, session, true)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n case \"DISK_USAGE_GB\":\n // For disk usage, we assume every node reports the same metrics\n query := fmt.Sprintf(QUERY_FORMAT, \"system.metrics\", \"total_disk\",\n startTime*1000, endTime*1000)\n iter := session.Query(query).Iter()\n values := [][]float64{}\n for iter.Scan(&ts, &value, &details) {\n values = append(values,\n []float64{float64(ts) / 1000,\n float64(value) / helpers.BYTES_IN_GB})\n }\n if err := iter.Close(); err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n sort.Slice(values, func(i, j int) bool {\n return values[i][0] < values[j][0]\n })\n query = fmt.Sprintf(QUERY_FORMAT, \"system.metrics\", \"free_disk\",\n startTime*1000, endTime*1000)\n iter = session.Query(query).Iter()\n freeValues := [][]float64{}\n for iter.Scan(&ts, &value, &details) {\n freeValues = append(freeValues,\n []float64{float64(ts) / 1000,\n float64(value) / helpers.BYTES_IN_GB})\n }\n if err := iter.Close(); err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n sort.Slice(freeValues, func(i, j int) bool {\n return freeValues[i][0] < freeValues[j][0]\n })\n\n // assume query results for free and total disk have the same timestamps\n for index, pair := range freeValues {\n if index >= len(values) {\n break\n }\n values[index][1] -= float64(pair[1])\n }\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: reduceGranularity(startTime, endTime, values,\n GRANULARITY_NUM_INTERVALS, true),\n })\n case \"PROVISIONED_DISK_SPACE_GB\":\n query := fmt.Sprintf(QUERY_FORMAT, \"system.metrics\", \"total_disk\",\n startTime*1000, endTime*1000)\n iter := session.Query(query).Iter()\n values := [][]float64{}\n for iter.Scan(&ts, &value, &details) {\n values = append(values,\n []float64{float64(ts) / 1000,\n float64(value) / helpers.BYTES_IN_GB})\n }\n if err := iter.Close(); err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n sort.Slice(values, func(i, j int) bool {\n return values[i][0] < values[j][0]\n })\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: reduceGranularity(startTime, endTime, values,\n GRANULARITY_NUM_INTERVALS, true),\n })\n case \"AVERAGE_READ_LATENCY_MS\":\n rawMetricValuesCount, err := getRawMetricsForAllNodes(READ_COUNT_METRIC,\n nodeList, hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n\n rawMetricValuesSum, err := getRawMetricsForAllNodes(READ_SUM_METRIC,\n nodeList, hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n\n rateMetricsCount := convertRawMetricsToRates(rawMetricValuesCount)\n rateMetricsSum := convertRawMetricsToRates(rawMetricValuesSum)\n\n rateMetricsCountReduced := reduceGranularityForAllNodes(startTime, endTime,\n rateMetricsCount, GRANULARITY_NUM_INTERVALS, false)\n\n rateMetricsSumReduced := reduceGranularityForAllNodes(startTime, endTime,\n rateMetricsSum, GRANULARITY_NUM_INTERVALS, false)\n\n rateMetricsCountCombined :=\n calculateCombinedMetric(rateMetricsCountReduced, false)\n rateMetricsSumCombined :=\n calculateCombinedMetric(rateMetricsSumReduced, false)\n\n latencyMetric :=\n divideMetricForAllNodes([][][]float64{rateMetricsSumCombined},\n [][][]float64{rateMetricsCountCombined})\n\n metricValues := latencyMetric[0]\n // Divide everything by 1000 to convert from microseconds to milliseconds\n divideMetricByConstant(metricValues, 1000)\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n case \"AVERAGE_WRITE_LATENCY_MS\":\n rawMetricValuesCount, err := getRawMetricsForAllNodes(WRITE_COUNT_METRIC,\n nodeList, hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n\n rawMetricValuesSum, err := getRawMetricsForAllNodes(WRITE_SUM_METRIC,\n nodeList, hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n\n rateMetricsCount := convertRawMetricsToRates(rawMetricValuesCount)\n rateMetricsSum := convertRawMetricsToRates(rawMetricValuesSum)\n\n rateMetricsCountReduced := reduceGranularityForAllNodes(startTime, endTime,\n rateMetricsCount, GRANULARITY_NUM_INTERVALS, false)\n\n rateMetricsSumReduced := reduceGranularityForAllNodes(startTime, endTime,\n rateMetricsSum, GRANULARITY_NUM_INTERVALS, false)\n\n rateMetricsCountCombined :=\n calculateCombinedMetric(rateMetricsCountReduced, false)\n rateMetricsSumCombined :=\n calculateCombinedMetric(rateMetricsSumReduced, false)\n\n latencyMetric :=\n divideMetricForAllNodes([][][]float64{rateMetricsSumCombined},\n [][][]float64{rateMetricsCountCombined})\n\n metricValues := latencyMetric[0]\n // Divide everything by 1000 to convert from microseconds to milliseconds\n divideMetricByConstant(metricValues, 1000)\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n case \"TOTAL_LIVE_NODES\":\n rawMetricValues, err := getRawMetricsForAllNodes(\"node_up\", nodeList,\n hostToUuid, startTime, endTime, session, false)\n if err != nil {\n return ctx.String(http.StatusInternalServerError, err.Error())\n }\n reducedMetric := reduceGranularityForAllNodes(startTime, endTime,\n rawMetricValues, GRANULARITY_NUM_INTERVALS, true)\n metricValues := calculateCombinedMetric(reducedMetric, false)\n // In cases where there is no data, set to 0\n for i, metric := range metricValues {\n if len(metric) < 2 {\n metricValues[i] = append(metricValues[i], 0)\n }\n }\n metricResponse.Data = append(metricResponse.Data, models.MetricData{\n Name: metric,\n Values: metricValues,\n })\n }\n }\n return ctx.JSON(http.StatusOK, metricResponse)\n}", "func (s *Server) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treturn s.querynode.GetMetrics(ctx, req)\n}", "func SendProcessMetrics() {\n\n c := h.NewClient(ip, port)\n\n processMetrics := s.ProcessMeasurement{\n TimeSlice: timeSlice,\n CpuUsed: cpu,\n MemUsed: mem,\n }\n\n\n path := fmt.Sprintf(\"/v1/metrics/nodes/%s/process/%s/\", nodeName, processName)\n req, _ := c.NewRequest(\"POST\", path, processMetrics)\n\n\n var processMeasurement s.ProcessMeasurement\n\n c.Do(req, &processMeasurement)\n\n\n //fmt.Printf(\"PROCESS MEASUREMENT SENT: %s\\n\", u.PrettyPrint(processMeasurement))\n\n}", "func (e Entry) GetMetrics(timeout time.Duration, h heimdall.Doer, debug bool) (Metrics, error) {\n\tvar m Metrics\n\n\t// Let's set the stuff we know already.\n\tm.Address = e.Address\n\tm.Regexp = e.Regexp\n\tm.CapturedAt = time.Now().UTC()\n\n\t// Set a timeout.\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\t// Setup the request.\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, e.Address, nil)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\tif debug {\n\t\tfmt.Printf(\"%#v\\n\", req)\n\t}\n\n\t// Let's do the request.\n\tstart := time.Now()\n\tres, err := h.Do(req)\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\t// We don't need the body unless we've got a regexp.\n\tif e.Regexp != \"\" {\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\treturn m, err\n\t\t}\n\t\t// Do the regexp here and assign the value.\n\t\tmatch, _ := regexp.MatchString(e.Regexp, string(body))\n\t\tm.RegexpStatus = match\n\t}\n\ttook := time.Since(start)\n\n\t// Set the last few values\n\tm.StatusCode = res.StatusCode\n\tm.ResponseTime = took\n\n\tif debug {\n\t\tfmt.Printf(\"Result: %#v\\n\", res)\n\t\tfmt.Printf(\"Time Taken: %s\\n\", took)\n\t\tfmt.Printf(\"Metrics: %#v\\n\", m)\n\t}\n\n\tif ctx.Err() != nil {\n\t\treturn m, errors.New(\"context deadline exceeded\")\n\t}\n\treturn m, nil\n}", "func (s *RestServer) getL2FlowPerformanceMetricsHandler(r *http.Request) (interface{}, error) {\n\tlog.Infof(\"Got GET request L2FlowPerformanceMetrics/%s\", mux.Vars(r)[\"Meta.Name\"])\n\treturn nil, nil\n}", "func (client DDMetricsClient) GetInfo() (*DDInfo, error) {\n\tinfoURL := client.endpoint\n\tinfoURL.Path = \"/info\"\n\tresp, err := client.httpClient.Get(infoURL.String())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinfo := DDInfo{}\n\terr = json.NewDecoder(resp.Body).Decode(&info)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogrus.Debugln(\"Received /info from Deepdetect :\", info)\n\treturn &info, nil\n}", "func (a *AllApiService) MetricsGetEdgeDeviceMetrics(ctx _context.Context, body MetricsGetEdgeDeviceMetrics) ([]MetricsGetEdgeDeviceMetricsResultItem, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []MetricsGetEdgeDeviceMetricsResultItem\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/metrics/getEdgeDeviceMetrics\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v []MetricsGetEdgeDeviceMetricsResultItem\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (y *YarnMetrics) getMetrics() *NMMetrics {\n\tjmxResp := &JmxResp{}\n\terr := y.requestUrl(metricsSuffix, jmxResp)\n\tif err != nil {\n\t\tklog.V(5).Infof(\"request nodemanager metrics err: %v\", err)\n\t\treturn nil\n\t}\n\tif len(jmxResp.Beans) == 0 {\n\t\tklog.V(5).Infof(\"request nodemanager metrics, empty beans\")\n\t\treturn nil\n\t}\n\treturn &jmxResp.Beans[0]\n}", "func (c *Client) Read(req *remote.ReadRequest) ([]map[string]interface{}, error) {\n\tctx := context.Background()\n\tquerier := req.Queries[0]\n\tquery := elastic.NewBoolQuery()\n\n\tfor _, matcher := range querier.Matchers {\n\t\tquery = query.Must(elastic.NewTermQuery(matcher.Name, matcher.Value))\n\t}\n\n\t// building elasticsearch query\n\tquery = query.Filter(elastic.\n\t\tNewRangeQuery(\"timestamp\").\n\t\tFrom(querier.StartTimestampMs).\n\t\tTo(querier.EndTimestampMs))\n\n\tsearchResult, err := c.client.\n\t\tSearch().\n\t\tIndex(c.esIndex).\n\t\tQuery(query).\n\t\tSize(1000).\n\t\tSort(\"timestamp\", true).\n\t\tDo(ctx)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar dataPoints []map[string]interface{}\n\n\t// parsing elasticsearch hits to array with datapoints\n\tif searchResult.Hits.TotalHits > 0 {\n\t\tfmt.Printf(\"Found a total of %d data points\\n\", searchResult.Hits.TotalHits)\n\n\t\tfor _, hit := range searchResult.Hits.Hits {\n\t\t\tvar dataPoint map[string]interface{}\n\t\t\tjson.Unmarshal(*hit.Source, &dataPoint)\n\t\t\tdataPoints = append(dataPoints, dataPoint)\n\t\t}\n\t} else {\n\t\treturn nil, newErrNoDataPointsFound(\"Found no metrics\")\n\t}\n\n\treturn dataPoints, nil\n}", "func (h *Handler) GetMetricSum(w http.ResponseWriter, r *http.Request) {\n\tvar b []byte\n\tkey := mux.Vars(r)[\"key\"]\n\n\tresp := response{}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tcachedVal, ok := h.MetricsCache.Get(key)\n\tif !ok {\n\t\tb, _ = json.Marshal(resp)\n\t\tw.Write(b)\n\t\treturn\n\t}\n\n\tcachedList := cachedVal.(*list.List)\n\tnewList := list.New()\n\n\tfor element := cachedList.Front(); element != nil; element = element.Next() {\n\t\tdata := element.Value.(metricData)\n\t\tmetricTime := data.time\n\t\tvalidMetricTime := metricTime.Add(h.InstrumentationTimeInSeconds * time.Second)\n\n\t\tif validMetricTime.After(time.Now()) {\n\t\t\tresp.Value = resp.Value + data.value\n\t\t\tdata := metricData{value: data.value, time: data.time}\n\n\t\t\tnewList.PushBack(data)\n\t\t} else {\n\t\t\th.MetricsCache.Set(key, newList, cache.NoExpiration)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tb, _ = json.Marshal(resp)\n\tw.Write(b)\n\n\treturn\n}", "func (r *CompanyUnitsOfMeasureCollectionRequest) Get(ctx context.Context) ([]UnitOfMeasure, error) {\n\treturn r.GetN(ctx, 0)\n}", "func (serv MetricsService) Metrics(w http.ResponseWriter, r *http.Request) {\n\tsetAccessControlHeaders(w)\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tmetricNames := serv.Storage.GetLabelValuesForLabelName(clientmodel.MetricNameLabel)\n\tsort.Sort(metricNames)\n\tresultBytes, err := json.Marshal(metricNames)\n\tif err != nil {\n\t\tglog.Error(\"Error marshalling metric names: \", err)\n\t\thttpJSONError(w, fmt.Errorf(\"Error marshalling metric names: %s\", err), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Write(resultBytes)\n}", "func (s *MeasurementService) GetMeasurementSeries(ctx context.Context, opt *MeasurementSeriesOptions) (*MeasurementSeriesGroup, *Response, error) {\n\tu := \"measurement/measurements/series\"\n\n\tqueryParams, err := addOptions(\"\", opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tLogger.Infof(\"query Parameters: %s\", queryParams)\n\n\treq, err := s.client.NewRequest(\"GET\", u, queryParams, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tdata := new(MeasurementSeriesGroup)\n\n\tresp, err := s.client.Do(ctx, req, data)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\t// Add extra information to the results\n\tdata.DeviceID = opt.Source\n\n\treturn data, resp, nil\n}", "func TestGetMetrics(t *testing.T) {\n\n\t//\t\tCreating mock request with custom params\n\t//\t\tand checking for error\n\trequest, err := http.NewRequest(\"GET\", \"/fizzbuzz-metrics\", nil)\n\tif err != nil {\n\t\tt.Errorf(\"GetMetrics() failed because of bad request: %v\", err)\n\t}\n\n\t//\t\tCreating a HTTP recorder for the test\n\trecorder := httptest.NewRecorder()\n\n\t//\t\tHitting endpoint\n\trouter := httprouter.New()\n\trouter.GET(\"/fizzbuzz-metrics\", GetMetrics)\n\trouter.ServeHTTP(recorder, request)\n\n\t//\t\tCheck status code\n\tif recorder.Code != http.StatusOK {\n\t\tt.Errorf(\"GetMetrics() failed because of status code: got %v instead of %v\", recorder.Code, http.StatusOK)\n\t}\n\n\t//\t\tCheck body\n\tgot := recorder.Body.String()\n\tif got == \"\" {\n\t\tt.Error(\"GetMetrics() failed because of empty body.\")\n\t}\n}", "func (c *Client) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {\n\treq = typeutil.Clone(req)\n\tcommonpbutil.UpdateMsgBase(\n\t\treq.GetBase(),\n\t\tcommonpbutil.FillMsgBaseFromClient(paramtable.GetNodeID()))\n\treturn wrapGrpcCall(ctx, c, func(client querypb.QueryNodeClient) (*milvuspb.GetMetricsResponse, error) {\n\t\treturn client.GetMetrics(ctx, req)\n\t})\n}", "func (a *Client) Metrics(params *MetricsParams, authInfo runtime.ClientAuthInfoWriter) (*MetricsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewMetricsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"metrics\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/system/metrics\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &MetricsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*MetricsOK), nil\n\n}", "func (c *CAdvisor) GetMetrics() (*Metrics, error) {\n\tlog.Printf(\"[DEBUG] [cadvisor] Get metrics\")\n\tnodeSpec, err := c.Client.MachineInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive machine info : %#v\",\n\t\tnodeSpec)\n\tnodeInfo, err := c.Client.ContainerInfo(\"/\", c.Query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive container info : %#v\",\n\t\tnodeInfo)\n\tcontainersInfo, err := c.Client.AllDockerContainers(c.Query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] [cadvisor] Receive all docker containers : %#v\",\n\t\tcontainersInfo)\n\tmetrics := &Metrics{\n\t\tNodeSpec: nodeSpec,\n\t\tNodeInfo: nodeInfo,\n\t\tContainersInfo: containersInfo,\n\t}\n\t//log.Printf(\"[INFO] [cadvisor] Metrics: %#v\", metrics)\n\treturn metrics, nil\n}", "func GetChartData(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"content-type\", \"application/json\")\n\n\tvar rr models.ResponseResult\n\tvar user models.User\n\tif ok := user.GetLoggedIn(ctx.Get(r, \"jwtToken\")); !ok {\n\t\trr = models.ResponseResult{\n\t\t\tError: \"Token is invalid!\",\n\t\t\tResult: \"\",\n\t\t}\n\t\t_ = json.NewEncoder(w).Encode(rr)\n\t\treturn\n\t}\n\n\tvar chartDatReq models.ChartDataRequest\n\tbody, _ := ioutil.ReadAll(r.Body)\n\n\t// log.Println(\"-===================> \", string(body))\n\n\terr := json.Unmarshal(body, &chartDatReq)\n\n\tif err != nil {\n\t\trr.Error = err.Error()\n\t\t_ = json.NewEncoder(w).Encode(rr)\n\t\treturn\n\t}\n\n\t// log.Println(chartDatReq)\n\tdataFetchResult := chartDatReq.Get()\n\t_ = json.NewEncoder(w).Encode(dataFetchResult)\n\treturn\n\n}", "func serveMetrics(w http.ResponseWriter, r *http.Request) {\n\tvar state []byte\n\tvar stateCode int\n\tvar dev string\n\tfmt.Fprintf(w, \"# metric values: 1 - clean, 0 - degraded\\n\")\n\tfor _, file := range mdFiles {\n\t\tstate, _ = ioutil.ReadFile(fmt.Sprintf(\"%s/md/array_state\", file))\n\t\tdev = filepath.Base(file)\n\t\tif strings.TrimSpace(string(state)) == \"clean\" {\n\t\t\tstateCode = 1\n\t\t} else {\n\t\t\tstateCode = 0\n\t\t}\n\t\tfmt.Fprintf(w, \"md_state{host=\\\"%s\\\",dev=\\\"%s\\\"} %d\\n\", host, dev, stateCode)\n\t}\n}", "func (e *HueEmulator) getDevices(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\te.logger.Debug(\"Devices list is requested\")\n\tresponse := make(map[string]*Light)\n\n\tfor _, v := range e.devices {\n\t\tresponse[v.internalHash] = getDevice(v)\n\t}\n\n\te.sendJSON(w, &LightsList{\n\t\tLights: response,\n\t})\n}", "func getInfo(url string) []Res {\n\n\tres, err := http.Get(url)\n\tcheck(err)\n\tinfo, err := ioutil.ReadAll(res.Body)\n\tres.Body.Close()\n\tcheck(err)\n\n\t// to struct\n\tvar data R1\n\terr = json.Unmarshal(info, &data)\n\tcheck(err)\n\tfCast := data.D1.Location.Forecast\n\terr = ioutil.WriteFile(\"response\", info, 0644)\n\treturn fCast\n\n}", "func get(data interface{}) {\n\n\t//GET API for fetching only GGUS alerts.\n\tapiurl := configJSON.CMSMONURL + \"/api/v1/alerts?active=true&silenced=false&inhibited=false&unprocessed=false\"\n\n\treq, err := http.NewRequest(\"GET\", apiurl, nil)\n\treq.Header.Add(\"Accept-Encoding\", \"identity\")\n\treq.Header.Add(\"Accept\", \"application/json\")\n\tif configJSON.Token != \"\" {\n\t\ttoken = TokenManager.ReadToken(configJSON.Token)\n\t\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"bearer %s\", token))\n\t}\n\n\ttimeout := time.Duration(configJSON.httpTimeout) * time.Second\n\tclient := &http.Client{Timeout: timeout}\n\tif token != \"\" {\n\t\trootCAs, err := TokenManager.LoadCAs(configJSON.Verbose)\n\t\tif err != nil {\n\t\t\tlog.Println(\"unable to load CERN ROOT CAs\", err)\n\t\t\treturn\n\t\t}\n\t\ttr, err := TokenManager.Transport(rootCAs, configJSON.Verbose)\n\t\tif err != nil {\n\t\t\tlog.Println(\"unable to initialize HTTP Transport\", err)\n\t\t\treturn\n\t\t}\n\t\tclient = &http.Client{Transport: tr}\n\t}\n\n\tif configJSON.Verbose > 1 {\n\t\tlog.Println(\"URL\", apiurl)\n\t\tdump, err := httputil.DumpRequestOut(req, true)\n\t\tif err == nil {\n\t\t\tlog.Println(\"Request: \", string(dump))\n\t\t}\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tbyteValue, err := io.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tlog.Printf(\"Unable to read %s JSON Data from AlertManager GET API, error: %v\\n\", service, err)\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(byteValue, &data)\n\tif err != nil {\n\t\tif configJSON.Verbose > 0 {\n\t\t\tlog.Println(string(byteValue))\n\t\t}\n\t\tlog.Fatalf(\"Unable to parse %s JSON Data from AlertManager GET API, error: %v\\n\", service, err)\n\t}\n\n\tif configJSON.Verbose > 1 {\n\t\tdump, err := httputil.DumpResponse(resp, true)\n\t\tif err == nil {\n\t\t\tlog.Println(\"Response: \", string(dump))\n\t\t}\n\t}\n\n}", "func TestGetAvgSpeed(t *testing.T) {\n\tqueryCondition := &api.QueryCondition{}\n\tavgSpeedDetails, err := testCli.GetAvgSpeed(queryCondition)\n\n\tdata, _ := json.Marshal(avgSpeedDetails)\n\tt.Logf(\"avgSpeedDetails: %s\", string(data))\n\tcheckClientErr(t, \"GetAvgSpeed\", err)\n}", "func GetTemperatureStat(rw http.ResponseWriter) error {\n\ttempstat, err := host.SensorsTemperatures()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn share.JSONResponse(tempstat, rw)\n}", "func ExampleMetricsClient_List_getMetricForData() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclient, err := armmonitor.NewMetricsClient(cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.List(ctx, \"subscriptions/b324c52b-4073-4807-93af-e07d289c093e/resourceGroups/test/providers/Microsoft.Storage/storageAccounts/larryshoebox/blobServices/default\", &armmonitor.MetricsClientListOptions{Timespan: to.Ptr(\"2017-04-14T02:20:00Z/2017-04-14T04:20:00Z\"),\n\t\tInterval: to.Ptr(\"PT1M\"),\n\t\tMetricnames: nil,\n\t\tAggregation: to.Ptr(\"Average,count\"),\n\t\tTop: to.Ptr[int32](3),\n\t\tOrderby: to.Ptr(\"Average asc\"),\n\t\tFilter: to.Ptr(\"BlobType eq '*'\"),\n\t\tResultType: nil,\n\t\tMetricnamespace: to.Ptr(\"Microsoft.Storage/storageAccounts/blobServices\"),\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func (c *Client) QueryMetrics(query string) (*VectorQueryResponse, error) {\n\tvar result VectorQueryResponse\n\tresp, err := c.rc.R().\n\t\tSetResult(&result).\n\t\tSetQueryParam(\"query\", query).\n\t\tGet(\"/query\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.IsError() {\n\t\tlog.Errorf(string(resp.Body()))\n\t\treturn nil, fmt.Errorf(\"prometheus responded with unexpected status: %s\", resp.Status())\n\t}\n\n\treturn &result, nil\n}", "func getStats(url string) *grequests.Response {\n\tresp, err := grequests.Get(url, requestOptions)\n\t// you can modify the request by passing an optional RequestOptions struct\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to make request: \", err)\n\t}\n\treturn resp\n}", "func (a API) GetRawMempoolGetRes() (out *[]string, e error) {\n\tout, _ = a.Result.(*[]string)\n\te, _ = a.Result.(error)\n\treturn \n}", "func (client IotHubResourceClient) GetQuotaMetricsResponder(resp *http.Response) (result IotHubQuotaMetricInfoListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (a *AGI) GetAllData(name string, timeout int, maxdigits int) (status int, result int, digit string, value string, err error) {\n\treturn a.Command(\"GET DATA\", name, strconv.Itoa(timeout), strconv.Itoa(maxdigits)).ResStrAll()\n}", "func (s *AppEngineService) GetDevicesStats(realm string) (DevicesStats, error) {\n\tcallURL, _ := url.Parse(s.appEngineURL.String())\n\tcallURL.Path = path.Join(callURL.Path, fmt.Sprintf(\"/v1/%s/stats/devices\", realm))\n\tdecoder, err := s.client.genericJSONDataAPIGET(callURL.String(), 200)\n\tif err != nil {\n\t\treturn DevicesStats{}, err\n\t}\n\tvar responseBody struct {\n\t\tData DevicesStats `json:\"data\"`\n\t}\n\terr = decoder.Decode(&responseBody)\n\tif err != nil {\n\t\treturn DevicesStats{}, err\n\t}\n\n\treturn responseBody.Data, nil\n}", "func TestHttpJsonCassandraMultiValue(t *testing.T) {\n\tcassandra := genJolokiaClientStub(validCassandraMultiValueJSON, 200, Servers, []string{ReadLatencyMetric})\n\n\tvar acc testutil.Accumulator\n\terr := acc.GatherError(cassandra.Gather)\n\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, len(acc.Metrics))\n\n\tfields := map[string]interface{}{\n\t\t\"ReadLatency_999thPercentile\": 20.0,\n\t\t\"ReadLatency_99thPercentile\": 10.0,\n\t\t\"ReadLatency_Count\": 400.0,\n\t\t\"ReadLatency_DurationUnit\": \"microseconds\",\n\t\t\"ReadLatency_Max\": 30.0,\n\t\t\"ReadLatency_MeanRate\": 3.0,\n\t\t\"ReadLatency_Min\": 1.0,\n\t\t\"ReadLatency_RateUnit\": \"events/second\",\n\t}\n\n\ttags := map[string]string{\n\t\t\"cassandra_host\": \"10.10.10.10\",\n\t\t\"mname\": \"ReadLatency\",\n\t\t\"keyspace\": \"test_keyspace1\",\n\t\t\"scope\": \"test_table\",\n\t}\n\tacc.AssertContainsTaggedFields(t, \"cassandraTable\", fields, tags)\n}", "func GetReadingMaterialHandler(w http.ResponseWriter, r *http.Request) {\n\n}", "func GetAllBubMeasurements(c *gin.Context) {\n\tstartTime, endTime := helpers.ParamReader(c.Param(\"start_time\"),\n\t\tc.Param(\"end_time\"))\n\tbubMeasurements, err := database.GetAllBubMeasurements(c,\n\t\tstartTime, endTime)\n\tif err != nil {\n\t\tc.Status(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, bubMeasurements)\n\t}\n}", "func hostMetrics(host *Host, time int32) string {\n \n cpu := random(BigDogMinCPU,BigDogMaxCPU)\n disk := random(BigDogMinDisk,BigDogMaxDisk)\n mem := random(BigDogMinMem,BigDogMaxMem)\n json := fmt.Sprintf(`{\"series\" : \n [\n {\n \"metric\":\"system.cpu.stolen\",\n \"points\":[[%d,0]],\n \"type\":\"gauge\",\n \"host\":\"%s\",\n \"tags\":[\"%s:%s\",\"%s:%s\"]\n },\n {\n \"metric\":\"system.cpu.user\",\n \"points\":[[%d,%d]],\n \"type\":\"gauge\",\n \"host\":\"%s\",\n \"tags\":[\"%s:%s\",\"%s:%s\"]\n },\n {\n \"metric\":\"system.disk.used\",\n \"points\":[[%d,%d]],\n \"type\":\"gauge\",\n \"host\":\"%s\",\n \"tags\":[\"%s:%s\",\"%s:%s\"]\n },\n {\n \"metric\":\"system.mem.used\",\n \"points\":[[%d,%d]],\n \"type\":\"gauge\",\n \"host\":\"%s\",\n \"tags\":[\"%s:%s\",\"%s:%s\"]\n }\n ]\n }`,time,host.name,host.tags[0].name,host.tags[0].value,host.tags[1].name,host.tags[1].value,time,cpu,host.name,host.tags[0].name,host.tags[0].value,host.tags[1].name,host.tags[1].value,time,disk,host.name,host.tags[0].name,host.tags[0].value,host.tags[1].name,host.tags[1].value,time,mem,host.name,host.tags[0].name,host.tags[0].value,host.tags[1].name,host.tags[1].value)\n fmt.Println(json)\n\n return json\n}", "func (client IotHubResourceClient) GetStatsResponder(resp *http.Response) (result RegistryStatistics, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (s *RestServer) getPcieMgrMetricsHandler(r *http.Request) (interface{}, error) {\n\tlog.Infof(\"Got GET request PcieMgrMetrics/%s\", mux.Vars(r)[\"Meta.Name\"])\n\treturn nil, nil\n}", "func (client PrimitiveClient) GetDurationResponder(resp *http.Response) (result DurationWrapper, err error) { \n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n}", "func (session *Session) PerformanceGetMetrics() ([]Metric, error) {\n\tmsg, err := session.blockingSend(\"Performance.getMetrics\", &Params{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm := make([]Metric, 0)\n\tunmarshal(msg[\"metrics\"], &m)\n\treturn m, nil\n}", "func (a *AllApiService) MetricsGetEdgeDeviceSeries(ctx _context.Context, body MetricsGetEdgeDeviceSeries) ([]MetricsGetEdgeDeviceSeriesResultItem, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []MetricsGetEdgeDeviceSeriesResultItem\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/metrics/getEdgeDeviceSeries\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v []MetricsGetEdgeDeviceSeriesResultItem\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (d *Decoder) Measurement() ([]byte, error) {\n\tif ok, err := d.advanceToSection(measurementSection); err != nil {\n\t\treturn nil, err\n\t} else if !ok {\n\t\treturn nil, nil\n\t}\n\td.reset()\n\tmeasure, i0, err := d.takeEsc(measurementChars, &measurementEscapes.revTable)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(measure) == 0 {\n\t\tif !d.ensure(1) {\n\t\t\treturn nil, d.syntaxErrorf(i0, \"no measurement name found\")\n\t\t}\n\t\treturn nil, d.syntaxErrorf(i0, \"invalid character %q found at start of measurement name\", d.at(0))\n\t}\n\tif measure[0] == '#' {\n\t\t// Comments are usually skipped earlier but if a comment contains invalid white space,\n\t\t// there's no way for the comment-parsing code to return an error, so instead\n\t\t// the read point is set to the start of the comment and we hit this case.\n\t\t// TODO find the actual invalid character to give a more accurate position.\n\t\treturn nil, d.syntaxErrorf(i0, \"invalid character found in comment line\")\n\t}\n\tif err := d.advanceTagComma(); err != nil {\n\t\treturn nil, err\n\t}\n\td.section = tagSection\n\treturn measure, nil\n}", "func getData() []float64 {\n\tvar f interface{}\n\tlistData := []float64{}\n\n\tresp, err := http.Get(\"https://min-api.cryptocompare.com/data/histominute?fsym=BTC&tsym=USD&limit=60\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t\tos.Exit(1)\n\t}\n\n\t// Read content from response\n\trespContent, err := ioutil.ReadAll(resp.Body)\n\n\t// Parse respContent Json to interface f\n\terr = json.Unmarshal(respContent, &f)\n\n\tjsonData := f.(map[string]interface{})\n\tarrayData := jsonData[\"Data\"].([]interface{})\n\n\tfor _, object := range arrayData {\n\t\tx := object.(map[string]interface{})\n\t\tminutePrice := x[\"close\"].(float64)\n\t\tlistData = append(listData, minutePrice)\n\t}\n\n\treturn listData\n}", "func (client DDMetricsClient) GetMetrics() ([]ServiceStatisticsFromDD, error) {\n\n\tinfo, err := client.GetInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmetrics := []ServiceStatisticsFromDD{}\n\tfor _, s := range info.Head.Services {\n\t\tstatsURL := client.endpoint\n\t\tstatsURL.Path = fmt.Sprintf(\"/services/%v\", s.Name)\n\n\t\tresp, err := client.httpClient.Get(statsURL.String())\n\t\tstats := ServiceStatisticsFromDD{}\n\t\terr = json.NewDecoder(resp.Body).Decode(&stats)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmetrics = append(metrics, stats)\n\t}\n\n\treturn metrics, nil\n}" ]
[ "0.74997777", "0.67356014", "0.6283912", "0.61545205", "0.6074424", "0.6033546", "0.6003006", "0.5927213", "0.5910613", "0.5830679", "0.5797388", "0.5765787", "0.5747032", "0.5735315", "0.5729223", "0.5726011", "0.5648738", "0.56365585", "0.55921185", "0.55593187", "0.5550674", "0.5539321", "0.5529876", "0.5490762", "0.54424787", "0.5435205", "0.5428762", "0.5427302", "0.5421939", "0.5417672", "0.5402542", "0.53992933", "0.53820497", "0.5367586", "0.5351132", "0.52998096", "0.5278049", "0.527199", "0.52638096", "0.52552074", "0.5255126", "0.5250379", "0.52449876", "0.52165216", "0.5206645", "0.52023584", "0.51864684", "0.5176912", "0.51761466", "0.51646626", "0.5158325", "0.515308", "0.515028", "0.51479435", "0.51465905", "0.51411194", "0.5117598", "0.51130813", "0.5110959", "0.510181", "0.51015186", "0.507658", "0.5072517", "0.50682425", "0.5060281", "0.5056667", "0.5024712", "0.5019088", "0.5011916", "0.5008265", "0.50057596", "0.5002998", "0.4998133", "0.49973667", "0.49930415", "0.49928626", "0.49910018", "0.498794", "0.49845076", "0.4984132", "0.49808642", "0.49728155", "0.4971872", "0.49663794", "0.49641362", "0.49624383", "0.4959845", "0.49561796", "0.49527135", "0.49507564", "0.493715", "0.49363232", "0.49279147", "0.49274772", "0.4918584", "0.49124348", "0.4911964", "0.48991638", "0.48987982", "0.48986903" ]
0.7500745
0
QueryStringParser converts URL querystring into a slice of `FilteredResult.` Given the querystring `?first_name=john:eq:and&last_name=doe:eq`
func QueryStringParser(queryStr string, filters map[string]string) []FilteredResult { //define custom map type to allowduplicate keys type Map struct { Key string Value string } params := []Map{} searchFilters := []FilteredResult{} parts := strings.Split(queryStr, "&") //build a key/value map of the querystring by //storing the query as key and the fragment as the value for _, part := range parts { split := strings.Split(part, "=") if len(split) > 1 && split[1] != "" { params = append(params, Map{ Key: split[0], Value: split[1], }) } else { params = append(params, Map{ Key: split[0], Value: "", }) } } // for _, param := range params { for name, varType := range filters { if param.Key == name { esc, _ := url.QueryUnescape(param.Value) parseValue, operator, condition := RHSParser(esc, varType) searchFilters = append(searchFilters, FilteredResult{ Field: param.Key, Type: varType, Value: parseValue, Operator: operator, Condition: condition, }) break } } } return searchFilters }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ExtractPaginationQueryString(qry url.Values) map[string]interface{} {\n\n\tpg := map[string]interface{}{\n\t\t\"Page\": 1,\n\t\t\"PerPage\": 15,\n\t\t\"Filter\": \"\",\n\t\t\"Order\": \"created_at\",\n\t\t\"OrderType\": \"desc\",\n\t\t\"NoPagination\": false,\n\t}\n\n\t// Extract noPagination from query\n\tparamNoPagination := qry.Get(\"noPagination\")\n\tif paramNoPagination == \"0\" || paramNoPagination == \"\" {\n\t\tpg[\"NoPagination\"] = false\n\t} else {\n\t\tpg[\"NoPagination\"] = true\n\t}\n\n\t// Extract Page from query\n\tif paramPage, err := strconv.Atoi(qry.Get(\"page\")); err == nil {\n\t\tpg[\"Page\"] = paramPage\n\t}\n\n\t// Extract item per page\n\tif paramPerPage, err := strconv.Atoi(qry.Get(\"perPage\")); err == nil {\n\t\tpg[\"PerPage\"] = paramPerPage\n\t}\n\n\t// Extract needed filter\n\tif qry.Get(\"filter\") != \"\" {\n\t\tpg[\"Filter\"] = qry.Get(\"filter\")\n\t}\n\n\t// Extract needed filter\n\tif qry.Get(\"IsPaginate\") == \"\" {\n\t\tpg[\"IsPaginate\"] = false\n\t} else if qry.Get(\"IsPaginate\") == \"false\" {\n\t\tpg[\"IsPaginate\"] = false\n\t} else {\n\t\tpg[\"IsPaginate\"] = false\n\t}\n\n\t// Extract order by direction\n\tif qry.Get(\"order\") != \"\" {\n\t\tpg[\"Order\"] = qry.Get(\"order\")\n\t\tswitch qry.Get(\"orderType\") {\n\t\tcase \"asc\":\n\t\t\tpg[\"OrderType\"] = \"asc\"\n\t\tcase \"desc\":\n\t\t\tpg[\"OrderType\"] = \"desc\"\n\t\t}\n\t}\n\n\treturn pg\n}", "func (f *Filter) QueryString() (q string, args []interface{}) {\n\tvar filters []string\n\n\tif !f.AddedAfter.IsZero() {\n\t\tfilter, newArgs := filterAddedAfter(f.AddedAfter.String())\n\t\tif filter != \"\" {\n\t\t\tfilters = append(filters, filter)\n\t\t\targs = append(args, newArgs...)\n\t\t}\n\t}\n\n\tif len(f.Versions) > 0 {\n\t\tfilter, newArgs := filterVersion(f.Versions)\n\t\tif filter != \"\" {\n\t\t\tfilters = append(filters, filter)\n\t\t\targs = append(args, newArgs...)\n\t\t}\n\t}\n\n\tfor field, raws := range filterMapFieldToRawStrings(f) {\n\t\tif len(raws) > 0 {\n\t\t\tfilter, newArgs := filterCreator(raws, field)\n\t\t\tfilters = append(filters, filter)\n\t\t\targs = append(args, newArgs...)\n\t\t}\n\t}\n\n\treturn strings.Join(filters, \" and \"), args\n}", "func ParseQueryString(q string) (map[string]interface{}, error) {\n\tuv, err := url.ParseQuery(q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmp := map[string]interface{}{}\n\tfor k, v := range uv {\n\t\tmp[k] = v[0]\n\t}\n\treturn mp, err\n}", "func ParseQueryString(values map[string][]string) *NgGrid {\n\tg := &NgGrid{}\n\tif value := values[QS_SORT_DIRECTION]; len(value) != 0 {\n\t\tg.SortDirection = value[0]\n\t}\n\tif value := values[QS_SORT_FIELD]; len(value) != 0 {\n\t\tg.SortField = value[0]\n\t}\n\tif value := values[QS_QUERY]; len(value) != 0 {\n\t\tg.Query = value[0]\n\t}\n\tif value := values[QS_PAGE_NUMBER]; len(value) != 0 {\n\t\tpn, err := strconv.Atoi(value[0])\n\t\tif err == nil {\n\t\t\tg.PageNumber = int64(pn)\n\t\t}\n\t}\n\tif value := values[QS_PAGE_SIZE]; len(value) != 0 {\n\t\tpn, err := strconv.Atoi(value[0])\n\t\tif err == nil {\n\t\t\tg.PageSize = int64(pn)\n\t\t}\n\t}\n\n\tif g.PageNumber < 1 {\n\t\tg.PageNumber = 1\n\t}\n\n\treturn g\n}", "func FilterQuery(fq string) func(url.Values) {\n\treturn func(p url.Values) {\n\t\tp[\"fq\"] = append(p[\"fq\"], fq)\n\t}\n}", "func ParseQueryString(param string, request *http.Request, params imageserver.Params) {\n\ts := request.URL.Query().Get(param)\n\tif s != \"\" {\n\t\tparams.Set(param, s)\n\t}\n}", "func AddFiltersFromQueryParams(r *http.Request, filterDetails ...string) ([]QueryProcessor, error) {\n\tqueryParams := r.URL.Query()\n\tfilters := make([]QueryProcessor, 0)\n\tfor _, filterNameAndTypeStr := range filterDetails {\n\t\tfilterNameAndType := strings.Split(filterNameAndTypeStr, \":\")\n\t\tfilterValueAsStr := queryParams.Get(filterNameAndType[0])\n\t\tif filterValueAsStr != \"\" {\n\t\t\tif len(filterNameAndType) > 1 && filterNameAndType[1] == \"datetime\" {\n\t\t\t\tfilterValueAsTime, err := time.Parse(time.RFC3339, filterValueAsStr)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, microappError.NewValidationError(\"Key_InvalidFields\", map[string]string{filterNameAndType[0]: \"Key_InvalidValue\"})\n\t\t\t\t}\n\t\t\t\tfilters = append(filters, Filter(fmt.Sprintf(\"%v = ?\", filterNameAndType[0]), filterValueAsTime))\n\t\t\t} else {\n\t\t\t\tfilters = append(filters, Filter(fmt.Sprintf(\"%v = ?\", filterNameAndType[0]), filterValueAsStr))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn filters, nil\n}", "func ReparseQuery(r *http.Request) {\n\tif !strings.ContainsRune(r.URL.Path, '?') {\n\t\treturn\n\t}\n\tq := r.URL.Query()\n\ttmpURL, err := url.Parse(r.URL.Path)\n\tdebug.AssertNoErr(err)\n\tfor k, v := range tmpURL.Query() {\n\t\tq.Add(k, strings.Join(v, \",\"))\n\t}\n\tr.URL.Path = tmpURL.Path\n\tr.URL.RawQuery = q.Encode()\n}", "func NewQueryParams(q, p, pp, sort, filter string) QueryParam {\n\tvar qp QueryParam\n\n\tif q != \"\" {\n\t\tqp.Query = q\n\t}\n\n\tpage, err := strconv.Atoi(p)\n\tif err != nil {\n\t\tpage = pageDef\n\t}\n\tqp.Page = page\n\n\tperPage, err := strconv.Atoi(pp)\n\tif err != nil {\n\t\tperPage = perPageDef\n\t}\n\tqp.PerPage = perPage\n\n\tif sortVals := strings.Split(sort, sortFltrSeparator); len(sortVals) == 2 {\n\t\tqp.Sort = map[string]string{sortVals[0]: sortVals[1]}\n\t}\n\n\tif ftrVal := strings.Split(filter, fltrSeparator); len(ftrVal) >= 1 {\n\t\tfilters := make(map[string]string, len(ftrVal))\n\t\tfor _, fltr := range ftrVal {\n\t\t\tif f := strings.Split(fltr, sortFltrSeparator); len(f) == 2 {\n\t\t\t\tfilters[f[0]] = f[1]\n\t\t\t}\n\t\t}\n\t\tqp.Filter = filters\n\t}\n\n\treturn qp\n}", "func (a *API) ParseQuery(ctx *fasthttp.RequestCtx) map[string]string {\n\tqs, _ := url.ParseQuery(string(ctx.URI().QueryString()))\n\tvalues := make(map[string]string)\n\tfor key, val := range qs {\n\t\tvalues[key] = val[0]\n\t}\n\n\treturn values\n}", "func FromQuery(key string) TokenExtractor {\n\treturn func(r *http.Request) (string, error) {\n\t\treturn r.URL.Query().Get(key), nil\n\t}\n}", "func parseQuery(url string) ([]string, error) {\n\turlList := strings.Split(url, \"?\")\n\tif len(urlList) < 2 {\n\t\treturn make([]string, 0), nil\n\t}\n\tquery := make([]string, 0)\n\tfor _, val := range strings.Split(urlList[1], \"&\") {\n\t\tv := strings.Split(val, \"=\")\n\t\tif len(v) < 2 {\n\t\t\treturn make([]string, 0), errors.New(\"query parameter error\")\n\t\t}\n\t\tquery = append(query, fmt.Sprintf(\"%s=%s\", v[0], v[1]))\n\t}\n\treturn query, nil\n}", "func (u *URL) QueryString(field string, expect string) (ret string) {\n\tret = expect\n\tif mi := u.Query().Get(field); mi != \"\" {\n\t\tret = mi\n\t}\n\n\treturn\n}", "func parseUrlEncodedQueryParams(rawQuery string) (bson.M, map[string]interface{}) {\n\t\n\tqueryMap, _ := url.ParseQuery(rawQuery)\n\tvar query map[string]interface{}\n\tfor key, value := range queryMap {\n\t\tswitch key {\n\t\tdefault:\n\t\t\treturn bson.M{}, nil\n\t\tcase \"where\":\n\t\t\tif len(value) == 1 {\n\t\t\t\t\n\t\t\t\terr := json.Unmarshal([]byte(value[0]), &query)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn bson.M{}, map[string]interface{}{\"code\": helpers.INVALID_JSON, \"error\": \"invalid JSON\"}\n\t\t\t\t}\n\n\t\t\t} \n\t\tcase \"order\":\n\t\tcase \"limit\":\n\t\tcase \"skip\":\n\t\tcase \"keys\":\n\t\tcase \"include\":\n\t\t}\n\t}\n\t// fmt.Println(findObjectWithKey(query, \"$select\"))\n\t_ = parseWhereQuery(query)\n\terrMap := formatObjectQuery(query)\n\t// map can be used as bson.M for return\n\treturn query, errMap\n}", "func ParseQuery(query string) (QueryParams, error) {\n\tmatch, _ := ValidateQuery(query)\n\tif !match {\n\t\treturn QueryParams{}, errors.New(\"Not a valid SQL query\")\n\t}\n\twords := strings.Fields(query[0 : len(query)-1])\n\tselectVal := words[1]\n\tfromVal := words[3]\n\torderByVal := \"\"\n\tfor i := 0; i < len(words); i++ {\n\t\tif strings.EqualFold(words[i], \"orderby\") {\n\t\t\torderByVal = strings.ToLower(words[i+1])\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn QueryParams{Select: selectVal, From: fromVal, OrderBy: orderByVal}, nil\n}", "func (r *Request) SetQueryString(query string) *Request {\n\tparams, err := url.ParseQuery(strings.TrimSpace(query))\n\tif err == nil {\n\t\tfor p, v := range params {\n\t\t\tfor _, pv := range v {\n\t\t\t\tr.QueryParam.Add(p, pv)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tr.client.log.Errorf(\"%v\", err)\n\t}\n\treturn r\n}", "func GetRequestQueryString(query string) map[string]string {\n\tpairs := strings.Split(query, \"&\")\n\tparams := make(map[string]string, len(pairs))\n\n\tif len(query) < 1 {\n\t\treturn params\n\t}\n\n\tfor i := 0; i < len(pairs); i++ {\n\t\tketValuePair := strings.Split(pairs[i], \"=\")\n\t\tparams[ketValuePair[0]] = ketValuePair[1]\n\t}\n\n\treturn params\n}", "func (pagination *Pagination) ParsingQuery() Where {\n\twhere := make(Where)\n\tquery := pagination.ctx.URL.Query()\n\tfor key, val := range query {\n\t\tif v, ok := pagination.fieldMapping[key]; ok {\n\t\t\tkey = v\n\t\t}\n\n\t\tif len(val) == 1 {\n\t\t\tif val[0] != \"\" {\n\t\t\t\twhere[key] = val[0]\n\t\t\t}\n\t\t}\n\t\tif len(val) > 1 {\n\t\t\twhere[key] = val\n\t\t}\n\t}\n\treturn where\n}", "func url_parser(url_string string) url.Values{\n\tparams, err := url.ParseQuery(url_string)\n\tif err != nil{\n\t\tfmt.Println(err)\n\t}\n\treturn params\n}", "func NewFromRawQuery(rawQuery string) *QueryString {\n\tqs := new(QueryString)\n\tqs.fields = make(map[string]string)\n\n\tfor {\n\t\ti := strings.IndexRune(rawQuery, '=')\n\t\tif i == -1 {\n\t\t\tbreak\n\t\t}\n\t\tname := rawQuery[:i]\n\t\trawQuery = rawQuery[i+1:]\n\n\t\ti = strings.IndexFunc(rawQuery, charClassDetector(1, 1))\n\t\tvar value string\n\t\tif i == -1 {\n\t\t\tvalue = rawQuery\n\t\t} else {\n\t\t\tvalue = rawQuery[:i]\n\t\t\trawQuery = rawQuery[i+1:]\n\t\t}\n\n\t\tqs.fields[name] = value\n\n\t\tif i == -1 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn qs\n}", "func ExtractFilter(request *restful.Request) (bson.M, error) {\n\tparams, err := url.ParseQuery(request.Request.URL.RawQuery)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfilters := make(bson.M)\n\n\tif rawFilters, ok := params[\"filter[]\"]; ok {\n\t\tfor _, filterString := range rawFilters {\n\t\t\tif len(strings.TrimSpace(filterString)) == 0 {\n\t\t\t\treturn nil, errors.New(\"filter[] value should not be blank\")\n\t\t\t}\n\n\t\t\tfilter, err := parseFilter(filterString)\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tfor k, v := range filter {\n\t\t\t\tfilters[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\treturn filters, nil\n}", "func ExtractQueryParams(r *events.APIGatewayProxyRequest) map[string]string {\n\treturn map[string]string{\n\t\tconfigs.TimeTypeQueryParam: r.QueryStringParameters[configs.TimeTypeQueryParam],\n\t\tconfigs.OffsetUnitsQueryParam: r.QueryStringParameters[configs.OffsetUnitsQueryParam],\n\t\tconfigs.OffsetValueQueryParam: r.QueryStringParameters[configs.OffsetValueQueryParam],\n\t\tconfigs.StartTimeQueryParam: r.QueryStringParameters[configs.StartTimeQueryParam],\n\t\tconfigs.EndTimeQueryParam: r.QueryStringParameters[configs.EndTimeQueryParam],\n\t\tconfigs.ProductNumberQueryParam: r.QueryStringParameters[configs.ProductNumberQueryParam],\n\t\tconfigs.SerialNumberQueryParam: r.QueryStringParameters[configs.SerialNumberQueryParam],\n\t}\n}", "func TestQueryFunc(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Header == nil {\n\t\t\tt.Errorf(\"Expected non-nil request Header\")\n\t\t}\n\t\tv := r.URL.Query()\n\t\tcheckQuery(t, v, \"query1\", \"test1\")\n\t\tcheckQuery(t, v, \"query2\", \"test2\")\n\t}))\n\tdefer ts.Close()\n\n\tNew().Post(ts.URL).\n\t\tQuery(\"query1=test1\").\n\t\tQuery(\"query2=test2\").\n\t\tEnd()\n\n\tqq := struct {\n\t\tQuery1 string `json:\"query1\"`\n\t\tQuery2 string `json:\"query2\"`\n\t}{\n\t\tQuery1: \"test1\",\n\t\tQuery2: \"test2\",\n\t}\n\tNew().Post(ts.URL).\n\t\tQuery(qq).\n\t\tEnd()\n}", "func mapFromQueryString(queryString string) map[string]string {\n\tm := make(map[string]string)\n\tparams := strings.Split(queryString, \"&\")\n\n\tfor _, param := range params {\n\t\tsplitParam := strings.Split(param, \"=\")\n\t\tkey := splitParam[0]\n\t\tval := splitParam[1]\n\n\t\tm[key] = val\n\t}\n\treturn m\n}", "func ReadQueryIntoStruct(request *http.Request, dest interface{}, ignoreMissing bool) error {\n\tquery := request.URL.Query()\n\tif query == nil {\n\t\treturn errors.New(\"Request has no query parameters\")\n\t}\n\tfor k, v := range query {\n\t\tif len(v) == 1 {\n\t\t\tquery[k] = strings.Split(v[0], \",\")\n\t\t}\n\t}\n\treturn ReadMapIntoStruct(query, dest, ignoreMissing)\n}", "func extractQuery(c *gin.Context, tag string) (string, []string, error) {\n\tname, required, defaultVal, err := parseTagKey(tag)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tvar params []string\n\tquery := c.Request.URL.Query()[name]\n\n\tif c.GetBool(ExplodeTag) {\n\t\t// Delete empty elements so default and required arguments\n\t\t// will play nice together. Append to a new collection to\n\t\t// preserve order without too much copying.\n\t\tparams = make([]string, 0, len(query))\n\t\tfor i := range query {\n\t\t\tif query[i] != \"\" {\n\t\t\t\tparams = append(params, query[i])\n\t\t\t}\n\t\t}\n\t} else {\n\t\tsplitFn := func(c rune) bool {\n\t\t\treturn c == ','\n\t\t}\n\t\tif len(query) > 1 {\n\t\t\treturn name, nil, errors.New(\"repeating values not supported: use comma-separated list\")\n\t\t} else if len(query) == 1 {\n\t\t\tparams = strings.FieldsFunc(query[0], splitFn)\n\t\t}\n\t}\n\n\t// XXX: deprecated, use of \"default\" tag is preferred\n\tif len(params) == 0 && defaultVal != \"\" {\n\t\treturn name, []string{defaultVal}, nil\n\t}\n\t// XXX: deprecated, use of \"validate\" tag is preferred\n\tif len(params) == 0 && required {\n\t\treturn \"\", nil, fmt.Errorf(\"missing query parameter: %s\", name)\n\t}\n\treturn name, params, nil\n}", "func parseQuery(s string) (charName, query string, backup bool) {\n\tif m := rxQuery.FindStringSubmatch(s); m != nil {\n\t\tcharName = m[1]\n\t\tquery = m[2]\n\t\tif query == \"\" {\n\t\t\tbackup = true\n\t\t}\n\t\tquery = strings.TrimLeft(query, \" \")\n\t\treturn\n\t}\n\tquery = s\n\treturn\n}", "func GetQueryStringSlice(values url.Values, key string) []string {\n\tif qs := GetQuerys(values, key); len(qs) > 0 {\n\t\tvs := make([]string, 0, len(qs)*2)\n\t\tfor _, q := range qs {\n\t\t\tfor _, v := range strings.Split(q, \",\") {\n\t\t\t\tif v != \"\" {\n\t\t\t\t\tvs = append(vs, v)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn []string{}\n}", "func QueryResponder(t *testing.T, resp httpmock.Responder, q url.Values) httpmock.Responder {\n\treturn func(r *http.Request) (*http.Response, error) {\n\t\tt.Helper()\n\n\t\tfor k := range q {\n\t\t\tif q.Get(k) != \"\" {\n\t\t\t\tassert.Equal(t, q.Get(k), r.URL.Query().Get(k))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tassert.Zero(t, r.URL.Query().Get(k))\n\t\t}\n\n\t\treturn resp(r)\n\t}\n}", "func FilterQuery(baseQuery string, filters map[string][]string, model interface{}) (string, map[string]interface{}, error) {\n\tfilterStrings := make(map[string]string)\n\tfor key, values := range filters {\n\t\tif len(values) >= 1 {\n\t\t\t// we only consider the first query parameter for now (we could AND or OR multiple params in the future)\n\t\t\tfilterStrings[key] = values[0]\n\t\t}\n\t}\n\n\tquery := baseQuery + \" WHERE 1=1\"\n\tqueryArgs := make(map[string]interface{})\n\n\tmodelReflection := reflect.ValueOf(model)\n\tif modelReflection.Kind() == reflect.Struct {\n\t\tfor i := 0; i < modelReflection.NumField(); i++ {\n\t\t\tfilterKey := modelReflection.Type().Field(i).Tag.Get(\"db\")\n\t\t\tif filterString, ok := filterStrings[filterKey]; ok {\n\t\t\t\tvar filterValue interface{}\n\t\t\t\tvar err error\n\n\t\t\t\tswitch modelReflection.Field(i).Interface().(type) {\n\t\t\t\tcase bool:\n\t\t\t\t\tfilterValue, err = strconv.ParseBool(filterString)\n\t\t\t\tcase int, int8, int16, int32, int64:\n\t\t\t\t\tfilterValue, err = strconv.ParseInt(filterString, 10, 64)\n\t\t\t\tcase uint, uint8, uint16, uint32, uint64:\n\t\t\t\t\tfilterValue, err = strconv.ParseUint(filterString, 10, 64)\n\t\t\t\tcase float32, float64:\n\t\t\t\t\tfilterValue, err = strconv.ParseFloat(filterString, 64)\n\t\t\t\tcase string:\n\t\t\t\t\tfilterValue = filterString\n\t\t\t\t}\n\n\t\t\t\tmodelName := reflect.TypeOf(model).Name()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn \"\", nil, fmt.Errorf(\"invalid type of filterValue value for field '%v' of '%v': %w\", filterKey, modelName, err)\n\t\t\t\t}\n\t\t\t\tif filterValue == nil {\n\t\t\t\t\treturn \"\", nil, fmt.Errorf(\"invalid field type for field '%v' of '%v'\", filterKey, model)\n\t\t\t\t}\n\n\t\t\t\t// Note that the string being inserted into the SQL query (filterKey) comes directly from the provided model\n\t\t\t\t// and not from user input (filters), so this should be safe from SQL Injection\n\t\t\t\tquery += fmt.Sprintf(\" AND %[1]v = :%[1]v\", filterKey) // e.g. \" AND username = :username\"\n\t\t\t\tqueryArgs[filterKey] = filterValue\n\t\t\t}\n\t\t}\n\n\t\treturn query, queryArgs, nil\n\t}\n\treturn \"\", nil, fmt.Errorf(\"the provided model is not a struct\")\n}", "func (q *ParsedRawQuery) FilterStartIndex() int { return 2 }", "func (l *Middleware) sanitizeQuery(inp string) string {\n\n\tinHiddenWords := func(str string) bool {\n\t\tfor _, w := range hideWords {\n\t\t\tif strings.EqualFold(w, str) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tparts := strings.SplitN(inp, \"?\", 2)\n\tif len(parts) < 2 {\n\t\treturn inp\n\t}\n\n\tq, e := url.ParseQuery(parts[1])\n\tif e != nil || len(q) == 0 {\n\t\treturn inp\n\t}\n\n\tres := []string{}\n\tfor k, v := range q {\n\t\tif inHiddenWords(k) {\n\t\t\tres = append(res, fmt.Sprintf(\"%s=********\", k))\n\t\t} else {\n\t\t\tres = append(res, fmt.Sprintf(\"%s=%v\", k, v[0]))\n\t\t}\n\t}\n\tsort.Strings(res) // to make testing persistent\n\treturn parts[0] + \"?\" + strings.Join(res, \"&\")\n}", "func ParseFilterStr(filterStr string) (EntityFilter, error) {\n\tfilterParts := strings.Split(filterStr, \",\")\n\n\tfilter := NewEntityFilter()\n\tfor _, filterStr := range filterParts {\n\t\tif strings.TrimSpace(filterStr) == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tnewEntry, err := buildFilterEntry(filterStr)\n\t\tif err != nil {\n\t\t\treturn filter, err\n\t\t}\n\n\t\tfilter.Add(newEntry)\n\t}\n\n\treturn filter, nil\n}", "func parseQuery(owner *user_model.User, query string) *conan_model.RecipeSearchOptions {\n\topts := &conan_model.RecipeSearchOptions{\n\t\tOwnerID: owner.ID,\n\t}\n\n\tif query != \"\" {\n\t\tparts := strings.Split(strings.ReplaceAll(query, \"@\", \"/\"), \"/\")\n\n\t\topts.Name = parts[0]\n\t\tif len(parts) > 1 && parts[1] != \"*\" {\n\t\t\topts.Version = parts[1]\n\t\t}\n\t\tif len(parts) > 2 && parts[2] != \"*\" {\n\t\t\topts.User = parts[2]\n\t\t}\n\t\tif len(parts) > 3 && parts[3] != \"*\" {\n\t\t\topts.Channel = parts[3]\n\t\t}\n\t}\n\n\treturn opts\n}", "func QueryStringParamList(r *http.Request, param string) []string {\n\tvar results []string\n\tvalues := r.URL.Query()\n\n\tif _, found := values[param]; found {\n\t\tfor _, value := range values[param] {\n\t\t\tvalue = strings.TrimSpace(value)\n\t\t\tif value != \"\" {\n\t\t\t\tresults = append(results, value)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn results\n}", "func QueryParser(key string) Parser {\n\tfn := func(r *http.Request) (string, error) {\n\t\treturn internal.ParseQuery(key, r, ErrMissingPin)\n\t}\n\n\treturn pinFn(fn)\n}", "func (p *GetAllParams) QueryString() string {\n\turlValues := &url.Values{}\n\n\turlvalues.AddStringSliceToURLValues(urlValues, p.Statuses, \"statuses\")\n\tif p.Limit > 0 {\n\t\turlValues.Add(\"limit\", strconv.Itoa(p.Limit))\n\t}\n\turlvalues.AddTimeToURLValues(urlValues, p.CreatedAfter, \"created_after\")\n\turlvalues.AddTimeToURLValues(urlValues, p.CreatedBefore, \"created_before\")\n\turlvalues.AddTimeToURLValues(urlValues, p.PaidAfter, \"paid_after\")\n\turlvalues.AddTimeToURLValues(urlValues, p.PaidBefore, \"paid_before\")\n\turlvalues.AddTimeToURLValues(urlValues, p.PaidBefore, \"paid_before\")\n\turlvalues.AddTimeToURLValues(urlValues, p.ExpiredAfter, \"expired_after\")\n\turlvalues.AddTimeToURLValues(urlValues, p.ExpiredBefore, \"expired_before\")\n\turlvalues.AddStringSliceToURLValues(urlValues, p.ClientTypes, \"client_types\")\n\turlvalues.AddStringSliceToURLValues(urlValues, p.PaymentChannels, \"payment_channels\")\n\tif p.OnDemandLink != \"\" {\n\t\turlValues.Add(\"on_demand\", p.OnDemandLink)\n\t}\n\tif p.RecurringPaymentID != \"\" {\n\t\turlValues.Add(\"recurring_payment_id\", p.RecurringPaymentID)\n\t}\n\n\treturn urlValues.Encode()\n}", "func (sc SearchClient) QueryParams() url.Values {\n\tparams := url.Values{}\n\n\tif sc.FilterID > 0 {\n\t\tparams.Add(\"filter_id\", strconv.Itoa(sc.FilterID))\n\t}\n\n\tif sc.PerPage > 1 && sc.PerPage != 25 {\n\t\tparams.Add(\"per_page\", strconv.Itoa(sc.PerPage))\n\t}\n\n\tif len(sc.Key) > 0 {\n\t\tparams.Add(\"key\", sc.Key)\n\t}\n\n\tif len(sc.SortDirection) > 0 {\n\t\tparams.Add(\"sd\", sc.SortDirection)\n\t}\n\n\tif len(sc.SortField) > 0 {\n\t\tparams.Add(\"sf\", sc.SortField)\n\t}\n\n\treturn params\n}", "func (b binder) setFromQueryParams() HTTPError {\n\tfor k, values := range b.req.URL.Query() {\n\t\tkey := k\n\t\t// Convention for array query params is key[]=val1&key[]=val2, which will be key: {val1, val2}\n\t\t// when parsed by Go. Remove the trailing []. We do this safely, if anyone is actually depending on\n\t\t// \"[]\" as part of a meaningful JSON key, they probably have a use case outside of apiparams.\n\t\tif strings.HasSuffix(key, \"[]\") {\n\t\t\tkey = strings.TrimSuffix(key, \"[]\")\n\t\t}\n\t\tfor _, v := range values {\n\t\t\tif err := b.setField(key, v, ParamSourceQuery); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func AddFiltersFromQueryParamsWithOR(r *http.Request, filterDetails ...string) ([]QueryProcessor, error) {\n\tqueryParams := r.URL.Query()\n\tfilters := make([]QueryProcessor, 0)\n\tfor _, filterNameAndTypeStr := range filterDetails {\n\t\tfilterNameAndType := strings.Split(filterNameAndTypeStr, \":\")\n\t\tfilterValueAsStr := queryParams.Get(filterNameAndType[0])\n\t\tif filterValueAsStr != \"\" {\n\t\t\tfilterValueArray := strings.Split(filterValueAsStr, \",\")\n\t\t\tcolumnName := []string{}\n\t\t\tcondition := []string{}\n\t\t\tfilterInterface := make([]interface{}, 0)\n\t\t\tfor _, filterValueArrayAsString := range filterValueArray {\n\t\t\t\tfilterValueArrayAsString = strings.TrimSpace(filterValueArrayAsString)\n\t\t\t\tif filterValueArrayAsString != \"\" {\n\t\t\t\t\tif len(filterNameAndType) > 1 && filterNameAndType[1] == \"datetime\" {\n\t\t\t\t\t\t_, err := time.Parse(time.RFC3339, filterValueArrayAsString)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn nil, microappError.NewValidationError(\"Key_InvalidFields\", map[string]string{filterNameAndType[0]: \"Key_InvalidValue\"})\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcolumnName = append(columnName, filterNameAndType[0])\n\t\t\t\t\t\tcondition = append(condition, \"like\")\n\t\t\t\t\t\tfilterInterface = append(filterInterface, fmt.Sprintf(\"%v%v%v\", \"%\", filterValueArrayAsString, \"%\"))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcolumnName = append(columnName, filterNameAndType[0])\n\t\t\t\t\t\tcondition = append(condition, \"like\")\n\t\t\t\t\t\tfilterInterface = append(filterInterface, fmt.Sprintf(\"%v%v%v\", \"%\", filterValueArrayAsString, \"%\"))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfilters = append(filters, FilterWithOR(columnName, condition, filterInterface))\n\t\t}\n\t}\n\treturn filters, nil\n}", "func QueryParamString(request *http.Request, name string) (string, IResponse) {\n\tvalue := request.URL.Query().Get(name)\n\tif value == \"\" {\n\t\treturn \"\", BadRequest(request, \"Empty query param %s\", name)\n\t}\n\n\treturn value, nil\n}", "func query_param(query_data map[string][]string) *pagination.QueryParam {\n\tqp := new(pagination.QueryParam)\n\tif len(query_data[\"page\"]) > 0 {\n\t\tpage, err := strconv.Atoi(query_data[\"page\"][0])\n\t\tif err == nil {\n\t\t\tqp.Page = page\n\t\t}\n\t}\n\n\tif len(query_data[\"per_page\"]) > 0 {\n\t\tpage, err := strconv.Atoi(query_data[\"per_page\"][0])\n\t\tif err == nil {\n\t\t\tqp.Per_page = page\n\t\t}\n\t}\n\n\tif len(query_data[\"value\"]) > 0 {\n\t\tqp.Value = query_data[\"value\"][0]\n\t}\n\n\tif len(query_data[\"filter\"]) > 0 {\n\t\tqp.Filter, _ = strconv.ParseBool(query_data[\"filter\"][0])\n\t}\n\n\treturn qp\n}", "func (p *Page) QueryString() (q string, args []interface{}) {\n\tif p.Valid() {\n\t\tq = \"limit ?\"\n\t\targs = []interface{}{(p.Limit)}\n\t}\n\treturn\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (r *BasicRequest) QueryArgs() (url.Values, error) {\n\treturn url.ParseQuery(r.Query)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (r *InboundRequest) QueryParamMultiple(key string) ([]string, bool) {\n value, ok := r.URL.Query()[key]\n\n return value, ok\n}", "func ExtractPrinterQueryParams(r *events.APIGatewayProxyRequest) map[string]string {\n\treturn map[string]string{\n\t\tconfigs.ProductNumberQueryParam: r.QueryStringParameters[configs.ProductNumberQueryParam],\n\t\tconfigs.SerialNumberQueryParam: r.QueryStringParameters[configs.SerialNumberQueryParam],\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func HTTPQueryString(data map[string]any) string {\n\tss := make([]string, 0, len(data))\n\tfor k, v := range data {\n\t\tss = append(ss, k+\"=\"+strutil.QuietString(v))\n\t}\n\n\treturn strings.Join(ss, \"&\")\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func redactQuerystring(ruleMatch HTTPMatch, u *url.URL) string {\n\tqueryValues := url.Values{}\n\n\tfor k, values := range u.Query() {\n\t\tfor _, v := range values {\n\t\t\tvalue := RedactedStr\n\t\t\tif ruleMatch.HasQuerystringWhitelistMatch(k) {\n\t\t\t\tvalue = v\n\t\t\t}\n\n\t\t\tqueryValues.Add(k, value)\n\t\t}\n\t}\n\n\treturn queryValues.Encode()\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (s *KendraConfiguration) SetQueryFilterString(v string) *KendraConfiguration {\n\ts.QueryFilterString = &v\n\treturn s\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput)\n}", "func (loc Location) Query() url.Values {\n\tvs, err := url.ParseQuery(loc[\"query\"])\n\tif err != nil {\n\t\tvs = make(url.Values)\n\t}\n\treturn vs\n}", "func QueryString(opts interface{}) map[string]interface{} {\n\titems := map[string]interface{}{}\n\tif opts == nil {\n\t\treturn items\n\t}\n\tvalue := reflect.ValueOf(opts)\n\tif value.Kind() == reflect.Ptr {\n\t\tvalue = value.Elem()\n\t}\n\tif value.Kind() != reflect.Struct {\n\t\treturn items\n\t}\n\tfor i := 0; i < value.NumField(); i++ {\n\t\tfield := value.Type().Field(i)\n\t\tif field.PkgPath != \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tkey := field.Tag.Get(\"qs\")\n\t\tif key == \"\" {\n\t\t\tkey = strings.ToLower(field.Name)\n\t\t} else if key == \"-\" {\n\t\t\tcontinue\n\t\t}\n\t\tv := value.Field(i)\n\t\tswitch v.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tif v.Bool() {\n\t\t\t\titems[key] = \"1\"\n\t\t\t}\n\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\tif v.Int() > 0 {\n\t\t\t\titems[key] = strconv.FormatInt(v.Int(), 10)\n\t\t\t}\n\t\tcase reflect.Float32, reflect.Float64:\n\t\t\tif v.Float() > 0 {\n\t\t\t\titems[key] = strconv.FormatFloat(v.Float(), 'f', -1, 64)\n\t\t\t}\n\t\tcase reflect.String:\n\t\t\tif v.String() != \"\" {\n\t\t\t\titems[key] = v.String()\n\t\t\t}\n\t\tcase reflect.Ptr:\n\t\t\tif !v.IsNil() {\n\t\t\t\tif b, err := json.Marshal(v.Interface()); err == nil {\n\t\t\t\t\titems[key] = string(b)\n\t\t\t\t}\n\t\t\t}\n\t\tcase reflect.Map:\n\t\t\tif len(v.MapKeys()) > 0 {\n\t\t\t\tif b, err := json.Marshal(v.Interface()); err == nil {\n\t\t\t\t\titems[key] = string(b)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn items\n}", "func (r *IntervalFilterInput) MakeQueryString(command string, measurement string) string {\n\tvar b bytes.Buffer\n\tb.WriteString(command)\n\tb.WriteString(\" FROM \")\n\tb.WriteString(measurement)\n\n\tcheck_empty := r == &IntervalFilterInput{}\n\tif check_empty {\n\t\treturn b.String()\n\t}\n\n\tflag := true\n\tb, flag = query.HandleTagFieldQuery(b, \"unique_meter_seqid\", r.UniqueMeterSeqid, flag)\n\tb, flag = query.HandleDateQuery(b, r.ExactTime, \"=\", flag)\n\tb, flag = query.HandleDateQuery(b, r.StartDate, \">=\", flag)\n\tb, _ = query.HandleDateQuery(b, r.EndDate, \"<\", flag)\n\n\treturn b.String()\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func QueryString(name string, value map[string]string, usage string) *map[string]string {\n\treturn Environment.QueryString(name, value, usage)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (s *FindQuery) Parse(req *http.Request) error {\n\tvar err error\n\n\tswitch req.Header.Get(contentType) {\n\tcase mimeJSON:\n\t\tbody, err := ioutil.ReadAll(req.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = json.Unmarshal(body, s); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase mimeForm:\n\t\tif err = req.ParseForm(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor key, val := range req.Form {\n\t\t\tswitch key {\n\t\t\tcase \"query\":\n\t\t\t\ts.Query = val[0]\n\t\t\tcase \"format\":\n\t\t\t\ts.Format = val[0]\n\t\t\tcase \"jsonp\":\n\t\t\t\ts.JSONP = val[0]\n\t\t\tcase \"wildcards\":\n\t\t\t\ts.Wildcards, err = strconv.Atoi(val[0])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase \"from\":\n\t\t\t\ts.From, err = strconv.ParseInt(val[0], 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase \"until\":\n\t\t\t\ts.Until, err = strconv.ParseInt(val[0], 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tparams := req.URL.Query()\n\tif len(params.Get(\"query\")) != 0 {\n\t\ts.Query = params.Get(\"query\")\n\t}\n\n\tif len(s.Format) != 0 {\n\t\ts.Format = params.Get(\"format\")\n\t}\n\n\tif len(params.Get(\"jsonp\")) != 0 {\n\t\ts.JSONP = params.Get(\"jsonp\")\n\t}\n\n\tif len(params.Get(\"wildcards\")) != 0 {\n\t\ts.Wildcards, err = strconv.Atoi(params.Get(\"wildcards\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(params.Get(\"from\")) != 0 {\n\t\ts.From, err = strconv.ParseInt(params.Get(\"from\"), 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(params.Get(\"until\")) != 0 {\n\t\ts.Until, err = strconv.ParseInt(params.Get(\"until\"), 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(params.Get(\"until\")) != 0 {\n\t\ts.Until, err = strconv.ParseInt(params.Get(\"until\"), 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func parseBodyQueryParams(body []byte) (bson.M, map[string]interface{}) {\n\t// return an empty bson hash map if the body is empty\n\tif string(body) == \"\" {\n\t\t\n\t\treturn bson.M{}, nil\n\t} else {\n\t\tvar queryMap map[string]interface{}\n\n\t\terr := json.Unmarshal(body, &queryMap)\n\t\tif err != nil {\n\t\t\treturn bson.M{}, map[string]interface{}{\"code\": helpers.INVALID_JSON, \"error\": \"invalid JSON\"}\n\t\t}\n\t\tvar query map[string]interface{}\n\t\tfor key, value := range queryMap {\n\t\t\tswitch key {\n\t\t\tdefault:\n\t\t\t\treturn bson.M{}, nil\n\t\t\tcase \"where\":\n\t\t\t\tquery = value.(map[string]interface{})\n\t\t\tcase \"order\":\n\t\t\tcase \"limit\":\n\t\t\tcase \"skip\":\n\t\t\tcase \"keys\":\n\t\t\tcase \"include\":\n\t\t\t}\n\t\t}\n\n\t\t// findObjectWithKey(query, \"$select\").(map[string]interface{})[\"helloworld\"] = \"helloworld\"\n\t\t// fmt.Println(query)\n\t\tparseWhereQuery(query)\n\t\terrMap := formatObjectQuery(query)\n\t\t\n\t\treturn query, errMap\n\t}\n\t\n}", "func TestQueryParser(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tinputQuery string\n\t\texpectedProblemSelector string\n\t\texpectedEntitySelector string\n\t}{\n\t\t{\n\t\t\tname: \"valid\",\n\t\t\tinputQuery: \"PV2;problemSelector=status(open)&entitySelector=mzId(7030365576649815430)\",\n\t\t\texpectedProblemSelector: \"status(open)\",\n\t\t\texpectedEntitySelector: \"mzId(7030365576649815430)\",\n\t\t},\n\t\t{\n\t\t\tname: \"valid - empty\",\n\t\t\tinputQuery: \"PV2;\",\n\t\t},\n\t\t{\n\t\t\tname: \"valid\",\n\t\t\tinputQuery: \"PV2;entitySelector=mzId(7030365576649815430)\",\n\t\t\texpectedEntitySelector: \"mzId(7030365576649815430)\",\n\t\t},\n\t\t{\n\t\t\tname: \"valid\",\n\t\t\tinputQuery: \"PV2;problemSelector=status(open)\",\n\t\t\texpectedProblemSelector: \"status(open)\",\n\t\t},\n\t}\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tquery, err := NewQueryParser(tc.inputQuery).Parse()\n\n\t\t\tassert.NoError(t, err)\n\t\t\tif assert.NotNil(t, query) {\n\t\t\t\tassert.EqualValues(t, tc.expectedProblemSelector, query.GetProblemSelector())\n\t\t\t\tassert.EqualValues(t, tc.expectedEntitySelector, query.GetEntitySelector())\n\t\t\t}\n\t\t})\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func parseTermsQuery(p *parser) parserStateFn {\n\tp.next() // Consume the ':' token.\n\n\tvar terms []term\n\ttok := p.peek()\n\tswitch tok.typ {\n\tcase tokTypeError:\n\t\treturn parseErrorTok\n\tcase tokTypeUnquotedLiteral, tokTypeQuotedLiteral:\n\t\t// E.g. `foo:val1 val2`, `breakfast:*am eggs` or `foo:*`.\n\t\t// If at least one of the terms is `*`, then this is an \"exists query\".\n\t\thaveExistsTerm := false\n\t\tfor {\n\t\t\ttok := p.next()\n\t\t\tif tok.typ == tokTypeUnquotedLiteral {\n\t\t\t\tif tok.val == \"*\" {\n\t\t\t\t\thaveExistsTerm = true\n\t\t\t\t}\n\t\t\t\tterms = append(terms, newTerm(tok.val))\n\t\t\t} else if tok.typ == tokTypeQuotedLiteral {\n\t\t\t\tterms = append(terms, newQuotedTerm(tok.val))\n\t\t\t} else {\n\t\t\t\tp.backup(tok)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif haveExistsTerm {\n\t\t\tp.filter.addStep(&rpnExistsQuery{field: p.field.val})\n\t\t} else {\n\t\t\tp.filter.addStep(&rpnTermsQuery{field: p.field.val, terms: terms})\n\t\t}\n\t\tp.field = nil\n\t\treturn parseAfterQuery\n\tcase tokTypeOpenParen:\n\t\t// E.g. `foo:(a or b ...)` or `foo:(a and b and c)`.\n\t\tp.next() // Consume the open paren.\n\t\tmatchAll := false // True if the second form with `and`: `foo:(a and b ...)`.\n\t\tfor i := 0; true; i++ {\n\t\t\t// Expect literal ...\n\t\t\ttermTok := p.next()\n\t\t\tif termTok.typ == tokTypeUnquotedLiteral {\n\t\t\t\tterms = append(terms, newTerm(termTok.val))\n\t\t\t} else if termTok.typ == tokTypeQuotedLiteral {\n\t\t\t\tterms = append(terms, newQuotedTerm(termTok.val))\n\t\t\t} else {\n\t\t\t\treturn p.errorfAt(termTok.pos, \"expected literal, got %s\", termTok.typ)\n\t\t\t}\n\t\t\t// ... then ')' to complete the query, or 'and' or 'or' to repeat.\n\t\t\topTok := p.next()\n\t\t\tswitch opTok.typ {\n\t\t\tcase tokTypeCloseParen:\n\t\t\t\tif matchAll {\n\t\t\t\t\tp.filter.addStep(&rpnMatchAllTermsQuery{field: p.field.val, terms: terms})\n\t\t\t\t} else {\n\t\t\t\t\tp.filter.addStep(&rpnTermsQuery{field: p.field.val, terms: terms})\n\t\t\t\t}\n\t\t\t\tp.field = nil\n\t\t\t\treturn parseAfterQuery\n\t\t\tcase tokTypeOr:\n\t\t\t\tif i == 0 {\n\t\t\t\t\tmatchAll = false\n\t\t\t\t} else if matchAll {\n\t\t\t\t\treturn p.errorfAt(opTok.pos,\n\t\t\t\t\t\t\"cannot mix 'and' and 'or' in parenthesized value group\")\n\t\t\t\t}\n\t\t\tcase tokTypeAnd:\n\t\t\t\tif i == 0 {\n\t\t\t\t\tmatchAll = true\n\t\t\t\t} else if !matchAll {\n\t\t\t\t\treturn p.errorfAt(opTok.pos,\n\t\t\t\t\t\t\"cannot mix 'and' and 'or' in parenthesized value group\")\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn p.errorfAt(opTok.pos, \"expected ')', 'or', or 'and'; got %s\",\n\t\t\t\t\topTok.typ)\n\t\t\t}\n\t\t}\n\t\tpanic(fmt.Sprintf(\"unreachable code hit with KQL %q\", p.kql))\n\tdefault:\n\t\treturn p.errorfAt(tok.pos, \"expected a literal or '('; got %s\", tok.typ)\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func BenchmarkQueryFilterString1From1(b *testing.B) {\n\tbenchmarkQueryFilterString(b, 1, 1)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func ReviewQuery(ctx context.Context, cfg *config.Config, urlQuery url.Values) (SearchURLParams, error) {\n\tvar validatedQueryParams SearchURLParams\n\n\tvalidatedQueryParams.Query = urlQuery.Get(\"q\")\n\n\terr := reviewPagination(ctx, cfg, urlQuery, &validatedQueryParams)\n\tif err != nil {\n\t\tlog.Event(ctx, \"unable to review pagination\", log.Error(err), log.ERROR)\n\t\treturn validatedQueryParams, err\n\t}\n\n\treviewSort(ctx, cfg, urlQuery, &validatedQueryParams)\n\n\terr = reviewFilters(ctx, urlQuery, &validatedQueryParams)\n\tif err != nil {\n\t\tlog.Event(ctx, \"unable to review filters\", log.Error(err), log.ERROR)\n\t\treturn validatedQueryParams, err\n\t}\n\n\treturn validatedQueryParams, nil\n}", "func extractFields(r *rest.Request) ([]string, error) {\n\tif _, filteringRequested := r.URL.Query()[\"fields\"]; !filteringRequested {\n\t\treturn nil, nil\n\t}\n\n\tfieldsValue := r.URL.Query().Get(\"fields\")\n\tif fieldsValue == \"\" {\n\t\treturn []string{}, nil\n\t}\n\n\tfieldsSplit := strings.Split(fieldsValue, \",\")\n\tfields := make([]string, len(fieldsSplit))\n\tfor i, fld := range fieldsSplit {\n\t\tfldName, ok := instanceQueryValuesToFieldNames[fld]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Field %s is not a valid field\", fld)\n\t\t}\n\n\t\tfields[i] = fldName\n\t}\n\n\treturn fields, nil\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput)\n}", "func validQueryStringParams(metric string, params map[string][]string) map[string][]string {\n\tvalidParams := make(map[string][]string)\n\tfor key, value := range params {\n\t\tif util.SliceContains(statsQueryStringParams[metric], key) {\n\t\t\tvalidParams[key] = value\n\t\t}\n\t}\n\treturn validParams\n}", "func ExtractFilters(req *http.Request) (*Filter, error) {\n\tfilter := &Filter{}\n\tqueryFilter := req.URL.Query().Get(\"filter\")\n\tif queryFilter != \"\" {\n\t\tif err := json.Unmarshal([]byte(queryFilter), filter); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not marshal filter: %w\", err)\n\t\t}\n\t}\n\n\treturn filter, nil\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (r InboundRequest) QueryParams() map[string][]string {\n return r.URL.Query()\n}", "func addQueryParams(s string, queryParams interface{}) (string, error) {\n\tv := reflect.ValueOf(queryParams)\n\tif v.Kind() == reflect.Ptr && v.IsNil() {\n\t\treturn s, nil\n\t}\n\n\tu, err := url.Parse(s)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\n\tqs, err := query.Values(queryParams)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\n\tu.RawQuery = qs.Encode()\n\treturn u.String(), nil\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func TestUrlParsing(t *testing.T) {\n\n\tu, _ := url.ParseRequestURI(strings.TrimPrefix(\n\t\t\"jdbc:mysql://mysql.default.svc.cluster.local:3306/vamp-${parent}?test=1&test2=2&useSSL=false\", \"jdbc:\"))\n\n\tassert.Equal(t, \"test=1&test2=2&useSSL=false\", u.Query().Encode())\n\n\tu, _ = url.ParseRequestURI(strings.TrimPrefix(\n\t\t\"jdbc:mysql://mysql.default.svc.cluster.local:3306/vamp-${parent}\", \"jdbc:\"))\n\n\tassert.Equal(t, \"\", u.Query().Encode())\n\n}", "func (o *Option) QueryString(q string) string {\n\treturn fmt.Sprintf(\"%s %s%s\", q, \"intitle:\", o.Text)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}" ]
[ "0.6135432", "0.60866284", "0.59948343", "0.59735113", "0.58965135", "0.5751068", "0.57321346", "0.56327635", "0.5629603", "0.55736727", "0.55452985", "0.5522028", "0.5475098", "0.54211044", "0.53964305", "0.53878003", "0.5383441", "0.5383123", "0.5362183", "0.53502405", "0.53202504", "0.52778774", "0.5234975", "0.520658", "0.52002037", "0.5170546", "0.5165005", "0.5146145", "0.51207036", "0.5102573", "0.5074672", "0.50345105", "0.5012376", "0.49950272", "0.49908715", "0.49731025", "0.4967307", "0.4932799", "0.49227512", "0.4907149", "0.4893779", "0.4891872", "0.48896837", "0.48858684", "0.48813683", "0.48588073", "0.4852373", "0.4842659", "0.48417538", "0.48334026", "0.48332363", "0.48237845", "0.48204052", "0.48181328", "0.4816205", "0.4810962", "0.48103017", "0.4806787", "0.48051736", "0.47993293", "0.47873944", "0.4782152", "0.4777409", "0.4775799", "0.47738707", "0.47734022", "0.4773104", "0.47650242", "0.4762062", "0.4760441", "0.47599456", "0.47579944", "0.4752855", "0.4750746", "0.47507164", "0.47473562", "0.474286", "0.47396177", "0.4734808", "0.47302592", "0.4727598", "0.4725896", "0.47238272", "0.47208747", "0.47168794", "0.47099528", "0.47073323", "0.47051305", "0.47045252", "0.4700834", "0.4700186", "0.46970513", "0.46946645", "0.46929696", "0.46929094", "0.46913543", "0.4690249", "0.46849984", "0.46838596", "0.4681323" ]
0.748404
0
RHSParser separates the fragment part of the query string into three parts value, comparison operator (=, >, , =, LIKE) and logical operator (AND/OR).
func RHSParser(queryStrValue string, valueType string) (value interface{}, comparisonOperator string, logicOperator string) { var val interface{} var cOperator string = " = " var lOperator string = " AND " parts := strings.Split(queryStrValue, ":") len := len(parts) if valueType == "int" { var number int64 number, _ = strconv.ParseInt(parts[0], 10, 64) val = number } else if valueType == "float" { number := 0.0 number, _ = strconv.ParseFloat(parts[0], 64) val = number } else { val = parts[0] } if len == 1 { cOperator = comparisonOperators["eq"] lOperator = " AND " return val, cOperator, lOperator } if comparisonOperators[parts[1]] != "" { cOperator = comparisonOperators[parts[1]] } if len == 3 { if logicalOperators[parts[2]] != "" { lOperator = logicalOperators[parts[2]] } } return val, cOperator, lOperator }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func QueryStringParser(queryStr string, filters map[string]string) []FilteredResult {\n\t//define custom map type to allowduplicate keys\n\ttype Map struct {\n\t\tKey string\n\t\tValue string\n\t}\n\n\tparams := []Map{}\n\tsearchFilters := []FilteredResult{}\n\n\tparts := strings.Split(queryStr, \"&\")\n\n\t//build a key/value map of the querystring by\n\t//storing the query as key and the fragment as the value\n\tfor _, part := range parts {\n\t\tsplit := strings.Split(part, \"=\")\n\n\t\tif len(split) > 1 && split[1] != \"\" {\n\t\t\tparams = append(params, Map{\n\t\t\t\tKey: split[0],\n\t\t\t\tValue: split[1],\n\t\t\t})\n\t\t} else {\n\t\t\tparams = append(params, Map{\n\t\t\t\tKey: split[0],\n\t\t\t\tValue: \"\",\n\t\t\t})\n\t\t}\n\t}\n\n\t//\n\tfor _, param := range params {\n\t\tfor name, varType := range filters {\n\t\t\tif param.Key == name {\n\t\t\t\tesc, _ := url.QueryUnescape(param.Value)\n\t\t\t\tparseValue, operator, condition := RHSParser(esc, varType)\n\n\t\t\t\tsearchFilters = append(searchFilters, FilteredResult{\n\t\t\t\t\tField: param.Key,\n\t\t\t\t\tType: varType,\n\t\t\t\t\tValue: parseValue,\n\t\t\t\t\tOperator: operator,\n\t\t\t\t\tCondition: condition,\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn searchFilters\n}", "func (r Rule) parse() (match, cond, result string) {\n\ts := strings.Split(r.rule, \"->\")\n\tif len(s) != 2 {\n\t\tlog.Fatalf(\"no arrow in %s\", r)\n\t}\n\tmatch = normalizeSpaces(s[0])\n\tresult = normalizeSpaces(s[1])\n\tcond = \"\"\n\tif i := strings.Index(match, \"&&\"); i >= 0 {\n\t\tcond = normalizeSpaces(match[i+2:])\n\t\tmatch = normalizeSpaces(match[:i])\n\t}\n\treturn match, cond, result\n}", "func TestRevParsing04(t *testing.T) {\n\tvar q = \"(*Ops;AUTHORS , *Vigith Maurice;AUTHORS) ,& (ops-prod-vpc1-range, ops-prod-vpc1-mon)\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed [reverse lookup with attr and hint]\", q)\n\t}\n\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tvar expected = []string{\"ops-prod-vpc1-mon\", \"ops-prod-vpc1-range\"}\n\tif len(errs) != 0 || !compare(*result, expected) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", q, expected, *result)\n\t}\n}", "func TestRevParsing05(t *testing.T) {\n\tvar q = \"*Ops;AUTHORS , (*Vigith Maurice;AUTHORS ,& ops-prod-vpc1-range) , ops-prod-vpc1-mon\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed [reverse lookup with attr and hint]\", q)\n\t}\n\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tvar expected = []string{\"ops-prod-vpc1-mon\", \"ops-prod-vpc1-range\", \"ops-prod-vpc2-mon\"}\n\tif len(errs) != 0 || !compare(*result, expected) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", q, expected, *result)\n\t}\n}", "func formulaCriteriaParser(exp string) (fc *formulaCriteria) {\n\tfc = &formulaCriteria{}\n\tif exp == \"\" {\n\t\treturn\n\t}\n\tif match := regexp.MustCompile(`^(\\d+)$`).FindStringSubmatch(exp); len(match) > 1 {\n\t\tfc.Type, fc.Condition = criteriaEq, match[1]\n\t\treturn\n\t}\n\tif match := regexp.MustCompile(`^=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {\n\t\tfc.Type, fc.Condition = criteriaEq, match[1]\n\t\treturn\n\t}\n\tif match := regexp.MustCompile(`^<>(.*)$`).FindStringSubmatch(exp); len(match) > 1 {\n\t\tfc.Type, fc.Condition = criteriaNe, match[1]\n\t\treturn\n\t}\n\tif match := regexp.MustCompile(`^<=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {\n\t\tfc.Type, fc.Condition = criteriaLe, match[1]\n\t\treturn\n\t}\n\tif match := regexp.MustCompile(`^>=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {\n\t\tfc.Type, fc.Condition = criteriaGe, match[1]\n\t\treturn\n\t}\n\tif match := regexp.MustCompile(`^<(.*)$`).FindStringSubmatch(exp); len(match) > 1 {\n\t\tfc.Type, fc.Condition = criteriaL, match[1]\n\t\treturn\n\t}\n\tif match := regexp.MustCompile(`^>(.*)$`).FindStringSubmatch(exp); len(match) > 1 {\n\t\tfc.Type, fc.Condition = criteriaG, match[1]\n\t\treturn\n\t}\n\tif strings.Contains(exp, \"?\") {\n\t\texp = strings.ReplaceAll(exp, \"?\", \".\")\n\t}\n\tif strings.Contains(exp, \"*\") {\n\t\texp = strings.ReplaceAll(exp, \"*\", \".*\")\n\t}\n\tfc.Type, fc.Condition = criteriaRegexp, exp\n\treturn\n}", "func TestRevParsing02(t *testing.T) {\n\tvar q = \"*Vigith Maurice;AUTHORS\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed [reverse lookup with attr]\", q)\n\t}\n\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tvar expected = []string{\"ops-prod-vpc1-range\"}\n\tif len(errs) != 0 || !compare(*result, expected) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", q, expected, *result)\n\t}\n}", "func TestParsing02(t *testing.T) {\n\tvar q = \"a\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed [starts with a-z]\", q)\n\t}\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tif len(errs) != 0 || !compare(*result, []string{\"a\"}) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", []string{\"ops\"}, *result)\n\t}\n}", "func parseQuery(s string) (charName, query string, backup bool) {\n\tif m := rxQuery.FindStringSubmatch(s); m != nil {\n\t\tcharName = m[1]\n\t\tquery = m[2]\n\t\tif query == \"\" {\n\t\t\tbackup = true\n\t\t}\n\t\tquery = strings.TrimLeft(query, \" \")\n\t\treturn\n\t}\n\tquery = s\n\treturn\n}", "func parseAfterQuery(p *parser) parserStateFn {\n\ttok := p.next()\n\tswitch tok.typ {\n\tcase tokTypeError:\n\t\tp.backup(tok)\n\t\treturn parseErrorTok\n\tcase tokTypeEOF:\n\t\tp.backup(tok)\n\t\treturn parseEOFTok\n\tcase tokTypeCloseParen:\n\t\tif p.incompleteBoolOp {\n\t\t\t// E.g.: \"(foo and)\"\n\t\t\t// Dev Note: I can't trigger this in tests.\n\t\t\treturn p.errorfAt(tok.pos, \"incomplete boolean operator\")\n\t\t}\n\t\t// Pop ops up to, and including, the matching rpnOpenParen.\n\t\tfor {\n\t\t\tif p.stagedOps.Len() == 0 {\n\t\t\t\treturn p.errorfAt(tok.pos, \"unmatched close parenthesis\")\n\t\t\t}\n\t\t\topTok := p.stagedOps.Pop()\n\t\t\tif opTok.typ == tokTypeOpenParen {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tp.filter.addBoolOp(opTok)\n\t\t\t}\n\t\t}\n\t\treturn parseAfterQuery\n\tcase tokTypeAnd:\n\t\tp.stageBoolOp(tok)\n\t\tp.incompleteBoolOp = true\n\t\treturn parseBeforeQuery\n\tcase tokTypeOr:\n\t\tp.stageBoolOp(tok)\n\t\tp.incompleteBoolOp = true\n\t\treturn parseBeforeQuery\n\tdefault:\n\t\treturn p.errorfAt(tok.pos, \"expect 'and', 'or', or ')'; got %s\",\n\t\t\ttok.typ)\n\t}\n}", "func parseMatcherWithoutLogicalOperator(s string) (m MatcherWithoutLogicalOperator, err error) {\n\tunParsed := s // the characters of s which are yet to be parsed\n\n\tswitch {\n\tcase strings.HasPrefix(unParsed, \"data1\"):\n\t\tm.LeftOperand = Data1\n\tcase strings.HasPrefix(unParsed, \"data2\"):\n\t\tm.LeftOperand = Data2\n\tdefault:\n\t\terr = fmt.Errorf(\"matcher %q: no valid left operand\", s)\n\t\treturn\n\t}\n\tunParsed = unParsed[len(\"datax\"):] // Discard parsed leftOperand\n\n\tskipToNonSpaceCharacter(&unParsed)\n\tvar operatorLength int\n\tswitch {\n\tcase strings.HasPrefix(unParsed, \"==\"):\n\t\tm.Operator = EqualToOperator\n\t\toperatorLength = 2\n\tcase strings.HasPrefix(unParsed, \"!=\"):\n\t\tm.Operator = UnequalToOperator\n\t\toperatorLength = 2\n\tcase strings.HasPrefix(unParsed, \"<=\"):\n\t\tm.Operator = LessThanOrEqualToOperator\n\t\toperatorLength = 2\n\tcase strings.HasPrefix(unParsed, \">=\"):\n\t\tm.Operator = GreaterThanOrEqualToOperator\n\t\toperatorLength = 2\n\tcase strings.HasPrefix(unParsed, \"<\"):\n\t\tm.Operator = LessThanOperator\n\t\toperatorLength = 1\n\tcase strings.HasPrefix(unParsed, \">\"):\n\t\tm.Operator = GreaterThanOperator\n\t\toperatorLength = 1\n\tdefault:\n\t\terr = fmt.Errorf(\"matcher %q: no valid comparison operator\", s)\n\t\treturn\n\t}\n\tunParsed = unParsed[operatorLength:] // Discard parsed operator\n\n\tskipToNonSpaceCharacter(&unParsed)\n\tn, err := strconv.ParseInt(unParsed, 10, 64)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"matcher %q: no valid right operand\", s)\n\t\treturn\n\t}\n\tm.RightOperand = int64(n)\n\n\treturn\n}", "func parseBeforeQuery(p *parser) parserStateFn {\n\ttok := p.next()\n\tswitch tok.typ {\n\tcase tokTypeError:\n\t\tp.backup(tok)\n\t\treturn parseErrorTok\n\tcase tokTypeEOF:\n\t\tp.backup(tok)\n\t\treturn parseEOFTok\n\tcase tokTypeOpenParen:\n\t\t// Push the '(' onto the ops stack. It will be the marker at which to\n\t\t// stop when the ')' token is parsed.\n\t\tp.stagedOps.Push(tok)\n\t\treturn parseBeforeQuery\n\tcase tokTypeNot:\n\t\tp.stageBoolOp(tok)\n\t\tp.incompleteBoolOp = true\n\t\treturn parseBeforeQuery\n\tcase tokTypeUnquotedLiteral, tokTypeQuotedLiteral:\n\t\tp.incompleteBoolOp = false\n\t\tswitch tok2 := p.peek(); tok2.typ {\n\t\tcase tokTypeError:\n\t\t\treturn parseErrorTok\n\t\tcase tokTypeGt, tokTypeGte, tokTypeLt, tokTypeLte:\n\t\t\t// E.g.: `a.field >= 100`, `some.date.field < \"2021-02\"`\n\t\t\tif tok.typ == tokTypeQuotedLiteral {\n\t\t\t\treturn p.errorfAt(tok.pos, \"a *quoted* field for a range query is not yet supported\")\n\t\t\t}\n\t\t\tp.field = &tok\n\t\t\treturn parseRangeQuery\n\t\tcase tokTypeColon:\n\t\t\t// E.g.: `foo:value1 value2`, `foo:(a or b)`, `foo:(a and b and c)`,\n\t\t\t// `foo:*`\n\t\t\tif tok.typ == tokTypeQuotedLiteral {\n\t\t\t\treturn p.errorfAt(tok.pos, \"a *quoted* field for a term query is not yet supported\")\n\t\t\t}\n\t\t\tp.field = &tok\n\t\t\treturn parseTermsQuery\n\t\tdefault:\n\t\t\t// E.g.: `foo bar baz`\n\t\t\t// No range operator and no colon means this is a query without\n\t\t\t// a field name. In Kibana, this matches against \"default fields\".\n\t\t\ttermTok := tok\n\t\t\tvar terms []term\n\t\t\tfor {\n\t\t\t\tif termTok.typ == tokTypeUnquotedLiteral {\n\t\t\t\t\tterms = append(terms, newTerm(termTok.val))\n\t\t\t\t} else if termTok.typ == tokTypeQuotedLiteral {\n\t\t\t\t\tterms = append(terms, newQuotedTerm(termTok.val))\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttermTok = p.next()\n\t\t\t}\n\t\t\tp.backup(termTok)\n\t\t\tp.filter.addStep(&rpnDefaultFieldsTermsQuery{terms: terms})\n\t\t\treturn parseAfterQuery\n\t\t}\n\tdefault:\n\t\treturn p.errorfAt(tok.pos,\n\t\t\t\"expecting a literal, 'not', or '('; got %s\", tok.typ)\n\t}\n}", "func TestRevParsing03(t *testing.T) {\n\tvar q = \"*Ops;AUTHORS:ops-prod-vpc1-mon\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed [reverse lookup with attr and hint]\", q)\n\t}\n\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tvar expected = []string{\"ops-prod-vpc1-mon\"}\n\tif len(errs) != 0 || !compare(*result, expected) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", q, expected, *result)\n\t}\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func parseRangeQuery(p *parser) parserStateFn {\n\topTok := p.next() // Already checked to be the range operator token.\n\tvalTok := p.next()\n\tswitch valTok.typ {\n\tcase tokTypeError:\n\t\tp.backup(valTok)\n\t\treturn parseErrorTok\n\tcase tokTypeUnquotedLiteral, tokTypeQuotedLiteral:\n\t\tvar trm term\n\t\tif valTok.typ == tokTypeUnquotedLiteral {\n\t\t\ttrm = newTerm(valTok.val)\n\t\t} else {\n\t\t\ttrm = newQuotedTerm(valTok.val)\n\t\t}\n\t\tif trm.Wildcard {\n\t\t\treturn p.errorfAt(valTok.pos, \"cannot have a wildcard in range query token\")\n\t\t}\n\t\tvar q rpnStep\n\t\tswitch opTok.typ {\n\t\tcase tokTypeGt:\n\t\t\tq = &rpnGtRangeQuery{\n\t\t\t\tfield: p.field.val,\n\t\t\t\tterm: trm,\n\t\t\t\tlogLevelLess: p.logLevelLess,\n\t\t\t}\n\t\tcase tokTypeGte:\n\t\t\tq = &rpnGteRangeQuery{\n\t\t\t\tfield: p.field.val,\n\t\t\t\tterm: trm,\n\t\t\t\tlogLevelLess: p.logLevelLess,\n\t\t\t}\n\t\tcase tokTypeLt:\n\t\t\tq = &rpnLtRangeQuery{\n\t\t\t\tfield: p.field.val,\n\t\t\t\tterm: trm,\n\t\t\t\tlogLevelLess: p.logLevelLess,\n\t\t\t}\n\t\tcase tokTypeLte:\n\t\t\tq = &rpnLteRangeQuery{\n\t\t\t\tfield: p.field.val,\n\t\t\t\tterm: trm,\n\t\t\t\tlogLevelLess: p.logLevelLess,\n\t\t\t}\n\t\tdefault:\n\t\t\tlg.Fatalf(\"invalid opTok.typ=%v while parsing range query\", opTok.typ)\n\t\t}\n\t\tp.filter.addStep(q)\n\t\tp.field = nil\n\t\treturn parseAfterQuery\n\tdefault:\n\t\treturn p.errorfAt(valTok.pos, \"expected a literal after '%s'; got %s\",\n\t\t\topTok.val, valTok.typ)\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func Parse(s string) (Matcher, error) {\n\tleft, right, operator := beforeAndAfterLogicalOperator(s)\n\tif operator == NoLogicalOperator {\n\t\treturn parseMatcherWithoutLogicalOperator(s)\n\t}\n\n\tvar matcher MatcherWithLogicalOperator\n\tmatcher.Operator = operator\n\tvar err error\n\tmatcher.LeftMatcher, err = Parse(strings.TrimSpace(left))\n\tif err != nil {\n\t\treturn matcher, err\n\t}\n\tmatcher.RightMatcher, err = Parse(strings.TrimSpace(right))\n\treturn matcher, err\n}", "func TestRevParsing01(t *testing.T) {\n\tvar q = \"*range1001.ops.example.com\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed [basic reverse lookup]\", q)\n\t}\n\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tvar expected = []string{\"ops-prod-vpc1-range\"}\n\tif len(errs) != 0 || !compare(*result, expected) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", q, expected, *result)\n\t}\n}", "func parseOpEquStat(node *node32) (RHS, error) {\n\trhs := new(ExpressionRHS)\n\trhs.SetToken(&node.token32)\n\n\tlhs, err := parseExpr(nextNode(node, ruleASSIGNLHS).up)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texprNode := nextNode(node, ruleEXPR)\n\texpr, err := parseExpr(exprNode.up)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch nextNode(node, ruleOPEQU).up.pegRule {\n\tcase rulePLUSEQU:\n\t\tbinOp := &BinaryOperatorAdd{BinaryOperatorBase{rhs: expr, lhs: lhs}}\n\t\tbinOp.SetToken(&node.token32)\n\t\trhs.expr = binOp\n\n\tcase ruleMINUSEQU:\n\t\tbinOp := &BinaryOperatorSub{BinaryOperatorBase{rhs: expr, lhs: lhs}}\n\t\tbinOp.SetToken(&node.token32)\n\t\trhs.expr = binOp\n\n\tcase ruleSTAREQU:\n\t\tbinOp := &BinaryOperatorMult{BinaryOperatorBase{rhs: expr, lhs: lhs}}\n\t\tbinOp.SetToken(&node.token32)\n\t\trhs.expr = binOp\n\n\tcase ruleDIVEQU:\n\t\tbinOp := &BinaryOperatorDiv{BinaryOperatorBase{rhs: expr, lhs: lhs}}\n\t\tbinOp.SetToken(&node.token32)\n\t\trhs.expr = binOp\n\n\tcase ruleMODEQU:\n\t\tbinOp := &BinaryOperatorMod{BinaryOperatorBase{rhs: expr, lhs: lhs}}\n\t\tbinOp.SetToken(&node.token32)\n\t\trhs.expr = binOp\n\t}\n\n\treturn rhs, nil\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func parseRHS(node *node32) (RHS, error) {\n\tswitch node.pegRule {\n\tcase ruleNEWPAIR:\n\t\tvar err error\n\t\tpair := new(PairLiterRHS)\n\n\t\tpair.SetToken(&node.token32)\n\n\t\tfstNode := nextNode(node, ruleEXPR)\n\t\tif pair.fst, err = parseExpr(fstNode.up); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsndNode := nextNode(fstNode.next, ruleEXPR)\n\t\tif pair.snd, err = parseExpr(sndNode.up); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn pair, nil\n\tcase ruleARRAYLITER:\n\t\tnode = node.up\n\n\t\tarr := new(ArrayLiterRHS)\n\n\t\tarr.SetToken(&node.token32)\n\n\t\tfor node = nextNode(node, ruleEXPR); node != nil; node = nextNode(node.next, ruleEXPR) {\n\t\t\tvar err error\n\t\t\tvar expr Expression\n\n\t\t\tif expr, err = parseExpr(node.up); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tarr.elements = append(arr.elements, expr)\n\t\t}\n\n\t\treturn arr, nil\n\tcase rulePAIRELEM:\n\t\ttarget := new(PairElemRHS)\n\n\t\ttarget.SetToken(&node.token32)\n\n\t\tfstNode := nextNode(node.up, ruleFST)\n\t\ttarget.snd = fstNode == nil\n\n\t\texprNode := nextNode(node.up, ruleEXPR)\n\t\tvar err error\n\t\tif target.expr, err = parseExpr(exprNode.up); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn target, nil\n\tcase ruleFCALL:\n\t\tnode = node.up\n\t\tcall := new(FunctionCallRHS)\n\n\t\tcall.SetToken(&node.token32)\n\n\t\tobjNode := nextNode(node, ruleCLASSOBJ)\n\t\tif objNode != nil {\n\t\t\tcall.obj = objNode.match\n\t\t}\n\n\t\tidentNode := nextNode(node, ruleIDENT)\n\t\tcall.ident = identNode.match\n\n\t\targlistNode := nextNode(node, ruleARGLIST)\n\t\tif arglistNode == nil {\n\t\t\treturn call, nil\n\t\t}\n\n\t\tfor argNode := nextNode(arglistNode.up, ruleEXPR); argNode != nil; argNode = nextNode(argNode.next, ruleEXPR) {\n\t\t\tvar err error\n\t\t\tvar expr Expression\n\n\t\t\tif expr, err = parseExpr(argNode.up); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tcall.args = append(call.args, expr)\n\t\t}\n\n\t\treturn call, nil\n\tcase ruleEXPR:\n\t\texprRHS := new(ExpressionRHS)\n\n\t\texprRHS.SetToken(&node.token32)\n\n\t\tvar err error\n\t\tvar expr Expression\n\t\tif expr, err = parseExpr(node.up); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\texprRHS.expr = expr\n\n\t\treturn exprRHS, nil\n\tcase ruleNEW:\n\t\tnewInst := new(NewInstanceRHS)\n\n\t\tnewInst.SetToken(&node.token32)\n\n\t\tidentNode := nextNode(node, ruleIDENT)\n\n\t\tnewInst.wtype = &ClassType{name: identNode.match}\n\n\t\targlistNode := nextNode(node, ruleARGLIST)\n\t\tif arglistNode != nil {\n\t\t\tfor argNode := nextNode(arglistNode.up, ruleEXPR); argNode != nil; argNode = nextNode(argNode.next, ruleEXPR) {\n\t\t\t\tvar err error\n\t\t\t\tvar expr Expression\n\n\t\t\t\tif expr, err = parseExpr(argNode.up); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tnewInst.args = append(newInst.args, expr)\n\t\t\t}\n\t\t}\n\n\t\treturn newInst, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unexpected rule %s %s\", node.String(), node.match)\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func TestQueryParser(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tinputQuery string\n\t\texpectedProblemSelector string\n\t\texpectedEntitySelector string\n\t}{\n\t\t{\n\t\t\tname: \"valid\",\n\t\t\tinputQuery: \"PV2;problemSelector=status(open)&entitySelector=mzId(7030365576649815430)\",\n\t\t\texpectedProblemSelector: \"status(open)\",\n\t\t\texpectedEntitySelector: \"mzId(7030365576649815430)\",\n\t\t},\n\t\t{\n\t\t\tname: \"valid - empty\",\n\t\t\tinputQuery: \"PV2;\",\n\t\t},\n\t\t{\n\t\t\tname: \"valid\",\n\t\t\tinputQuery: \"PV2;entitySelector=mzId(7030365576649815430)\",\n\t\t\texpectedEntitySelector: \"mzId(7030365576649815430)\",\n\t\t},\n\t\t{\n\t\t\tname: \"valid\",\n\t\t\tinputQuery: \"PV2;problemSelector=status(open)\",\n\t\t\texpectedProblemSelector: \"status(open)\",\n\t\t},\n\t}\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tquery, err := NewQueryParser(tc.inputQuery).Parse()\n\n\t\t\tassert.NoError(t, err)\n\t\t\tif assert.NotNil(t, query) {\n\t\t\t\tassert.EqualValues(t, tc.expectedProblemSelector, query.GetProblemSelector())\n\t\t\t\tassert.EqualValues(t, tc.expectedEntitySelector, query.GetEntitySelector())\n\t\t\t}\n\t\t})\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func splitTerm(term string) (lhs, op, rhs string, ok bool) {\n\tfor i := range term {\n\t\tremaining := term[i:]\n\t\tfor _, op := range termOperators {\n\t\t\tif strings.HasPrefix(remaining, op) {\n\t\t\t\treturn term[0:i], op, term[i+len(op):], true\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", \"\", \"\", false\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (s *SelectParser) parseWhereExpr(expr sqlparser.Expr) SqlAny {\n\tswitch expr := expr.(type) {\n\tcase *sqlparser.AndExpr:\n\t\treturn &AndOp{\n\t\t\tLeft: s.parseWhereExpr(expr.Left),\n\t\t\tRight: s.parseWhereExpr(expr.Right),\n\t\t}\n\tcase *sqlparser.OrExpr:\n\t\treturn &OrOp{\n\t\t\tLeft: s.parseWhereExpr(expr.Left),\n\t\t\tRight: s.parseWhereExpr(expr.Right),\n\t\t}\n\tcase *sqlparser.NotExpr:\n\t\treturn &NotOp{\n\t\t\tExpr: s.parseWhereExpr(expr.Expr),\n\t\t}\n\tcase *sqlparser.ParenExpr:\n\t\treturn s.parseWhereExpr(expr.Expr)\n\tcase *sqlparser.ComparisonExpr:\n\t\t//if !supportedCompOps.Contains(expr.Operator) {\n\t\t//\tpanic(fmt.Errorf(\"unsupported operator: %s\", expr.Operator))\n\t\t//}\n\t\treturn &CompOp{\n\t\t\tOperator: expr.Operator,\n\t\t\tLeft: s.parseWhereExpr(expr.Left),\n\t\t\tRight: s.parseWhereExpr(expr.Right),\n\t\t}\n\tcase *sqlparser.RangeCond:\n\t\trangeOp := &RangeOp{\n\t\t\tLeft: s.parseWhereExpr(expr.Left),\n\t\t\tFrom: s.parseWhereExpr(expr.From),\n\t\t\tTo: s.parseWhereExpr(expr.To),\n\t\t}\n\t\tswitch expr.Operator {\n\t\tcase sqlparser.BetweenStr:\n\t\t\treturn rangeOp\n\t\tcase sqlparser.NotBetweenStr:\n\t\t\treturn &NotOp{\n\t\t\t\tExpr: rangeOp,\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"bug: RangeCond.Operator=%s\", expr.Operator))\n\t\t}\n\tcase *sqlparser.SQLVal:\n\t\tswitch expr.Type {\n\t\tcase sqlparser.StrVal:\n\t\t\treturn SqlString(string(expr.Val))\n\t\tcase sqlparser.IntVal:\n\t\t\tval, err := strconv.ParseInt(string(expr.Val), 10, 64)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn SqlBigInt(val)\n\t\tdefault:\n\t\t\t// TODO\n\t\t\tpanic(\"todo\")\n\t\t}\n\tcase *sqlparser.ColName:\n\t\ttable := s.table.Name\n\t\tif expr.Qualifier.Name.String() != \"\" {\n\t\t\ttable = expr.Qualifier.Name.String()\n\t\t}\n\t\treturn &SqlField{\n\t\t\tField: Field{\n\t\t\t\tTable: table,\n\t\t\t\tName: expr.Name.String(),\n\t\t\t},\n\t\t}\n\tcase *sqlparser.IntervalExpr:\n\t\t// TODO\n\t\tpanic(\"todo\")\n\n\tcase *sqlparser.FuncExpr:\n\t\tif !expr.Qualifier.IsEmpty() {\n\t\t\tpanic(ErrFunctionQualifier)\n\t\t}\n\t\tif expr.Distinct {\n\t\t\tpanic(ErrDistinct)\n\t\t}\n\n\t\tvar found bool\n\t\tvar sqlfunc SqlFunc\n\t\tfor i := range funcs {\n\t\t\tif expr.Name.EqualString(funcs[i].Name) {\n\t\t\t\tfound = true\n\t\t\t\tsqlfunc = funcs[i]\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tpanic(fmt.Errorf(\"not found %s function\", expr.Name.String()))\n\t\t}\n\n\t\t// 関数の引数をパースするは、補完されるテーブル名を SqlFunc で定義されたテーブル名に変更する。\n\t\tparser := s\n\t\tif sqlfunc.Table != \"\" {\n\t\t\ttable, ok := findTableByName(sqlfunc.Table)\n\t\t\tif !ok {\n\t\t\t\tpanic(fmt.Errorf(\"not found %s table\", sqlfunc.Table))\n\t\t\t}\n\t\t\tparser = &SelectParser{\n\t\t\t\ttable: table,\n\t\t\t}\n\t\t}\n\n\t\tvar fnargs []SqlAny\n\t\tfor _, arg := range expr.Exprs {\n\t\t\tfnargs = append(fnargs, parser.parseSelectExpr(arg))\n\t\t}\n\t\treturn sqlfunc.Parse(fnargs...)\n\tdefault:\n\t\tpanic(\"bug\")\n\t}\n\treturn nil\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func beforeAndAfterLogicalOperator(s string) (string, string, LogicalOperator) {\n\tlogicalAndRegexp := regexp.MustCompilePOSIX(\"&&\")\n\tlogicalOrRegexp := regexp.MustCompilePOSIX(`\\|\\|`)\n\n\tbefore, after, ok := helper.BeforeAndAfter(logicalAndRegexp, s)\n\tif ok {\n\t\treturn before, after, LogicalAndOperator\n\t}\n\n\tbefore, after, ok = helper.BeforeAndAfter(logicalOrRegexp, s)\n\tif ok {\n\t\treturn before, after, LogicalOrOperator\n\t}\n\n\treturn \"\", \"\", NoLogicalOperator\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (parser *Parser) ParseBinOpRHS(exprPrec int, lhs ExprAST) (ExprAST, error) {\n\tfor {\n\t\t// If this is a binop, find its precedence.\n\t\tprecedence := parser.tokenPrecedence()\n\n\t\t// If this is a binop that binds at least as tightly as the current binop,\n\t\t// consume it, otherwise we are done.\n\t\tif precedence < exprPrec {\n\t\t\treturn lhs, nil\n\t\t}\n\n\t\t// Okay, we know this is a binop.\n\t\tbinOp := parser.lexer.LastChar\n\t\tparser.Next() // Eat binary operator.\n\n\t\t// Parse the primary expression after the binary operator.\n\t\trhs, rhsErr := parser.ParsePrimary()\n\t\tif rhsErr != nil {\n\t\t\treturn nil, rhsErr\n\t\t}\n\n\t\t// If BinOp binds less tightly with RHS than the operator after RHS, let\n\t\t// the pending operator take RHS as its LHS.\n\t\tnextPrecedence := parser.tokenPrecedence()\n\t\tif precedence < nextPrecedence {\n\t\t\tvar rhsError error\n\t\t\trhs, rhsError = parser.ParseBinOpRHS(precedence+1, rhs)\n\t\t\tif rhsError != nil {\n\t\t\t\treturn nil, rhsErr\n\t\t\t}\n\t\t}\n\n\t\t// Merge LHS/RHS.\n\t\tlhs = &BinaryExprAST{binOp, lhs, rhs}\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func TestParsing12(t *testing.T) {\n\tvar q = \"1-2-3-4\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed (a.b.c.d is valid ip)\", q)\n\t}\n\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tvar expected = []string{\"1-2-3-4\"}\n\tif len(errs) != 0 || !compare(*result, expected) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", q, expected, *result)\n\t}\n}", "func TestInvalidFilterSyntax(t *testing.T) {\n\tqueries := []string{\n\t\t\"()\", // It's not a boolean expression\n\t\t\"(TRUE)\",\n\t\t\"(City)\",\n\t\t\"(\",\n\t\t\"((((\",\n\t\t\")\",\n\t\t\"12345\", // Number 12345 is not a boolean expression\n\t\t\"0\", // Number 0 is not a boolean expression\n\t\t\"'123'\", // String '123' is not a boolean expression\n\t\t\"TRUE\", // Should be 'true' lowercase\n\t\t\"FALSE\", // Should be 'false' lowercase\n\t\t\"yes\", // yes is not a boolean expression\n\t\t\"no\", // yes is not a boolean expression\n\t\t\"\", // Empty string.\n\t\t\"eq\", // Just a single logical operator\n\t\t\"and\", // Just a single logical operator\n\t\t\"add\", // Just a single arithmetic operator\n\t\t\"add \", // Just a single arithmetic operator\n\t\t\"add 2\", // Missing operands\n\t\t\"add 2 3\", // Missing operands\n\t\t\"City\", // Just a single literal\n\t\t\"City City City City\", // Sequence of literals\n\t\t\"City eq\", // Missing operand\n\t\t\"City eq (\", // Wrong operand\n\t\t\"City eq )\", // Wrong operand\n\t\t\"City equals 'Dallas'\", // Unknown operator that starts with the same letters as a known operator\n\t\t\"City near 'Dallas'\", // Unknown operator that starts with the same letters as a known operator\n\t\t\"City isNot 'Dallas'\", // Unknown operator\n\t\t\"not [City eq 'Dallas']\", // Wrong delimiter\n\t\t\"not (City eq )\", // Missing operand\n\t\t\"not ((City eq 'Dallas'\", // Missing closing parenthesis\n\t\t\"not (City eq 'Dallas'\", // Missing closing parenthesis\n\t\t\"not (City eq 'Dallas'))\", // Extraneous closing parenthesis\n\t\t\"not City eq 'Dallas')\", // Missing open parenthesis\n\t\t\"City eq 'Dallas' orCity eq 'Houston'\", // missing space between or and City\n\t\t// TODO: the query below should fail.\n\t\t//\"Tags/any(var:var/Key eq 'Site') orTags/any(var:var/Key eq 'Site')\",\n\t\t\"not (City eq 'Dallas') and Name eq 'Houston')\",\n\t\t\"Tags/all()\", // The all operator cannot be used without an argument expression.\n\t\t\"LastName contains 'Smith'\", // Previously the godata library was not returning an error.\n\t\t\"contains\", // Function with missing parenthesis and arguments\n\t\t\"contains()\", // Function with missing arguments\n\t\t\"contains LastName, 'Smith'\", // Missing parenthesis\n\t\t\"contains(LastName)\", // Insufficent number of function arguments\n\t\t\"contains(LastName, 'Smith'))\", // Extraneous closing parenthesis\n\t\t\"contains(LastName, 'Smith'\", // Missing closing parenthesis\n\t\t\"contains LastName, 'Smith')\", // Missing open parenthesis\n\t\t\"City eq 'Dallas' 'Houston'\", // extraneous string value\n\t\t//\"contains(Name, 'a', 'b', 'c', 'd')\", // Too many function arguments\n\t}\n\tfor _, input := range queries {\n\t\tq, err := ParseFilterString(input)\n\t\tif err == nil {\n\t\t\t// The parser has incorrectly determined the syntax is valid.\n\t\t\tprintTree(q.Tree)\n\t\t\tt.Errorf(\"The query '$filter=%s' is not valid ODATA syntax. The ODATA parser should return an error\", input)\n\t\t\treturn\n\t\t}\n\t}\n}", "func ParseCondition(value string) Condition {\n\tvar empty Condition\n\n\tts := strings.SplitN(value, \"=\", 2)\n\n\tif len(ts) != 2 {\n\t\treturn empty\n\t}\n\n\tsm := strings.SplitN(ts[1], \",\", 3)\n\tm, err := time.ParseDuration(sm[1])\n\n\tif err != nil {\n\t\treturn empty\n\t}\n\n\treturn Condition{ConditionType: v1.NodeConditionType(ts[0]), ConditionValue: v1.ConditionStatus(sm[0]), TimeInEffect: m, Action: sm[2]}\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func prefixHandler(query string) (string, string) {\n\tif strings.HasPrefix(query, \"<=\") ||\n\t\tstrings.HasPrefix(query, \">=\") {\n\t\treturn query[:2], query[2:]\n\t} else if strings.HasPrefix(query, \"<\") ||\n\t\tstrings.HasPrefix(query, \">\") {\n\t\treturn query[:1], query[1:]\n\t} else if strings.HasPrefix(query, \"(\") {\n\t\treturn \"startsWith\", query[1:]\n\t} else if strings.HasPrefix(query, \")\") {\n\t\treturn \"endsWith\", query[1:]\n\t} else if strings.HasPrefix(query, \"=\") {\n\t\treturn \"=\", query[1:]\n\t} else if strings.HasPrefix(query, \"!\") {\n\t\treturn \"!=\", query[1:]\n\t} else if strings.HasPrefix(query, \"~\") {\n\t\treturn \"interface\", query[1:]\n\t} else {\n\t\treturn \"default\", query\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func parseTermsQuery(p *parser) parserStateFn {\n\tp.next() // Consume the ':' token.\n\n\tvar terms []term\n\ttok := p.peek()\n\tswitch tok.typ {\n\tcase tokTypeError:\n\t\treturn parseErrorTok\n\tcase tokTypeUnquotedLiteral, tokTypeQuotedLiteral:\n\t\t// E.g. `foo:val1 val2`, `breakfast:*am eggs` or `foo:*`.\n\t\t// If at least one of the terms is `*`, then this is an \"exists query\".\n\t\thaveExistsTerm := false\n\t\tfor {\n\t\t\ttok := p.next()\n\t\t\tif tok.typ == tokTypeUnquotedLiteral {\n\t\t\t\tif tok.val == \"*\" {\n\t\t\t\t\thaveExistsTerm = true\n\t\t\t\t}\n\t\t\t\tterms = append(terms, newTerm(tok.val))\n\t\t\t} else if tok.typ == tokTypeQuotedLiteral {\n\t\t\t\tterms = append(terms, newQuotedTerm(tok.val))\n\t\t\t} else {\n\t\t\t\tp.backup(tok)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif haveExistsTerm {\n\t\t\tp.filter.addStep(&rpnExistsQuery{field: p.field.val})\n\t\t} else {\n\t\t\tp.filter.addStep(&rpnTermsQuery{field: p.field.val, terms: terms})\n\t\t}\n\t\tp.field = nil\n\t\treturn parseAfterQuery\n\tcase tokTypeOpenParen:\n\t\t// E.g. `foo:(a or b ...)` or `foo:(a and b and c)`.\n\t\tp.next() // Consume the open paren.\n\t\tmatchAll := false // True if the second form with `and`: `foo:(a and b ...)`.\n\t\tfor i := 0; true; i++ {\n\t\t\t// Expect literal ...\n\t\t\ttermTok := p.next()\n\t\t\tif termTok.typ == tokTypeUnquotedLiteral {\n\t\t\t\tterms = append(terms, newTerm(termTok.val))\n\t\t\t} else if termTok.typ == tokTypeQuotedLiteral {\n\t\t\t\tterms = append(terms, newQuotedTerm(termTok.val))\n\t\t\t} else {\n\t\t\t\treturn p.errorfAt(termTok.pos, \"expected literal, got %s\", termTok.typ)\n\t\t\t}\n\t\t\t// ... then ')' to complete the query, or 'and' or 'or' to repeat.\n\t\t\topTok := p.next()\n\t\t\tswitch opTok.typ {\n\t\t\tcase tokTypeCloseParen:\n\t\t\t\tif matchAll {\n\t\t\t\t\tp.filter.addStep(&rpnMatchAllTermsQuery{field: p.field.val, terms: terms})\n\t\t\t\t} else {\n\t\t\t\t\tp.filter.addStep(&rpnTermsQuery{field: p.field.val, terms: terms})\n\t\t\t\t}\n\t\t\t\tp.field = nil\n\t\t\t\treturn parseAfterQuery\n\t\t\tcase tokTypeOr:\n\t\t\t\tif i == 0 {\n\t\t\t\t\tmatchAll = false\n\t\t\t\t} else if matchAll {\n\t\t\t\t\treturn p.errorfAt(opTok.pos,\n\t\t\t\t\t\t\"cannot mix 'and' and 'or' in parenthesized value group\")\n\t\t\t\t}\n\t\t\tcase tokTypeAnd:\n\t\t\t\tif i == 0 {\n\t\t\t\t\tmatchAll = true\n\t\t\t\t} else if !matchAll {\n\t\t\t\t\treturn p.errorfAt(opTok.pos,\n\t\t\t\t\t\t\"cannot mix 'and' and 'or' in parenthesized value group\")\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn p.errorfAt(opTok.pos, \"expected ')', 'or', or 'and'; got %s\",\n\t\t\t\t\topTok.typ)\n\t\t\t}\n\t\t}\n\t\tpanic(fmt.Sprintf(\"unreachable code hit with KQL %q\", p.kql))\n\tdefault:\n\t\treturn p.errorfAt(tok.pos, \"expected a literal or '('; got %s\", tok.typ)\n\t}\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func TestFilterInOperatorBothSides(t *testing.T) {\n\ttokenizer := FilterTokenizer()\n\tinput := \"(1, 2) in ( ('ab', 'cd'), (1, 2), ('abc', 'def') )\"\n\n\texpect := []*Token{\n\t\t&Token{Value: \"(\", Type: FilterTokenOpenParen},\n\t\t&Token{Value: \"1\", Type: FilterTokenInteger},\n\t\t&Token{Value: \",\", Type: FilterTokenComma},\n\t\t&Token{Value: \"2\", Type: FilterTokenInteger},\n\t\t&Token{Value: \")\", Type: FilterTokenCloseParen},\n\t\t&Token{Value: \"in\", Type: FilterTokenLogical},\n\t\t&Token{Value: \"(\", Type: FilterTokenOpenParen},\n\n\t\t&Token{Value: \"(\", Type: FilterTokenOpenParen},\n\t\t&Token{Value: \"'ab'\", Type: FilterTokenString},\n\t\t&Token{Value: \",\", Type: FilterTokenComma},\n\t\t&Token{Value: \"'cd'\", Type: FilterTokenString},\n\t\t&Token{Value: \")\", Type: FilterTokenCloseParen},\n\t\t&Token{Value: \",\", Type: FilterTokenComma},\n\n\t\t&Token{Value: \"(\", Type: FilterTokenOpenParen},\n\t\t&Token{Value: \"1\", Type: FilterTokenInteger},\n\t\t&Token{Value: \",\", Type: FilterTokenComma},\n\t\t&Token{Value: \"2\", Type: FilterTokenInteger},\n\t\t&Token{Value: \")\", Type: FilterTokenCloseParen},\n\t\t&Token{Value: \",\", Type: FilterTokenComma},\n\n\t\t&Token{Value: \"(\", Type: FilterTokenOpenParen},\n\t\t&Token{Value: \"'abc'\", Type: FilterTokenString},\n\t\t&Token{Value: \",\", Type: FilterTokenComma},\n\t\t&Token{Value: \"'def'\", Type: FilterTokenString},\n\t\t&Token{Value: \")\", Type: FilterTokenCloseParen},\n\t\t&Token{Value: \")\", Type: FilterTokenCloseParen},\n\t}\n\ttokens, err := tokenizer.Tokenize(input)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tresult, err := CompareTokens(expect, tokens)\n\tif !result {\n\t\tt.Error(err)\n\t}\n\tvar postfix *tokenQueue\n\tpostfix, err = GlobalFilterParser.InfixToPostfix(tokens)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\texpect = []*Token{\n\t\t&Token{Value: \"1\", Type: FilterTokenInteger},\n\t\t&Token{Value: \"2\", Type: FilterTokenInteger},\n\t\t&Token{Value: \"2\", Type: TokenTypeArgCount},\n\t\t&Token{Value: TokenListExpr, Type: TokenTypeListExpr},\n\n\t\t&Token{Value: \"'ab'\", Type: FilterTokenString},\n\t\t&Token{Value: \"'cd'\", Type: FilterTokenString},\n\t\t&Token{Value: \"2\", Type: TokenTypeArgCount},\n\t\t&Token{Value: TokenListExpr, Type: TokenTypeListExpr},\n\n\t\t&Token{Value: \"1\", Type: FilterTokenInteger},\n\t\t&Token{Value: \"2\", Type: FilterTokenInteger},\n\t\t&Token{Value: \"2\", Type: TokenTypeArgCount},\n\t\t&Token{Value: TokenListExpr, Type: TokenTypeListExpr},\n\n\t\t&Token{Value: \"'abc'\", Type: FilterTokenString},\n\t\t&Token{Value: \"'def'\", Type: FilterTokenString},\n\t\t&Token{Value: \"2\", Type: TokenTypeArgCount},\n\t\t&Token{Value: TokenListExpr, Type: TokenTypeListExpr},\n\n\t\t&Token{Value: \"3\", Type: TokenTypeArgCount},\n\t\t&Token{Value: TokenListExpr, Type: TokenTypeListExpr},\n\n\t\t&Token{Value: \"in\", Type: FilterTokenLogical},\n\t}\n\tresult, err = CompareQueue(expect, postfix)\n\tif !result {\n\t\tfmt.Printf(\"postfix notation: %s\\n\", postfix.String())\n\t\tt.Error(err)\n\t}\n\n\ttree, err := GlobalFilterParser.PostfixToTree(postfix)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tvar treeExpect []expectedParseNode = []expectedParseNode{\n\t\t{\"in\", 0},\n\t\t{TokenListExpr, 1},\n\t\t{\"1\", 2},\n\t\t{\"2\", 2},\n\t\t// ('ab', 'cd'), (1, 2), ('abc', 'def')\n\t\t{TokenListExpr, 1},\n\t\t{TokenListExpr, 2},\n\t\t{\"'ab'\", 3},\n\t\t{\"'cd'\", 3},\n\t\t{TokenListExpr, 2},\n\t\t{\"1\", 3},\n\t\t{\"2\", 3},\n\t\t{TokenListExpr, 2},\n\t\t{\"'abc'\", 3},\n\t\t{\"'def'\", 3},\n\t}\n\tpos := 0\n\terr = CompareTree(tree, treeExpect, &pos, 0)\n\tif err != nil {\n\t\tprintTree(tree)\n\t\tt.Errorf(\"Tree representation does not match expected value. error: %s\", err.Error())\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (q *Equals) Parse(params map[string]interface{}) error {\n\tfield, ok := json.GetString(params, \"field\")\n\tif !ok {\n\t\treturn fmt.Errorf(\"`field` parameter missing from query\")\n\t}\n\tvalue, ok := json.Get(params, \"value\")\n\tif !ok {\n\t\treturn fmt.Errorf(\"`value` parameter missing from query\")\n\t}\n\tq.Field = field\n\tq.Value = value\n\treturn nil\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementNotStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementNotStatementStatementOrStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementNotStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatementFieldToMatchQueryStringPtrOutput)\n}", "func TestParsing05(t *testing.T) {\n\tvar q = \"%a-b-c%d\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err == nil {\n\t\tt.Errorf(\"Expected Error, (Query: %s) should NOT BE parsed [contains %%, where not expected]\", q)\n\t}\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func ParseCondition(inputStr string) (ast.Condition, error) {\n\tlogger := logrus.WithField(\"method\", \"ParseCondition\")\n\tlxr := lexer.New(inputStr)\n\temptySwaggerTypes := []types.Type{}\n\tprsr := New(lxr, emptySwaggerTypes)\n\tast := prsr.parseCondition(PRECEDENCE_LOWEST)\n\tlogger.WithField(\"condition\", inputStr).WithField(\"ast\", fmt.Sprintf(\"%#v\", ast)).Debug(\"ParseCondition\")\n\tif len(prsr.errors) > 0 {\n\t\treturn nil, errors.New(strings.Join(prsr.errors, \"\\n\"))\n\t}\n\treturn ast, nil\n}", "func (p *Parser) parseOperator() (op selection.Operator, err error) {\n\ttok, lit := p.consume(KeyAndOperator)\n\tswitch tok {\n\t// DoesNotExistToken shouldn't be here because it's a unary operator, not a binary operator\n\tcase InToken:\n\t\top = selection.In\n\tcase EqualsToken:\n\t\top = selection.Equals\n\tcase DoubleEqualsToken:\n\t\top = selection.DoubleEquals\n\tcase GreaterThanToken:\n\t\top = selection.GreaterThan\n\tcase LessThanToken:\n\t\top = selection.LessThan\n\tcase NotInToken:\n\t\top = selection.NotIn\n\tcase NotEqualsToken:\n\t\top = selection.NotEquals\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"found '%s', expected: %v\", lit, strings.Join(binaryOperators, \", \"))\n\t}\n\treturn op, nil\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatch) *WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func TestParsing11(t *testing.T) {\n\tvar q = \"a-b-c-d\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed (a.b.c.d is valid ip)\", q)\n\t}\n\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tvar expected = []string{\"a-b-c-d\"}\n\tif len(errs) != 0 || !compare(*result, expected) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", q, expected, *result)\n\t}\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchOutput) QueryString() WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatch) *WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func evalBinaryStringExpr(ctx *Ctx, x reflect.Value, op token.Token, y reflect.Value) (reflect.Value, error) {\n\tvar err error\n\tvar r string\n\tvar b bool\n\tis_bool := false\n\n\txx, yy := x.String(), y.String()\n\tswitch op {\n\tcase token.ADD:\tr = xx + yy\n\tcase token.EQL: b = xx == yy; is_bool = true\n\tcase token.NEQ: b = xx != yy; is_bool = true\n\tcase token.LEQ: b = xx <= yy; is_bool = true\n\tcase token.GEQ: b = xx >= yy; is_bool = true\n\tcase token.LSS: b = xx < yy; is_bool = true\n\tcase token.GTR: b = xx > yy; is_bool = true\n\tdefault: err = ErrInvalidOperands{x, op, y}\n\t}\n\tif is_bool {\n\t\treturn reflect.ValueOf(b), err\n\t} else {\n\t\treturn reflect.ValueOf(r).Convert(x.Type()), err\n\t}\n}", "func (pagination *Pagination) ParsingQuery() Where {\n\twhere := make(Where)\n\tquery := pagination.ctx.URL.Query()\n\tfor key, val := range query {\n\t\tif v, ok := pagination.fieldMapping[key]; ok {\n\t\t\tkey = v\n\t\t}\n\n\t\tif len(val) == 1 {\n\t\t\tif val[0] != \"\" {\n\t\t\t\twhere[key] = val[0]\n\t\t\t}\n\t\t}\n\t\tif len(val) > 1 {\n\t\t\twhere[key] = val\n\t\t}\n\t}\n\treturn where\n}", "func TestParsingKey03(t *testing.T) {\n\tvar q = \"(*Ops;AUTHORS , *Vigith Maurice;AUTHORS) ,& (ops-prod-vpc1-range, ops-prod-vpc1-mon)\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err != nil {\n\t\tt.Errorf(\"Expected NO Error, (Query: %s) should BE parsed [ Keys, eg (%%foo:KEY)]\", q)\n\t}\n\n\tr.Execute()\n\tresult, errs := r.Evaluate(store)\n\tvar expected = []string{\"ops-prod-vpc1-range\", \"ops-prod-vpc1-mon\"}\n\tif len(errs) != 0 || !compare(*result, expected) {\n\t\tt.Errorf(\"Expected NO Evaluate Error, (Query: %s) should BE %s [Got: %s]\", q, expected, *result)\n\t}\n}", "func Parse(expression string) Node {\n\tvar stack Stack\n\tpostfix := infixToPostfix(expression)\n\tfor _, c := range postfix {\n\t\tswitch c {\n\t\tcase ' ':\n\t\t\tbreak\n\t\tcase andOp:\n\t\t\ta := And{}\n\t\t\ta.Left, _ = stack.Pop().(Node)\n\t\t\ta.Right, _ = stack.Pop().(Node)\n\t\t\tstack.Push(a)\n\t\tcase orOp:\n\t\t\to := Or{}\n\t\t\to.Left, _ = stack.Pop().(Node)\n\t\t\to.Right, _ = stack.Pop().(Node)\n\t\t\tstack.Push(o)\n\t\tdefault:\n\t\t\tv, err := strconv.Atoi(string(c))\n\t\t\tif err != nil {\n\t\t\t\treturn Leaf{}\n\t\t\t}\n\t\t\tstack.Push(Leaf{Value: v})\n\t\t}\n\t}\n\tt, _ := stack.Pop().(Node)\n\treturn t\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput)\n}", "func (s *BaseSyslParserListener) EnterMatching_rhs(ctx *Matching_rhsContext) {}", "func TestParsingComb02(t *testing.T) {\n\tvar q = \"%a-b,%d,\"\n\tvar r = &RangeExpr{Buffer: q}\n\tr.Init()\n\tr.Expression.Init(q)\n\terr := r.Parse()\n\tif err == nil {\n\t\tt.Errorf(\"Expected Error, (Query: %s) should NOT BE parsed [Combined Expression (union) should not end with ,]\", q)\n\t}\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatch) *WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (p *parser) parseOperand(lhs bool) ast.Expr {\n\n\tswitch p.tok {\n\tcase token.IDENT:\n\t\tx := p.parseIdent()\n\t\t//\t\tif !lhs {\n\t\t//\t\t\tp.resolve(x)\n\t\t//\t\t}\n\t\treturn x\n\n\tcase token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING:\n\t\tx := &ast.BasicLit{ValuePos: p.pos, Kind: p.tok, Value: p.lit}\n\t\tp.next()\n\t\treturn x\n\n\tcase token.LPAREN:\n\t\tlparen := p.pos\n\t\tp.next()\n\t\tp.exprLev++\n\t\tx := p.parseOperand(false)\n\t\tp.exprLev--\n\t\trparen := p.expect(token.RPAREN)\n\t\treturn &ast.ParenExpr{Lparen: lparen, X: x, Rparen: rparen}\n\n\tdefault:\n\t\tp.errorExpected(p.pos, \"operand\")\n\t\treturn &ast.BadExpr{From: p.pos - 10, To: p.pos + 10}\n\t}\n\n}", "func And(parsers ...Parser) Parser {\n\treturn &andParser{parsers}\n}", "func (uri *URI) parseWithoutFragments(reqURI []byte) {\n\tif len(reqURI) == 0 {\n\t\treturn\n\t}\n\tqueryIndex := bytes.IndexByte(reqURI, '?')\n\tif queryIndex >= 0 {\n\t\turi.queries = reqURI[queryIndex:]\n\t\turi.parseWithoutQueriesFragments(reqURI[:queryIndex])\n\t} else {\n\t\turi.parseWithoutQueriesFragments(reqURI)\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchPtrOutput) QueryString() WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatch) *WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryString {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchOutput) QueryString() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatch) *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput)\n}", "func parse(expression string) ExpressionNode {\r\n\tnode := ExpressionNode{}\r\n\tsides := make([]string, 0)\r\n\tif strings.Contains(expression, \"+\") {\r\n\t\tnode.expression = \"+\"\r\n\t\tsides = strings.SplitN(expression, \"+\", 2)\r\n\t} else if strings.Contains(expression, \"-\") {\r\n\t\tnode.expression = \"-\"\r\n\t\tsides = strings.SplitN(expression, \"-\", 2)\r\n\t} else if strings.Contains(expression, \"*\") {\r\n\t\tnode.expression = \"*\"\r\n\t\tsides = strings.SplitN(expression, \"*\", 2)\r\n\t} else if strings.Contains(expression, \"/\") {\r\n\t\tnode.expression = \"/\"\r\n\t\tsides = strings.SplitN(expression, \"/\", 2)\r\n\t} else {\r\n\t\tnode.expression = expression\r\n\t\treturn node\r\n\t}\r\n\tleft := parse(sides[0])\r\n\tright := parse(sides[1])\r\n\tnode.left = &left\r\n\tnode.right = &right\r\n\treturn node\r\n}" ]
[ "0.6000679", "0.5544201", "0.5538723", "0.5515873", "0.53919816", "0.5371112", "0.5337646", "0.5244362", "0.5227058", "0.5201624", "0.5035713", "0.49393153", "0.49017668", "0.4891215", "0.48855764", "0.48798397", "0.48732585", "0.486875", "0.48676294", "0.4867318", "0.48652303", "0.48627603", "0.48452693", "0.484341", "0.4837792", "0.48359123", "0.48270056", "0.4814619", "0.4806367", "0.48027912", "0.47989747", "0.47800285", "0.47710973", "0.47663185", "0.4764101", "0.4759353", "0.4756586", "0.47527796", "0.4748543", "0.47473997", "0.47468612", "0.4740215", "0.47296426", "0.4724939", "0.47148362", "0.4713122", "0.47106326", "0.4708487", "0.47033477", "0.46880654", "0.4687376", "0.46822974", "0.46822903", "0.46657386", "0.4660814", "0.46569338", "0.46540222", "0.46500978", "0.46498895", "0.464435", "0.46320817", "0.46188098", "0.46073908", "0.46010774", "0.458682", "0.45704755", "0.45667174", "0.45628628", "0.45625916", "0.45616612", "0.45583323", "0.45577824", "0.45536745", "0.4537234", "0.45369223", "0.4528909", "0.45227736", "0.45198038", "0.45178464", "0.45147336", "0.45089853", "0.45055744", "0.4501939", "0.4497231", "0.44896036", "0.44873938", "0.4481794", "0.44738188", "0.4446299", "0.44392306", "0.44326127", "0.4426025", "0.4417516", "0.44055554", "0.440537", "0.44049498", "0.44030827", "0.43937227", "0.43930027", "0.4392299" ]
0.73141813
0
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be nonnil.
func (in *DailyRule) DeepCopyInto(out *DailyRule) { *out = *in }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RunInfo) DeepCopyInto(out *RunInfo) {\n\t*out = *r\n}", "func (in *Base) DeepCopyInto(out *Base) {\n\t*out = *in\n\treturn\n}", "func (in *ForkObject) DeepCopyInto(out *ForkObject) {\n\t*out = *in\n}", "func (in *TargetObjectInfo) DeepCopyInto(out *TargetObjectInfo) {\n\t*out = *in\n}", "func (in *DebugObjectInfo) DeepCopyInto(out *DebugObjectInfo) {\n\t*out = *in\n}", "func (in *Input) DeepCopyInto(out *Input) {\n\t*out = *in\n}", "func (u *SSN) DeepCopyInto(out *SSN) {\n\t*out = *u\n}", "func (in *ExistPvc) DeepCopyInto(out *ExistPvc) {\n\t*out = *in\n}", "func (in *DockerStep) DeepCopyInto(out *DockerStep) {\n\t*out = *in\n\tif in.Inline != nil {\n\t\tin, out := &in.Inline, &out.Inline\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tout.Auth = in.Auth\n\treturn\n}", "func (in *Container) DeepCopyInto(out *Container) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.Command != nil {\n\t\tin, out := &in.Command, &out.Command\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.LifeCycleScript != nil {\n\t\tin, out := &in.LifeCycleScript, &out.LifeCycleScript\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *RuntimeRef) DeepCopyInto(out *RuntimeRef) {\n\t*out = *in\n}", "func (in *Ibft2) DeepCopyInto(out *Ibft2) {\n\t*out = *in\n\treturn\n}", "func (in *TestResult) DeepCopyInto(out *TestResult) {\n\t*out = *in\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *Haproxy) DeepCopyInto(out *Haproxy) {\n\t*out = *in\n\treturn\n}", "func (in *SSH) DeepCopyInto(out *SSH) {\n\t*out = *in\n\treturn\n}", "func (in *Runtime) DeepCopyInto(out *Runtime) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (b *Base64) DeepCopyInto(out *Base64) {\n\t*out = *b\n}", "func (in *EventDependencyTransformer) DeepCopyInto(out *EventDependencyTransformer) {\n\t*out = *in\n\treturn\n}", "func (in *StageOutput) DeepCopyInto(out *StageOutput) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Dependent) DeepCopyInto(out *Dependent) {\n\t*out = *in\n\treturn\n}", "func (in *GitFileGeneratorItem) DeepCopyInto(out *GitFileGeneratorItem) {\n\t*out = *in\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *AnsibleStep) DeepCopyInto(out *AnsibleStep) {\n\t*out = *in\n\treturn\n}", "func (in *Forks) DeepCopyInto(out *Forks) {\n\t*out = *in\n\tif in.DAO != nil {\n\t\tin, out := &in.DAO, &out.DAO\n\t\t*out = new(uint)\n\t\t**out = **in\n\t}\n}", "func (in *ContainerPort) DeepCopyInto(out *ContainerPort) {\n\t*out = *in\n}", "func (in *General) DeepCopyInto(out *General) {\n\t*out = *in\n\treturn\n}", "func (in *IsoContainer) DeepCopyInto(out *IsoContainer) {\n\t*out = *in\n}", "func (in *Git) DeepCopyInto(out *Git) {\n\t*out = *in\n\treturn\n}", "func (in *ConfigFile) DeepCopyInto(out *ConfigFile) {\n\t*out = *in\n}", "func (in *BackupProgress) DeepCopyInto(out *BackupProgress) {\n\t*out = *in\n}", "func (in *DataDisk) DeepCopyInto(out *DataDisk) {\n\t*out = *in\n}", "func (in *PhaseStep) DeepCopyInto(out *PhaseStep) {\n\t*out = *in\n}", "func (u *MAC) DeepCopyInto(out *MAC) {\n\t*out = *u\n}", "func (in *Variable) DeepCopyInto(out *Variable) {\n\t*out = *in\n}", "func (in *RestoreProgress) DeepCopyInto(out *RestoreProgress) {\n\t*out = *in\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *NamespacedObjectReference) DeepCopyInto(out *NamespacedObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Path) DeepCopyInto(out *Path) {\n\t*out = *in\n\treturn\n}", "func (in *GitDirectoryGeneratorItem) DeepCopyInto(out *GitDirectoryGeneratorItem) {\n\t*out = *in\n}", "func (in *NamePath) DeepCopyInto(out *NamePath) {\n\t*out = *in\n\treturn\n}", "func (in *ConsoleCreateObj) DeepCopyInto(out *ConsoleCreateObj) {\n\t*out = *in\n}", "func (in *UsedPipelineRun) DeepCopyInto(out *UsedPipelineRun) {\n\t*out = *in\n}", "func (in *BuildTemplate) DeepCopyInto(out *BuildTemplate) {\n\t*out = *in\n\tif in.Cmd != nil {\n\t\tin, out := &in.Cmd, &out.Cmd\n\t\t*out = make([]BuildTemplateStep, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n}", "func (in *ObjectInfo) DeepCopyInto(out *ObjectInfo) {\n\t*out = *in\n\tout.GroupVersionKind = in.GroupVersionKind\n\treturn\n}", "func (in *Files) DeepCopyInto(out *Files) {\n\t*out = *in\n}", "func (in *Source) DeepCopyInto(out *Source) {\n\t*out = *in\n\tif in.Dependencies != nil {\n\t\tin, out := &in.Dependencies, &out.Dependencies\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MavenRepositories != nil {\n\t\tin, out := &in.MavenRepositories, &out.MavenRepositories\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\treturn\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *StackBuild) DeepCopyInto(out *StackBuild) {\n\t*out = *in\n\treturn\n}", "func (in *BuildTaskRef) DeepCopyInto(out *BuildTaskRef) {\n\t*out = *in\n\treturn\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *PathInfo) DeepCopyInto(out *PathInfo) {\n\t*out = *in\n}", "func (in *PoA) DeepCopyInto(out *PoA) {\n\t*out = *in\n}", "func (in *Section) DeepCopyInto(out *Section) {\n\t*out = *in\n\tif in.SecretRefs != nil {\n\t\tin, out := &in.SecretRefs, &out.SecretRefs\n\t\t*out = make([]SecretReference, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Files != nil {\n\t\tin, out := &in.Files, &out.Files\n\t\t*out = make([]FileMount, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n}", "func (in *DNSSelection) DeepCopyInto(out *DNSSelection) {\n\t*out = *in\n\tif in.Include != nil {\n\t\tin, out := &in.Include, &out.Include\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Exclude != nil {\n\t\tin, out := &in.Exclude, &out.Exclude\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ReleaseVersion) DeepCopyInto(out *ReleaseVersion) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Command) DeepCopyInto(out *Command) {\n\t*out = *in\n\tif in.Flags != nil {\n\t\tin, out := &in.Flags, &out.Flags\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Value != nil {\n\t\tin, out := &in.Value, &out.Value\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *PathRule) DeepCopyInto(out *PathRule) {\n\t*out = *in\n\treturn\n}", "func (in *DockerLifecycleData) DeepCopyInto(out *DockerLifecycleData) {\n\t*out = *in\n}", "func (in *RunScriptStepConfig) DeepCopyInto(out *RunScriptStepConfig) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Checksum) DeepCopyInto(out *Checksum) {\n\t*out = *in\n}", "func (in *DomainNameOutput) DeepCopyInto(out *DomainNameOutput) {\n\t*out = *in\n}", "func (in *InterfaceStruct) DeepCopyInto(out *InterfaceStruct) {\n\t*out = *in\n\tif in.val != nil {\n\t\tin, out := &in.val, &out.val\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Ref) DeepCopyInto(out *Ref) {\n\t*out = *in\n}", "func (in *MemorySpec) DeepCopyInto(out *MemorySpec) {\n\t*out = *in\n}", "func (in *BuildJenkinsInfo) DeepCopyInto(out *BuildJenkinsInfo) {\n\t*out = *in\n\treturn\n}", "func (in *VirtualDatabaseBuildObject) DeepCopyInto(out *VirtualDatabaseBuildObject) {\n\t*out = *in\n\tif in.Incremental != nil {\n\t\tin, out := &in.Incremental, &out.Incremental\n\t\t*out = new(bool)\n\t\t**out = **in\n\t}\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]v1.EnvVar, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\tout.Git = in.Git\n\tin.Source.DeepCopyInto(&out.Source)\n\tif in.Webhooks != nil {\n\t\tin, out := &in.Webhooks, &out.Webhooks\n\t\t*out = make([]WebhookSecret, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *MaintenanceInfo) DeepCopyInto(out *MaintenanceInfo) {\n\t*out = *in\n\treturn\n}", "func (in *KopsNode) DeepCopyInto(out *KopsNode) {\n\t*out = *in\n\treturn\n}", "func (in *FalconAPI) DeepCopyInto(out *FalconAPI) {\n\t*out = *in\n}", "func (in *EBS) DeepCopyInto(out *EBS) {\n\t*out = *in\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n\treturn\n}", "func (in *Empty) DeepCopyInto(out *Empty) {\n\t*out = *in\n\tout.XXX_NoUnkeyedLiteral = in.XXX_NoUnkeyedLiteral\n\tif in.XXX_unrecognized != nil {\n\t\tin, out := &in.XXX_unrecognized, &out.XXX_unrecognized\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ComponentDistGit) DeepCopyInto(out *ComponentDistGit) {\n\t*out = *in\n\treturn\n}", "func (in *Memory) DeepCopyInto(out *Memory) {\n\t*out = *in\n\tout.Required = in.Required.DeepCopy()\n}", "func (in *Persistence) DeepCopyInto(out *Persistence) {\n\t*out = *in\n\tout.Size = in.Size.DeepCopy()\n\treturn\n}", "func (in *ManagedDisk) DeepCopyInto(out *ManagedDisk) {\n\t*out = *in\n}", "func (e *Email) DeepCopyInto(out *Email) {\n\t*out = *e\n}", "func (in *ImageInfo) DeepCopyInto(out *ImageInfo) {\n\t*out = *in\n}", "func (in *ShootRef) DeepCopyInto(out *ShootRef) {\n\t*out = *in\n}", "func (in *N3000Fpga) DeepCopyInto(out *N3000Fpga) {\n\t*out = *in\n}", "func (in *NetflowType) DeepCopyInto(out *NetflowType) {\n\t*out = *in\n\treturn\n}", "func (in *BuiltInAdapter) DeepCopyInto(out *BuiltInAdapter) {\n\t*out = *in\n}", "func (in *Node) DeepCopyInto(out *Node) {\n\t*out = *in\n\tif in.FailStatus != nil {\n\t\tin, out := &in.FailStatus, &out.FailStatus\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MigratingSlots != nil {\n\t\tin, out := &in.MigratingSlots, &out.MigratingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.ImportingSlots != nil {\n\t\tin, out := &in.ImportingSlots, &out.ImportingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n}", "func (in *CPUSpec) DeepCopyInto(out *CPUSpec) {\n\t*out = *in\n}", "func (in *LoopState) DeepCopyInto(out *LoopState) {\n\t*out = *in\n}" ]
[ "0.8215289", "0.81280124", "0.81039286", "0.80862963", "0.8083811", "0.80673146", "0.8064545", "0.8026454", "0.8012046", "0.7996313", "0.799204", "0.79887754", "0.7987097", "0.7986994", "0.7986994", "0.79854053", "0.7975989", "0.7972486", "0.79695636", "0.79695636", "0.79695636", "0.7967528", "0.79624444", "0.7961954", "0.7945754", "0.7945754", "0.7944541", "0.79428566", "0.7942668", "0.7942668", "0.7940451", "0.793851", "0.7936731", "0.79294837", "0.79252166", "0.7915377", "0.7911627", "0.7911138", "0.7909384", "0.790913", "0.7908773", "0.7905649", "0.79050326", "0.7904594", "0.7904594", "0.7904235", "0.79036915", "0.79020816", "0.78988886", "0.78977424", "0.7891376", "0.7891024", "0.7889831", "0.78890276", "0.7887135", "0.788637", "0.7885264", "0.7885264", "0.7884786", "0.7880785", "0.78745943", "0.78745943", "0.78745407", "0.78734446", "0.78724426", "0.78713626", "0.78713554", "0.78652424", "0.7863321", "0.7863321", "0.7863321", "0.7863293", "0.7862628", "0.7860664", "0.7858556", "0.785785", "0.78571486", "0.7851332", "0.78453225", "0.78448987", "0.78415996", "0.7837483", "0.7837037", "0.7836443", "0.78351796", "0.78329664", "0.7831094", "0.7829445", "0.7826582", "0.7824499", "0.78242797", "0.78227437", "0.78192484", "0.7818843", "0.78128535", "0.7812535", "0.78111476", "0.78111106", "0.781107", "0.78093034", "0.7808775" ]
0.0
-1
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DailyRule.
func (in *DailyRule) DeepCopy() *DailyRule { if in == nil { return nil } out := new(DailyRule) in.DeepCopyInto(out) return out }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in *Rule) DeepCopy() *Rule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule) DeepCopy() *Rule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule) DeepCopy() *Rule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule) DeepCopy() *Rule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule) DeepCopy() *Rule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *TriggerRule) DeepCopy() *TriggerRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TriggerRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ClbStatefulSetRule) DeepCopy() *ClbStatefulSetRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ClbStatefulSetRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DailyMaintenanceWindow) DeepCopy() *DailyMaintenanceWindow {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DailyMaintenanceWindow)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScaleRule) DeepCopy() *ScaleRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PathRule) DeepCopy() *PathRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PathRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (rule *Rule) Copy() *Rule {\n\tcpy := *rule\n\tcpy.Key = rule.Key.Copy()\n\tcpy.Value = rule.Value.Copy()\n\tcpy.Body = rule.Body.Copy()\n\treturn &cpy\n}", "func (in *DnsRule) DeepCopy() *DnsRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DnsRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o ConfigurationBackupRetentionPolicyOutput) DailySchedule() ConfigurationBackupRetentionPolicyDailySchedulePtrOutput {\n\treturn o.ApplyT(func(v ConfigurationBackupRetentionPolicy) *ConfigurationBackupRetentionPolicyDailySchedule {\n\t\treturn v.DailySchedule\n\t}).(ConfigurationBackupRetentionPolicyDailySchedulePtrOutput)\n}", "func (in *MatchRule) DeepCopy() *MatchRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MatchRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Weekly) DeepCopy() *Weekly {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Weekly)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o ConfigurationBackupRetentionPolicyPtrOutput) DailySchedule() ConfigurationBackupRetentionPolicyDailySchedulePtrOutput {\n\treturn o.ApplyT(func(v *ConfigurationBackupRetentionPolicy) *ConfigurationBackupRetentionPolicyDailySchedule {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.DailySchedule\n\t}).(ConfigurationBackupRetentionPolicyDailySchedulePtrOutput)\n}", "func (in *DailyRule) DeepCopyInto(out *DailyRule) {\n\t*out = *in\n}", "func (r *IPRule) Copy() IPRule {\n\treturn IPRule{\n\t\tNo: r.No,\n\t\tSourceIP: r.SourceIP,\n\t\tRouteTableName: r.RouteTableName,\n\t\tFwMark: r.FwMark,\n\t}\n}", "func (in *HostRule) DeepCopy() *HostRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HostRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule_From) DeepCopy() *Rule_From {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule_From)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RuleObservation) DeepCopy() *RuleObservation {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RuleObservation)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *EgressRule) DeepCopy() *EgressRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(EgressRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule) DeepCopyInterface() interface{} {\n\treturn in.DeepCopy()\n}", "func NewRule() *Rule {\n\tthis := Rule{}\n\treturn &this\n}", "func (in *ClbRule) DeepCopy() *ClbRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ClbRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AlertingRule) DeepCopy() *AlertingRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AlertingRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o *AutomodRuleDatum) Rule(mods ...qm.QueryMod) automodRuleQuery {\n\tqueryMods := []qm.QueryMod{\n\t\tqm.Where(\"\\\"id\\\" = ?\", o.RuleID),\n\t}\n\n\tqueryMods = append(queryMods, mods...)\n\n\treturn AutomodRules(queryMods...)\n}", "func (in *Redpanda) DeepCopy() *Redpanda {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Redpanda)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RuleSpec) DeepCopy() *RuleSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RuleSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RuleSpec) DeepCopy() *RuleSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RuleSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DryRun) DeepCopy() *DryRun {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DryRun)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WeeklyList) DeepCopy() *WeeklyList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WeeklyList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ClbHttpRule) DeepCopy() *ClbHttpRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ClbHttpRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule_To) DeepCopy() *Rule_To {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule_To)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RuleExecution) DeepCopy() *RuleExecution {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RuleExecution)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *HTTPRule) DeepCopy() *HTTPRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HTTPRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ClbStatefulSetHttpRule) DeepCopy() *ClbStatefulSetHttpRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ClbStatefulSetHttpRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *IngressRule) DeepCopy() *IngressRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(IngressRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DestinationRule) DeepCopy() *DestinationRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DestinationRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule_From) DeepCopyInterface() interface{} {\n\treturn in.DeepCopy()\n}", "func (o ResourcePolicyWeeklyCycleDayOfWeekOutput) Day() ResourcePolicyWeeklyCycleDayOfWeekDayPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyWeeklyCycleDayOfWeek) *ResourcePolicyWeeklyCycleDayOfWeekDay { return v.Day }).(ResourcePolicyWeeklyCycleDayOfWeekDayPtrOutput)\n}", "func (in *PagerdutyRuleset) DeepCopy() *PagerdutyRuleset {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PagerdutyRuleset)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Crd) DeepCopy() *Crd {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Crd)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScaleRule) DeepCopyInto(out *ScaleRule) {\n\t*out = *in\n\tout.ScaleSpec = in.ScaleSpec\n\tif in.Daily != nil {\n\t\tin, out := &in.Daily, &out.Daily\n\t\t*out = new(DailyRule)\n\t\t**out = **in\n\t}\n}", "func (in *RuleParameters) DeepCopy() *RuleParameters {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RuleParameters)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RuleList) DeepCopy() *RuleList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RuleList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *HealthCheck) DeepCopy() *HealthCheck {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HealthCheck)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *HealthCheck) DeepCopy() *HealthCheck {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HealthCheck)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *HealthCheck) DeepCopy() *HealthCheck {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HealthCheck)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *KubeEventsRule) DeepCopy() *KubeEventsRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(KubeEventsRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in SortableRuleSlice) DeepCopy() SortableRuleSlice {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SortableRuleSlice)\n\tin.DeepCopyInto(out)\n\treturn *out\n}", "func (in *RollingUpdateStatefulSetStrategy) DeepCopy() *RollingUpdateStatefulSetStrategy {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RollingUpdateStatefulSetStrategy)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Budget) DeepCopy() *Budget {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Budget)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AppAutoscalingRule) DeepCopy() *AppAutoscalingRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AppAutoscalingRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DnsRuleList) DeepCopy() *DnsRuleList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DnsRuleList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *TimeWindowDays) DeepCopy() *TimeWindowDays {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TimeWindowDays)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DebugRuleConfiguration) DeepCopy() *DebugRuleConfiguration {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DebugRuleConfiguration)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RollingUpdateStrategy) DeepCopy() *RollingUpdateStrategy {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RollingUpdateStrategy)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *FlexibleServersFirewallRule) DeepCopy() *FlexibleServersFirewallRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(FlexibleServersFirewallRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *CurReportDefinition) DeepCopy() *CurReportDefinition {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CurReportDefinition)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SD) DeepCopy() *SD {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SD)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RedpandaMemory) DeepCopy() *RedpandaMemory {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RedpandaMemory)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func DeepCopy_v1_ImageExecutionPolicyRule(in interface{}, out interface{}, c *conversion.Cloner) error {\n\t{\n\t\tin := in.(*ImageExecutionPolicyRule)\n\t\tout := out.(*ImageExecutionPolicyRule)\n\t\t*out = *in\n\t\tif err := DeepCopy_v1_ImageCondition(&in.ImageCondition, &out.ImageCondition, c); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n}", "func (in *CronTrigger) DeepCopy() *CronTrigger {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CronTrigger)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WeeklyStatus) DeepCopy() *WeeklyStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WeeklyStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DnsForwardingRuleSetsForwardingRule) DeepCopy() *DnsForwardingRuleSetsForwardingRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DnsForwardingRuleSetsForwardingRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RegistryCronJob) DeepCopy() *RegistryCronJob {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RegistryCronJob)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *Job) Days() *Job {\n\tif c.delayUnit == delayNone {\n\t\tc.unit = days\n\t} else {\n\t\tc.delayUnit = delayDays\n\t}\n\treturn c\n}", "func (d *AppsV1DeploymentRule) createRule(deployment *appsv1.Deployment, ydr *YamlDerivedResource) *rule {\n\tr := &rule{\n\t\tID: d.ID,\n\t\tPrereqs: d.Prereqs,\n\t\tCondition: func() bool {\n\t\t\tif d.Condition == nil {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn d.Condition(deployment)\n\t\t},\n\t\tMessage: d.Message,\n\t\tLevel: d.Level,\n\t\tResources: []*YamlDerivedResource{ydr},\n\t\tFix: func() bool {\n\t\t\tif d.Fix == nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn d.Fix(deployment)\n\t\t},\n\t\tFixDescription: func() string {\n\t\t\tif d.FixDescription == nil {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn d.FixDescription(deployment)\n\t\t},\n\t}\n\treturn r\n}", "func (in *PasswordPolicyRule) DeepCopy() *PasswordPolicyRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PasswordPolicyRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Schedule) DeepCopy() *Schedule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Schedule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (od *OutputDefinition) DeepCopy() *OutputDefinition {\n\tvar o2 OutputDefinition\n\to2 = *od\n\to2.ApplyTo = make([]string, len(od.ApplyTo))\n\tcopy(o2.ApplyTo, od.ApplyTo)\n\treturn &o2\n}", "func (in *DnsRuleSpec) DeepCopy() *DnsRuleSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DnsRuleSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Validation) DeepCopy() *Validation {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Validation)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RuleGroup) DeepCopy() *RuleGroup {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RuleGroup)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (h *HamtFunctional) DeepCopy() Hamt {\n\tvar nh = new(HamtFunctional)\n\tnh.root = *h.root.deepCopy().(*fixedTable)\n\tnh.nentries = h.nentries\n\tnh.nograde = h.nograde\n\tnh.startFixed = h.startFixed\n\treturn nh\n}", "func (in *IstioDestinationRule) DeepCopy() *IstioDestinationRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(IstioDestinationRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *CompanyValuation) DailyDiscountedCashFlow(req objects.RequestDailyDiscountedCashFlow) (vList []objects.DailyDiscountedCashFlow, err error) {\n\tdata, err := c.Client.Get(\n\t\tfmt.Sprintf(urlAPICompanyValuationHistoryDailyDiscountedCashFlow, req.Symbol),\n\t\tmap[string]string{\"limit\": fmt.Sprint(req.Limit)},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(data.Body(), &vList)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vList, nil\n}", "func (in *AlertingRuleList) DeepCopy() *AlertingRuleList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AlertingRuleList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (obj *Rule) Populate(RuleID string, data RulesDataRow) {\n\tobj.RuleID = RuleID\n\tobj.Protocol = data.Protocol\n\tobj.DstIP = data.DstIP\n\tobj.SrcIP = data.SrcIP\n\tobj.DstMAC = data.DstMAC\n\tobj.FlowID = data.FlowID\n\tobj.Interface = data.Interface\n\tobj.NodeIP = data.NodeIP\n\tobj.Action = data.Action\n\tobj.NodeName = data.NodeName\n\tobj.IsActive = data.IsActive\n}", "func NewRule(name, targetLocation, pattern, linkPattern, deeplinkPatterns, headers string, totalPages int) (*Rule, error) {\n\tif utility.IsNil(name, pattern, targetLocation) {\n\t\treturn nil, errors.New(utility.Enums().ErrorMessages.LackOfInfo)\n\t}\n\tid, _ := uuid.NewRandom()\n\treturn &Rule{\n\t\tID: id.String(),\n\t\tName: name,\n\t\tStatus: utility.Enums().Status.Active,\n\t\tPattern: pattern,\n\t\tPriority: 0,\n\t\tLinkPattern: linkPattern,\n\t\tDeepLinkPatterns: deeplinkPatterns,\n\t\tTotalPages: totalPages,\n\t\tHeaders: headers,\n\t\tTargetLocation: targetLocation,\n\t}, nil\n}", "func (d *Definition) Rules() Rules {\n\tout := Rules{}\n\tfor state, rules := range d.rules {\n\t\tfor _, rule := range rules {\n\t\t\tout[state] = append(out[state], rule.Rule)\n\t\t}\n\t}\n\treturn out\n}", "func (in *Rule_To) DeepCopyInterface() interface{} {\n\treturn in.DeepCopy()\n}", "func NewRuleWithDefaults() *Rule {\n\tthis := Rule{}\n\treturn &this\n}", "func (o *AutomodRuleDatum) Reload(ctx context.Context, exec boil.ContextExecutor) error {\n\tret, err := FindAutomodRuleDatum(ctx, exec, o.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*o = *ret\n\treturn nil\n}", "func (in *Rule) DeepCopyInto(out *Rule) {\n\t*out = *in\n\treturn\n}", "func NewDeeplinkRule() *DeeplinkRule {\n\tthis := DeeplinkRule{}\n\treturn &this\n}", "func (in *PagerdutyRulesetList) DeepCopy() *PagerdutyRulesetList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PagerdutyRulesetList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DnsForwardingRuleset) DeepCopy() *DnsForwardingRuleset {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DnsForwardingRuleset)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PolicyRuleBuilder) DeepCopy() *PolicyRuleBuilder {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PolicyRuleBuilder)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WeeklySpec) DeepCopy() *WeeklySpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WeeklySpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RuleStatus) DeepCopy() *RuleStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RuleStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RedpandaImage) DeepCopy() *RedpandaImage {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RedpandaImage)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WeightedDst) DeepCopy() *WeightedDst {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WeightedDst)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Weekly) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *PodDisruptionBudget) DeepCopy() *PodDisruptionBudget {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PodDisruptionBudget)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DaemonsetRef) DeepCopy() *DaemonsetRef {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DaemonsetRef)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RecurringWindow) DeepCopy() *RecurringWindow {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RecurringWindow)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DOLoadBalancerHealthCheck) DeepCopy() *DOLoadBalancerHealthCheck {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DOLoadBalancerHealthCheck)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RollingUpgradeStrategy) DeepCopy() *RollingUpgradeStrategy {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RollingUpgradeStrategy)\n\tin.DeepCopyInto(out)\n\treturn out\n}" ]
[ "0.5939093", "0.5939093", "0.5939093", "0.5939093", "0.5939093", "0.5546245", "0.5436166", "0.5406394", "0.539924", "0.5398177", "0.5362258", "0.53486407", "0.5299951", "0.52968395", "0.52954674", "0.5180423", "0.51571137", "0.4970968", "0.49688", "0.4924555", "0.49125367", "0.49073246", "0.48964024", "0.48674887", "0.48608187", "0.482667", "0.4818544", "0.4752206", "0.47429502", "0.47429502", "0.474053", "0.4699441", "0.46674117", "0.4660497", "0.46580967", "0.46422765", "0.4638935", "0.46091834", "0.4604648", "0.46032435", "0.45914337", "0.45909035", "0.45880836", "0.45782155", "0.456003", "0.4542727", "0.4483218", "0.4483218", "0.4483218", "0.44785383", "0.4473906", "0.4468675", "0.44493285", "0.44387722", "0.44313523", "0.44201803", "0.438651", "0.43810076", "0.43501946", "0.4348311", "0.43457", "0.43414724", "0.43390533", "0.43300748", "0.4329148", "0.4327235", "0.43247274", "0.4322266", "0.4315357", "0.43131918", "0.43009773", "0.42856896", "0.4275655", "0.42724842", "0.42529166", "0.4236151", "0.42214087", "0.42079663", "0.42001987", "0.41947564", "0.41911602", "0.4183859", "0.4181327", "0.41785598", "0.41753352", "0.41720736", "0.4170709", "0.41637245", "0.41625792", "0.41569743", "0.4144099", "0.41402155", "0.41372156", "0.41294217", "0.41223407", "0.41176912", "0.40988111", "0.4087821", "0.40864193", "0.4082213" ]
0.8802274
0
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be nonnil.
func (in *ScaleRule) DeepCopyInto(out *ScaleRule) { *out = *in out.ScaleSpec = in.ScaleSpec if in.Daily != nil { in, out := &in.Daily, &out.Daily *out = new(DailyRule) **out = **in } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RunInfo) DeepCopyInto(out *RunInfo) {\n\t*out = *r\n}", "func (in *Base) DeepCopyInto(out *Base) {\n\t*out = *in\n\treturn\n}", "func (in *ForkObject) DeepCopyInto(out *ForkObject) {\n\t*out = *in\n}", "func (in *TargetObjectInfo) DeepCopyInto(out *TargetObjectInfo) {\n\t*out = *in\n}", "func (in *DebugObjectInfo) DeepCopyInto(out *DebugObjectInfo) {\n\t*out = *in\n}", "func (in *Input) DeepCopyInto(out *Input) {\n\t*out = *in\n}", "func (u *SSN) DeepCopyInto(out *SSN) {\n\t*out = *u\n}", "func (in *ExistPvc) DeepCopyInto(out *ExistPvc) {\n\t*out = *in\n}", "func (in *DockerStep) DeepCopyInto(out *DockerStep) {\n\t*out = *in\n\tif in.Inline != nil {\n\t\tin, out := &in.Inline, &out.Inline\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tout.Auth = in.Auth\n\treturn\n}", "func (in *Container) DeepCopyInto(out *Container) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.Command != nil {\n\t\tin, out := &in.Command, &out.Command\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.LifeCycleScript != nil {\n\t\tin, out := &in.LifeCycleScript, &out.LifeCycleScript\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *RuntimeRef) DeepCopyInto(out *RuntimeRef) {\n\t*out = *in\n}", "func (in *Ibft2) DeepCopyInto(out *Ibft2) {\n\t*out = *in\n\treturn\n}", "func (in *TestResult) DeepCopyInto(out *TestResult) {\n\t*out = *in\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *Haproxy) DeepCopyInto(out *Haproxy) {\n\t*out = *in\n\treturn\n}", "func (in *SSH) DeepCopyInto(out *SSH) {\n\t*out = *in\n\treturn\n}", "func (in *Runtime) DeepCopyInto(out *Runtime) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (b *Base64) DeepCopyInto(out *Base64) {\n\t*out = *b\n}", "func (in *EventDependencyTransformer) DeepCopyInto(out *EventDependencyTransformer) {\n\t*out = *in\n\treturn\n}", "func (in *StageOutput) DeepCopyInto(out *StageOutput) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Dependent) DeepCopyInto(out *Dependent) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *GitFileGeneratorItem) DeepCopyInto(out *GitFileGeneratorItem) {\n\t*out = *in\n}", "func (in *AnsibleStep) DeepCopyInto(out *AnsibleStep) {\n\t*out = *in\n\treturn\n}", "func (in *Forks) DeepCopyInto(out *Forks) {\n\t*out = *in\n\tif in.DAO != nil {\n\t\tin, out := &in.DAO, &out.DAO\n\t\t*out = new(uint)\n\t\t**out = **in\n\t}\n}", "func (in *ContainerPort) DeepCopyInto(out *ContainerPort) {\n\t*out = *in\n}", "func (in *General) DeepCopyInto(out *General) {\n\t*out = *in\n\treturn\n}", "func (in *IsoContainer) DeepCopyInto(out *IsoContainer) {\n\t*out = *in\n}", "func (in *Git) DeepCopyInto(out *Git) {\n\t*out = *in\n\treturn\n}", "func (in *BackupProgress) DeepCopyInto(out *BackupProgress) {\n\t*out = *in\n}", "func (in *ConfigFile) DeepCopyInto(out *ConfigFile) {\n\t*out = *in\n}", "func (in *DataDisk) DeepCopyInto(out *DataDisk) {\n\t*out = *in\n}", "func (in *PhaseStep) DeepCopyInto(out *PhaseStep) {\n\t*out = *in\n}", "func (u *MAC) DeepCopyInto(out *MAC) {\n\t*out = *u\n}", "func (in *Variable) DeepCopyInto(out *Variable) {\n\t*out = *in\n}", "func (in *RestoreProgress) DeepCopyInto(out *RestoreProgress) {\n\t*out = *in\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *NamespacedObjectReference) DeepCopyInto(out *NamespacedObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Path) DeepCopyInto(out *Path) {\n\t*out = *in\n\treturn\n}", "func (in *GitDirectoryGeneratorItem) DeepCopyInto(out *GitDirectoryGeneratorItem) {\n\t*out = *in\n}", "func (in *NamePath) DeepCopyInto(out *NamePath) {\n\t*out = *in\n\treturn\n}", "func (in *ConsoleCreateObj) DeepCopyInto(out *ConsoleCreateObj) {\n\t*out = *in\n}", "func (in *UsedPipelineRun) DeepCopyInto(out *UsedPipelineRun) {\n\t*out = *in\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n}", "func (in *BuildTemplate) DeepCopyInto(out *BuildTemplate) {\n\t*out = *in\n\tif in.Cmd != nil {\n\t\tin, out := &in.Cmd, &out.Cmd\n\t\t*out = make([]BuildTemplateStep, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\treturn\n}", "func (in *ObjectInfo) DeepCopyInto(out *ObjectInfo) {\n\t*out = *in\n\tout.GroupVersionKind = in.GroupVersionKind\n\treturn\n}", "func (in *Files) DeepCopyInto(out *Files) {\n\t*out = *in\n}", "func (in *Source) DeepCopyInto(out *Source) {\n\t*out = *in\n\tif in.Dependencies != nil {\n\t\tin, out := &in.Dependencies, &out.Dependencies\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MavenRepositories != nil {\n\t\tin, out := &in.MavenRepositories, &out.MavenRepositories\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\treturn\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *StackBuild) DeepCopyInto(out *StackBuild) {\n\t*out = *in\n\treturn\n}", "func (in *BuildTaskRef) DeepCopyInto(out *BuildTaskRef) {\n\t*out = *in\n\treturn\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *PathInfo) DeepCopyInto(out *PathInfo) {\n\t*out = *in\n}", "func (in *PoA) DeepCopyInto(out *PoA) {\n\t*out = *in\n}", "func (in *Section) DeepCopyInto(out *Section) {\n\t*out = *in\n\tif in.SecretRefs != nil {\n\t\tin, out := &in.SecretRefs, &out.SecretRefs\n\t\t*out = make([]SecretReference, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Files != nil {\n\t\tin, out := &in.Files, &out.Files\n\t\t*out = make([]FileMount, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *DNSSelection) DeepCopyInto(out *DNSSelection) {\n\t*out = *in\n\tif in.Include != nil {\n\t\tin, out := &in.Include, &out.Include\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Exclude != nil {\n\t\tin, out := &in.Exclude, &out.Exclude\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n}", "func (in *ReleaseVersion) DeepCopyInto(out *ReleaseVersion) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *PathRule) DeepCopyInto(out *PathRule) {\n\t*out = *in\n\treturn\n}", "func (in *Command) DeepCopyInto(out *Command) {\n\t*out = *in\n\tif in.Flags != nil {\n\t\tin, out := &in.Flags, &out.Flags\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Value != nil {\n\t\tin, out := &in.Value, &out.Value\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *DockerLifecycleData) DeepCopyInto(out *DockerLifecycleData) {\n\t*out = *in\n}", "func (in *RunScriptStepConfig) DeepCopyInto(out *RunScriptStepConfig) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Checksum) DeepCopyInto(out *Checksum) {\n\t*out = *in\n}", "func (in *DomainNameOutput) DeepCopyInto(out *DomainNameOutput) {\n\t*out = *in\n}", "func (in *InterfaceStruct) DeepCopyInto(out *InterfaceStruct) {\n\t*out = *in\n\tif in.val != nil {\n\t\tin, out := &in.val, &out.val\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Ref) DeepCopyInto(out *Ref) {\n\t*out = *in\n}", "func (in *MemorySpec) DeepCopyInto(out *MemorySpec) {\n\t*out = *in\n}", "func (in *BuildJenkinsInfo) DeepCopyInto(out *BuildJenkinsInfo) {\n\t*out = *in\n\treturn\n}", "func (in *KopsNode) DeepCopyInto(out *KopsNode) {\n\t*out = *in\n\treturn\n}", "func (in *MaintenanceInfo) DeepCopyInto(out *MaintenanceInfo) {\n\t*out = *in\n\treturn\n}", "func (in *VirtualDatabaseBuildObject) DeepCopyInto(out *VirtualDatabaseBuildObject) {\n\t*out = *in\n\tif in.Incremental != nil {\n\t\tin, out := &in.Incremental, &out.Incremental\n\t\t*out = new(bool)\n\t\t**out = **in\n\t}\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]v1.EnvVar, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\tout.Git = in.Git\n\tin.Source.DeepCopyInto(&out.Source)\n\tif in.Webhooks != nil {\n\t\tin, out := &in.Webhooks, &out.Webhooks\n\t\t*out = make([]WebhookSecret, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *FalconAPI) DeepCopyInto(out *FalconAPI) {\n\t*out = *in\n}", "func (in *EBS) DeepCopyInto(out *EBS) {\n\t*out = *in\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n\treturn\n}", "func (in *Empty) DeepCopyInto(out *Empty) {\n\t*out = *in\n\tout.XXX_NoUnkeyedLiteral = in.XXX_NoUnkeyedLiteral\n\tif in.XXX_unrecognized != nil {\n\t\tin, out := &in.XXX_unrecognized, &out.XXX_unrecognized\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ComponentDistGit) DeepCopyInto(out *ComponentDistGit) {\n\t*out = *in\n\treturn\n}", "func (in *Persistence) DeepCopyInto(out *Persistence) {\n\t*out = *in\n\tout.Size = in.Size.DeepCopy()\n\treturn\n}", "func (in *Memory) DeepCopyInto(out *Memory) {\n\t*out = *in\n\tout.Required = in.Required.DeepCopy()\n}", "func (in *ManagedDisk) DeepCopyInto(out *ManagedDisk) {\n\t*out = *in\n}", "func (e *Email) DeepCopyInto(out *Email) {\n\t*out = *e\n}", "func (in *ImageInfo) DeepCopyInto(out *ImageInfo) {\n\t*out = *in\n}", "func (in *ShootRef) DeepCopyInto(out *ShootRef) {\n\t*out = *in\n}", "func (in *NetflowType) DeepCopyInto(out *NetflowType) {\n\t*out = *in\n\treturn\n}", "func (in *N3000Fpga) DeepCopyInto(out *N3000Fpga) {\n\t*out = *in\n}", "func (in *BuiltInAdapter) DeepCopyInto(out *BuiltInAdapter) {\n\t*out = *in\n}", "func (in *Node) DeepCopyInto(out *Node) {\n\t*out = *in\n\tif in.FailStatus != nil {\n\t\tin, out := &in.FailStatus, &out.FailStatus\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MigratingSlots != nil {\n\t\tin, out := &in.MigratingSlots, &out.MigratingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.ImportingSlots != nil {\n\t\tin, out := &in.ImportingSlots, &out.ImportingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n}", "func (in *CPUSpec) DeepCopyInto(out *CPUSpec) {\n\t*out = *in\n}", "func (in *LoopState) DeepCopyInto(out *LoopState) {\n\t*out = *in\n}" ]
[ "0.8215148", "0.8128148", "0.8104491", "0.8086232", "0.8083645", "0.80681837", "0.8064712", "0.80272263", "0.80118906", "0.79957503", "0.79923207", "0.79894227", "0.79878217", "0.7987706", "0.7987706", "0.79856145", "0.7976737", "0.797243", "0.79705614", "0.79705614", "0.79705614", "0.7967998", "0.7963185", "0.7962239", "0.7946799", "0.7946799", "0.79451364", "0.79437023", "0.79437023", "0.79423654", "0.79407156", "0.79375064", "0.79369694", "0.7929554", "0.7925828", "0.79153883", "0.79121333", "0.7912032", "0.7910158", "0.79093456", "0.79087806", "0.7906067", "0.7906014", "0.7905399", "0.7905399", "0.79051214", "0.790477", "0.79011744", "0.7899582", "0.7897098", "0.7891637", "0.78907233", "0.78905463", "0.78897065", "0.78873104", "0.7886752", "0.7885397", "0.7885397", "0.7885259", "0.78815824", "0.787546", "0.787546", "0.7875398", "0.78739077", "0.78724843", "0.78717405", "0.78714716", "0.7865966", "0.7864238", "0.7864238", "0.7864238", "0.7863405", "0.7862614", "0.7860687", "0.78587526", "0.7858436", "0.78570235", "0.78514445", "0.7846122", "0.78443074", "0.78416294", "0.7837446", "0.78372633", "0.78368735", "0.78350383", "0.7833183", "0.78313106", "0.7830074", "0.78268486", "0.78255475", "0.7825175", "0.78235906", "0.78204864", "0.78198004", "0.7812933", "0.7811604", "0.78113776", "0.7810981", "0.78103817", "0.7809776", "0.78089356" ]
0.0
-1
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ScaleRule.
func (in *ScaleRule) DeepCopy() *ScaleRule { if in == nil { return nil } out := new(ScaleRule) in.DeepCopyInto(out) return out }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in *Scale) DeepCopy() *Scale {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Scale)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScaleTarget) DeepCopy() *ScaleTarget {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleTarget)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *LinehaulCostComputation) Scale(factor float64) {\n\tc.BaseLinehaul = c.BaseLinehaul.MultiplyFloat64(factor)\n\tc.OriginLinehaulFactor = c.OriginLinehaulFactor.MultiplyFloat64(factor)\n\tc.DestinationLinehaulFactor = c.DestinationLinehaulFactor.MultiplyFloat64(factor)\n\tc.ShorthaulCharge = c.ShorthaulCharge.MultiplyFloat64(factor)\n\tc.LinehaulChargeTotal = c.LinehaulChargeTotal.MultiplyFloat64(factor)\n}", "func (in *ScaleList) DeepCopy() *ScaleList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (p Point) Scale(s Length) Point {\n\treturn Point{p.X * s, p.Y * s}\n}", "func (in *ScaleSpec) DeepCopy() *ScaleSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule) DeepCopy() *Rule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule) DeepCopy() *Rule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule) DeepCopy() *Rule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule) DeepCopy() *Rule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Rule) DeepCopy() *Rule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (r Rectangle) Scale(factor float64) Rectangle {\n\treturn Rectangle{\n\t\tMin: r.Min.Mul(factor),\n\t\tMax: r.Max.Mul(factor),\n\t}\n}", "func (p Period) Scale(factor float64) *Period {\n\tresult, _ := p.ScaleWithOverflowCheck(factor)\n\treturn result\n}", "func (p Point) Scale(s float64) Point {\n\treturn NewPoint(p.X*s, p.Y*s)\n}", "func (self *T) Scale(f float64) *T {\n\tself[0] *= f\n\tself[1] *= f\n\treturn self\n}", "func (self *T) Scale(f float32) *T {\n\tself[0][0] *= f\n\tself[1][1] *= f\n\treturn self\n}", "func (t *Transform) Scale(sx, sy float64) {\n\tout := fmt.Sprintf(\"scale(%g,%g)\", sx, sy)\n\n\tt.transforms = append(t.transforms, out)\n}", "func (in *ElasticsearchDataSetScaling) DeepCopy() *ElasticsearchDataSetScaling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ElasticsearchDataSetScaling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (tfs *tiflashScaler) Scale(tc *v1alpha1.TidbCluster, oldSet *apps.StatefulSet, newSet *apps.StatefulSet) error {\n\tscaling, _, _, _ := scaleOne(oldSet, newSet)\n\tif scaling > 0 {\n\t\treturn tfs.ScaleOut(tc, oldSet, newSet)\n\t} else if scaling < 0 {\n\t\treturn tfs.ScaleIn(tc, oldSet, newSet)\n\t}\n\t// we only sync auto scaler annotations when we are finishing syncing scaling\n\treturn tfs.SyncAutoScalerAnn(tc, oldSet)\n}", "func (p Point) Scale(f float64) Point {\n\treturn Point{p[0] * f, p[1] * f, p[2] * f}\n}", "func Scale(value float64) *SimpleElement { return newSEFloat(\"scale\", value) }", "func (wv *Spectrum) Scale(s float32) {\n\twv.C[0] *= s\n\twv.C[1] *= s\n\twv.C[2] *= s\n\twv.C[3] *= s\n}", "func (this *RectangleShape) Scale(factor Vector2f) {\n\tC.sfRectangleShape_scale(this.cptr, factor.toC())\n}", "func (in *SetCanaryScale) DeepCopy() *SetCanaryScale {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SetCanaryScale)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScaleStatus) DeepCopy() *ScaleStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (s *TaskSet) SetScale(v *Scale) *TaskSet {\n\ts.Scale = v\n\treturn s\n}", "func (this *Transformable) Scale(factor Vector2f) {\n\tC.sfTransformable_scale(this.cptr, factor.toC())\n}", "func (m Matrix) Scale(scale vec32.Vector) Matrix {\n\treturn Mul(m, Matrix{\n\t\t{scale[0], 0, 0, 0},\n\t\t{0, scale[1], 0, 0},\n\t\t{0, 0, scale[2], 0},\n\t\t{0, 0, 0, 1},\n\t})\n}", "func (s *UpdateTaskSetInput) SetScale(v *Scale) *UpdateTaskSetInput {\n\ts.Scale = v\n\treturn s\n}", "func (p *Point) Scale(v float64) {\n\tp.x *= v\n\tp.y *= v\n}", "func (o HorizontalPodAutoscalerBehaviorPatchOutput) ScaleDown() HPAScalingRulesPatchPtrOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerBehaviorPatch) *HPAScalingRulesPatch { return v.ScaleDown }).(HPAScalingRulesPatchPtrOutput)\n}", "func (s *CreateTaskSetInput) SetScale(v *Scale) *CreateTaskSetInput {\n\ts.Scale = v\n\treturn s\n}", "func (in *Rule_To) DeepCopy() *Rule_To {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Rule_To)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o HorizontalPodAutoscalerBehaviorPatchPtrOutput) ScaleDown() HPAScalingRulesPatchPtrOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerBehaviorPatch) *HPAScalingRulesPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScaleDown\n\t}).(HPAScalingRulesPatchPtrOutput)\n}", "func (o HorizontalPodAutoscalerBehaviorOutput) ScaleDown() HPAScalingRulesPtrOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerBehavior) *HPAScalingRules { return v.ScaleDown }).(HPAScalingRulesPtrOutput)\n}", "func (in *PasswordPolicyRule) DeepCopy() *PasswordPolicyRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PasswordPolicyRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (p *P1D) Scale(factor float64) {\n\tp.bng.scaleW(factor)\n}", "func (p *Plane) Scale(scaleVec mgl32.Vec3) {\n\tp.model.Scale = scaleVec\n\tp.centroid = CalculateCentroid(p.vertexValues.Vertices, p.model.Scale)\n\tp.boundingBox = ScaleBoundingBox(p.boundingBox, scaleVec)\n}", "func (m *Matrix3) Scale(s float64) {\n\tfor i, x := range m {\n\t\tm[i] = x * s\n\t}\n}", "func (o HorizontalPodAutoscalerBehaviorPtrOutput) ScaleDown() HPAScalingRulesPtrOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerBehavior) *HPAScalingRules {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScaleDown\n\t}).(HPAScalingRulesPtrOutput)\n}", "func (in *ClbStatefulSetRule) DeepCopy() *ClbStatefulSetRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ClbStatefulSetRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c2d *C2DMatrix) Scale(xScale, yScale float64) {\n\tvar mat Matrix\n\n\tmat.m11 = xScale\n\tmat.m12 = 0\n\tmat.m13 = 0\n\n\tmat.m21 = 0\n\tmat.m22 = yScale\n\tmat.m23 = 0\n\n\tmat.m31 = 0\n\tmat.m32 = 0\n\tmat.m33 = 1\n\n\t//and multiply\n\tc2d.MatrixMultiply(mat)\n}", "func (in *ScalableTarget) DeepCopy() *ScalableTarget {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalableTarget)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (t *Transform) Scale() lmath.Vec3 {\n\tt.access.RLock()\n\ts := t.scale\n\tt.access.RUnlock()\n\treturn s\n}", "func (v *Vertex) Scale(l float64) {\n\tv.x *= l\n\tv.y *= l\n}", "func (self Transform) Scale(scaleX, scaleY float32) {\n\tC.sfTransform_scale(self.Cref, C.float(scaleX), C.float(scaleY))\n}", "func (r Rectangle) Scale(factor float32) Rectangle {\n\tret := Rectangle{Width: int32(float32(r.Width) * factor),\n\t\tHeight: int32(float32(r.Height) * factor)}\n\tret.X = r.X + (r.Width-ret.Width)/2\n\tret.Y = r.Y + (r.Height-ret.Height)/2\n\treturn ret\n}", "func (k *kubectlContext) Scale(resource string, scale uint) error {\n\tout, err := k.do(\"scale\", fmt.Sprintf(\"--replicas=%d\", scale), resource)\n\tk.t.Log(string(out))\n\treturn err\n}", "func (t *Transform) SetScale(v *Vector) ITransform {\n\tt.Scale = v\n\treturn t\n}", "func (t *Transform) SetScale(sx, sy float64) *Transform {\n\tt.Scale1.X = sx - 1\n\tt.Scale1.Y = sy - 1\n\treturn t\n}", "func Scale(p point, factor int) point {\n\treturn point{p.x * factor, p.y * factor, p.z * factor}\n}", "func (w *windowImpl) Scale(dr image.Rectangle, src screen.Texture, sr image.Rectangle, op draw.Op, opts *screen.DrawOptions) {\n\tpanic(\"not implemented\") // TODO: Implement\n}", "func (in *SchedulingScaler) DeepCopy() *SchedulingScaler {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScaler)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (self *Rectangle) Scale(x int) *Rectangle{\n return &Rectangle{self.Object.Call(\"scale\", x)}\n}", "func (s *Surface) Scale(x, y float64) {\n\ts.Ctx.Call(\"scale\", x, y)\n}", "func (in *ScheduledPodScaler) DeepCopy() *ScheduledPodScaler {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScaler)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *RGB) Scale(f float32) {\n\tfor k := range c {\n\t\tc[k] *= f\n\t}\n}", "func (a *Workload) Scale(ctx context.Context, instances int32) error {\n\treturn retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\t// Retrieve the latest version of Deployment before attempting update\n\t\t// RetryOnConflict uses exponential backoff to avoid exhausting the apiserver\n\t\tdeployment, err := a.Deployment(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdeployment.Spec.Replicas = &instances\n\n\t\t_, err = a.cluster.Kubectl.AppsV1().Deployments(a.app.Org).Update(\n\t\t\tctx, deployment, metav1.UpdateOptions{})\n\n\t\treturn err\n\t})\n}", "func DeepCopy_v1_ImageResolutionPolicyRule(in interface{}, out interface{}, c *conversion.Cloner) error {\n\t{\n\t\tin := in.(*ImageResolutionPolicyRule)\n\t\tout := out.(*ImageResolutionPolicyRule)\n\t\t*out = *in\n\t\treturn nil\n\t}\n}", "func Scale(s Frac, m M) M {\n\tm = CopyMatrix(m)\n\n\tfor r := 1; r <= m.Rows(); r++ {\n\t\tm.MultiplyRow(r, s)\n\t}\n\n\treturn m\n}", "func (in *FlexibleServersFirewallRule) DeepCopy() *FlexibleServersFirewallRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(FlexibleServersFirewallRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PathRule) DeepCopy() *PathRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PathRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RuleSpec) DeepCopy() *RuleSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RuleSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RuleSpec) DeepCopy() *RuleSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RuleSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (b ResourceBehavior) ToScalingBehavior() *limes.ScalingBehavior {\n\tif b.ScalesWithResourceName == \"\" {\n\t\treturn nil\n\t}\n\treturn &limes.ScalingBehavior{\n\t\tScalesWithServiceType: b.ScalesWithServiceType,\n\t\tScalesWithResourceName: b.ScalesWithResourceName,\n\t\tScalingFactor: b.ScalingFactor,\n\t}\n}", "func (dw *DrawingWand) Scale(x, y float64) {\n\tC.MagickDrawScale(dw.dw, C.double(x), C.double(y))\n}", "func (in *TriggerRule) DeepCopy() *TriggerRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TriggerRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (v *V_elem) Scale(ofs, scale *[3]float32) *[3]int {\n\treturn &[3]int{\n\t\tint((v.x[0] + ofs[0]) * scale[0]),\n\t\tint((v.x[1] + ofs[1]) * scale[1]),\n\t\tint((v.x[2] + ofs[2]) * scale[2]),\n\t}\n}", "func (p *Proc) Scale(x, y float64) {\n\tp.stk.scale(x, y)\n}", "func (v Vec3) Scale(s float64) Vec3 {\n\treturn Vec3{v[0] * s, v[1] * s, v[2] * s}\n}", "func Scale(s float64) Matrix {\n\treturn Matrix{s, 0, 0, s, 0, 0}\n}", "func (rule *Rule) Copy() *Rule {\n\tcpy := *rule\n\tcpy.Key = rule.Key.Copy()\n\tcpy.Value = rule.Value.Copy()\n\tcpy.Body = rule.Body.Copy()\n\treturn &cpy\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * 1\n\tv.Y = v.Y * 1\n}", "func (in *ClusterScaling) DeepCopy() *ClusterScaling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ClusterScaling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DailyRule) DeepCopy() *DailyRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DailyRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (mw *MagickWand) Scale(cols, rows uint) error {\n\treturn mw.ScaleImage(cols, rows)\n}", "func (m *Manager) Scale(shardIDs []int, shardCount int) (err error) {\n\tsg, err := NewShardGroup(m, shardIDs, shardCount)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = sg.Start()\n\treturn\n}", "func (in *Scale) DeepCopyInto(out *Scale) {\n\t*out = *in\n\tin.Scale.DeepCopyInto(&out.Scale)\n\treturn\n}", "func (in *RuleParameters) DeepCopy() *RuleParameters {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RuleParameters)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *CanaryDeployer) Scale(cd *flaggerv1.Canary, replicas int32) error {\n\ttargetName := cd.Spec.TargetRef.Name\n\tdep, err := c.kubeClient.AppsV1().Deployments(cd.Namespace).Get(targetName, metav1.GetOptions{})\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn fmt.Errorf(\"deployment %s.%s not found\", targetName, cd.Namespace)\n\t\t}\n\t\treturn fmt.Errorf(\"deployment %s.%s query error %v\", targetName, cd.Namespace, err)\n\t}\n\n\tdepCopy := dep.DeepCopy()\n\tdepCopy.Spec.Replicas = int32p(replicas)\n\n\t_, err = c.kubeClient.AppsV1().Deployments(dep.Namespace).Update(depCopy)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"scaling %s.%s to %v failed: %v\", depCopy.GetName(), depCopy.Namespace, replicas, err)\n\t}\n\treturn nil\n}", "func (in *AlertingRule) DeepCopy() *AlertingRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AlertingRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X *= f\n\tv.Y *= f\n}", "func (self *Rectangle) ScaleI(args ...interface{}) *Rectangle{\n return &Rectangle{self.Object.Call(\"scale\", args)}\n}", "func (v Vector) Scale(c float64) Vector {\n\tfor i, x := range v {\n\t\tv[i] = x * c\n\t}\n\treturn v\n}", "func (canvas *Canvas) Scale(x, y float32) {\n\twriteCommand(canvas.contents, \"cm\", x, 0, 0, y, 0, 0)\n}", "func (v *Vector) ScaleTo(s float64) {\n\tv.X = s * v.X\n\tv.Y = s * v.Y\n\tv.Z = s * v.Z\n}", "func (in *ScalingPolicy) DeepCopy() *ScalingPolicy {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalingPolicy)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func Scale(f float64, d Number) Number {\n\treturn Number{Real: f * d.Real, E1mag: f * d.E1mag, E2mag: f * d.E2mag, E1E2mag: f * d.E1E2mag}\n}", "func TestScale(t *testing.T) {\n\tvar i, j uint\n\tfor i = 0; i < 100; i++ {\n\t\ta := makeRandomVector(i)\n\t\tx := rand.ExpFloat64()\n\t\tb := Scale(a, x)\n\n\t\tfor j = 0; j < i; j++ {\n\t\t\tif b.dims[j] != a.dims[j]*x {\n\t\t\t\tt.Error(\"Scalar Multiplication failed, \",\n\t\t\t\t\t\"didn't get expected values.\")\n\t\t\t\tt.Logf(\"%f * %f != %f\", a.dims[j], x, b.dims[j])\n\t\t\t}\n\t\t}\n\n\t\t// Test in-place scalar multiplication\n\t\tb = a.Copy()\n\t\tb.Scale(x)\n\n\t\tfor j = 0; j < i; j++ {\n\t\t\tif b.dims[j] != a.dims[j]*x {\n\t\t\t\tt.Error(\"In-place Scalar Multiplication failed, \",\n\t\t\t\t\t\"didn't get expected values.\")\n\t\t\t\tt.Logf(\"%f * %f != %f\", a.dims[j], x, b.dims[j])\n\t\t\t}\n\t\t}\n\t}\n}", "func (v Vector) Scale(scale float64) Vector {\n\treturn Vector{\n\t\tX: v.X * scale,\n\t\tY: v.Y * scale,\n\t\tZ: v.Z * scale}\n}", "func (in *ResourceThresholdStrategy) DeepCopy() *ResourceThresholdStrategy {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ResourceThresholdStrategy)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (this *RectangleShape) SetScale(scale Vector2f) {\n\tC.sfRectangleShape_setScale(this.cptr, scale.toC())\n}", "func (b *Base) Scale(w http.ResponseWriter, r *http.Request) {\n\tb.log.Printf(\"%s %s -> %s\", r.Method, r.URL.Path, r.RemoteAddr)\n\n\tsOptions, pOptions, kOptions, oOptions := render.SetDefaultScaleOptions()\n\n\tpv := render.PageVars{\n\t\tTitle: \"Practice Scales and Arpeggios\", // default scale initially displayed is A Major\n\t\tScalearp: \"Scale\",\n\t\tPitch: \"Major\",\n\t\tKey: \"A\",\n\t\tScaleImgPath: \"img/scale/major/a1.png\",\n\t\tGifPath: \"\",\n\t\tAudioPath: \"mp3/scale/major/a1.mp3\",\n\t\tAudioPath2: \"mp3/drone/a1.mp3\",\n\t\tLeftLabel: \"Listen to Major scale\",\n\t\tRightLabel: \"Listen to Drone\",\n\t\tScaleOptions: sOptions,\n\t\tPitchOptions: pOptions,\n\t\tKeyOptions: kOptions,\n\t\tOctaveOptions: oOptions,\n\t}\n\n\tif err := render.Render(w, \"scale.html\", pv); err != nil {\n\t\tb.log.Printf(\"%s %s -> %s : ERROR : %v\", r.Method, r.URL.Path, r.RemoteAddr, err)\n\t\treturn\n\t}\n}", "func (in *AppAutoscalingRule) DeepCopy() *AppAutoscalingRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AppAutoscalingRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *ProcessClient) Scale(ctx context.Context, guid string, scale *resource.ProcessScale) (*resource.Process, error) {\n\tvar process resource.Process\n\t_, err := c.client.post(ctx, path.Format(\"/v3/processes/%s/actions/scale\", guid), scale, &process)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &process, nil\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}" ]
[ "0.69663656", "0.6074237", "0.5888195", "0.5856589", "0.57944095", "0.5784623", "0.55765456", "0.55765456", "0.55765456", "0.55765456", "0.55765456", "0.54937565", "0.5412746", "0.53581494", "0.5351253", "0.5344039", "0.53345853", "0.5311341", "0.52926254", "0.5274284", "0.52514356", "0.52472067", "0.5241284", "0.52280384", "0.5211288", "0.5189498", "0.51802343", "0.5150034", "0.5147446", "0.51468384", "0.51387185", "0.5137231", "0.5133496", "0.51220566", "0.5116344", "0.5099099", "0.5091423", "0.5088686", "0.5076321", "0.50678694", "0.5059852", "0.50487113", "0.5046112", "0.5034644", "0.5027354", "0.5026179", "0.50189155", "0.5018473", "0.50062203", "0.4965788", "0.49566966", "0.49563843", "0.4954672", "0.49439174", "0.49257717", "0.49164397", "0.48904288", "0.48876584", "0.48849425", "0.48814762", "0.48789054", "0.48691937", "0.4868614", "0.4868614", "0.48555273", "0.485334", "0.48171395", "0.48159704", "0.48063853", "0.47989023", "0.4798719", "0.47828132", "0.47678247", "0.47474945", "0.47471896", "0.47440654", "0.47421104", "0.47365957", "0.4734531", "0.47264794", "0.47105023", "0.4707569", "0.47062597", "0.47060442", "0.47024438", "0.47007662", "0.46967998", "0.4677506", "0.4671622", "0.46682072", "0.46674925", "0.4664807", "0.46614394", "0.46592662", "0.46591675", "0.4658936", "0.4658936", "0.4658936", "0.4658936", "0.4658936" ]
0.86958313
0
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be nonnil.
func (in *ScaleSpec) DeepCopyInto(out *ScaleSpec) { *out = *in }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RunInfo) DeepCopyInto(out *RunInfo) {\n\t*out = *r\n}", "func (in *Base) DeepCopyInto(out *Base) {\n\t*out = *in\n\treturn\n}", "func (in *ForkObject) DeepCopyInto(out *ForkObject) {\n\t*out = *in\n}", "func (in *TargetObjectInfo) DeepCopyInto(out *TargetObjectInfo) {\n\t*out = *in\n}", "func (in *DebugObjectInfo) DeepCopyInto(out *DebugObjectInfo) {\n\t*out = *in\n}", "func (in *Input) DeepCopyInto(out *Input) {\n\t*out = *in\n}", "func (u *SSN) DeepCopyInto(out *SSN) {\n\t*out = *u\n}", "func (in *ExistPvc) DeepCopyInto(out *ExistPvc) {\n\t*out = *in\n}", "func (in *DockerStep) DeepCopyInto(out *DockerStep) {\n\t*out = *in\n\tif in.Inline != nil {\n\t\tin, out := &in.Inline, &out.Inline\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tout.Auth = in.Auth\n\treturn\n}", "func (in *Container) DeepCopyInto(out *Container) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.Command != nil {\n\t\tin, out := &in.Command, &out.Command\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.LifeCycleScript != nil {\n\t\tin, out := &in.LifeCycleScript, &out.LifeCycleScript\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *RuntimeRef) DeepCopyInto(out *RuntimeRef) {\n\t*out = *in\n}", "func (in *Ibft2) DeepCopyInto(out *Ibft2) {\n\t*out = *in\n\treturn\n}", "func (in *TestResult) DeepCopyInto(out *TestResult) {\n\t*out = *in\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *Haproxy) DeepCopyInto(out *Haproxy) {\n\t*out = *in\n\treturn\n}", "func (in *SSH) DeepCopyInto(out *SSH) {\n\t*out = *in\n\treturn\n}", "func (in *Runtime) DeepCopyInto(out *Runtime) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (b *Base64) DeepCopyInto(out *Base64) {\n\t*out = *b\n}", "func (in *EventDependencyTransformer) DeepCopyInto(out *EventDependencyTransformer) {\n\t*out = *in\n\treturn\n}", "func (in *StageOutput) DeepCopyInto(out *StageOutput) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Dependent) DeepCopyInto(out *Dependent) {\n\t*out = *in\n\treturn\n}", "func (in *GitFileGeneratorItem) DeepCopyInto(out *GitFileGeneratorItem) {\n\t*out = *in\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *AnsibleStep) DeepCopyInto(out *AnsibleStep) {\n\t*out = *in\n\treturn\n}", "func (in *Forks) DeepCopyInto(out *Forks) {\n\t*out = *in\n\tif in.DAO != nil {\n\t\tin, out := &in.DAO, &out.DAO\n\t\t*out = new(uint)\n\t\t**out = **in\n\t}\n}", "func (in *ContainerPort) DeepCopyInto(out *ContainerPort) {\n\t*out = *in\n}", "func (in *General) DeepCopyInto(out *General) {\n\t*out = *in\n\treturn\n}", "func (in *IsoContainer) DeepCopyInto(out *IsoContainer) {\n\t*out = *in\n}", "func (in *Git) DeepCopyInto(out *Git) {\n\t*out = *in\n\treturn\n}", "func (in *ConfigFile) DeepCopyInto(out *ConfigFile) {\n\t*out = *in\n}", "func (in *BackupProgress) DeepCopyInto(out *BackupProgress) {\n\t*out = *in\n}", "func (in *DataDisk) DeepCopyInto(out *DataDisk) {\n\t*out = *in\n}", "func (in *PhaseStep) DeepCopyInto(out *PhaseStep) {\n\t*out = *in\n}", "func (u *MAC) DeepCopyInto(out *MAC) {\n\t*out = *u\n}", "func (in *Variable) DeepCopyInto(out *Variable) {\n\t*out = *in\n}", "func (in *RestoreProgress) DeepCopyInto(out *RestoreProgress) {\n\t*out = *in\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *NamespacedObjectReference) DeepCopyInto(out *NamespacedObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Path) DeepCopyInto(out *Path) {\n\t*out = *in\n\treturn\n}", "func (in *GitDirectoryGeneratorItem) DeepCopyInto(out *GitDirectoryGeneratorItem) {\n\t*out = *in\n}", "func (in *NamePath) DeepCopyInto(out *NamePath) {\n\t*out = *in\n\treturn\n}", "func (in *ConsoleCreateObj) DeepCopyInto(out *ConsoleCreateObj) {\n\t*out = *in\n}", "func (in *UsedPipelineRun) DeepCopyInto(out *UsedPipelineRun) {\n\t*out = *in\n}", "func (in *BuildTemplate) DeepCopyInto(out *BuildTemplate) {\n\t*out = *in\n\tif in.Cmd != nil {\n\t\tin, out := &in.Cmd, &out.Cmd\n\t\t*out = make([]BuildTemplateStep, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n}", "func (in *ObjectInfo) DeepCopyInto(out *ObjectInfo) {\n\t*out = *in\n\tout.GroupVersionKind = in.GroupVersionKind\n\treturn\n}", "func (in *Files) DeepCopyInto(out *Files) {\n\t*out = *in\n}", "func (in *Source) DeepCopyInto(out *Source) {\n\t*out = *in\n\tif in.Dependencies != nil {\n\t\tin, out := &in.Dependencies, &out.Dependencies\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MavenRepositories != nil {\n\t\tin, out := &in.MavenRepositories, &out.MavenRepositories\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\treturn\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *StackBuild) DeepCopyInto(out *StackBuild) {\n\t*out = *in\n\treturn\n}", "func (in *BuildTaskRef) DeepCopyInto(out *BuildTaskRef) {\n\t*out = *in\n\treturn\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *PathInfo) DeepCopyInto(out *PathInfo) {\n\t*out = *in\n}", "func (in *PoA) DeepCopyInto(out *PoA) {\n\t*out = *in\n}", "func (in *Section) DeepCopyInto(out *Section) {\n\t*out = *in\n\tif in.SecretRefs != nil {\n\t\tin, out := &in.SecretRefs, &out.SecretRefs\n\t\t*out = make([]SecretReference, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Files != nil {\n\t\tin, out := &in.Files, &out.Files\n\t\t*out = make([]FileMount, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n}", "func (in *DNSSelection) DeepCopyInto(out *DNSSelection) {\n\t*out = *in\n\tif in.Include != nil {\n\t\tin, out := &in.Include, &out.Include\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Exclude != nil {\n\t\tin, out := &in.Exclude, &out.Exclude\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ReleaseVersion) DeepCopyInto(out *ReleaseVersion) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Command) DeepCopyInto(out *Command) {\n\t*out = *in\n\tif in.Flags != nil {\n\t\tin, out := &in.Flags, &out.Flags\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Value != nil {\n\t\tin, out := &in.Value, &out.Value\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *PathRule) DeepCopyInto(out *PathRule) {\n\t*out = *in\n\treturn\n}", "func (in *DockerLifecycleData) DeepCopyInto(out *DockerLifecycleData) {\n\t*out = *in\n}", "func (in *RunScriptStepConfig) DeepCopyInto(out *RunScriptStepConfig) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Checksum) DeepCopyInto(out *Checksum) {\n\t*out = *in\n}", "func (in *DomainNameOutput) DeepCopyInto(out *DomainNameOutput) {\n\t*out = *in\n}", "func (in *InterfaceStruct) DeepCopyInto(out *InterfaceStruct) {\n\t*out = *in\n\tif in.val != nil {\n\t\tin, out := &in.val, &out.val\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Ref) DeepCopyInto(out *Ref) {\n\t*out = *in\n}", "func (in *MemorySpec) DeepCopyInto(out *MemorySpec) {\n\t*out = *in\n}", "func (in *BuildJenkinsInfo) DeepCopyInto(out *BuildJenkinsInfo) {\n\t*out = *in\n\treturn\n}", "func (in *VirtualDatabaseBuildObject) DeepCopyInto(out *VirtualDatabaseBuildObject) {\n\t*out = *in\n\tif in.Incremental != nil {\n\t\tin, out := &in.Incremental, &out.Incremental\n\t\t*out = new(bool)\n\t\t**out = **in\n\t}\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]v1.EnvVar, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\tout.Git = in.Git\n\tin.Source.DeepCopyInto(&out.Source)\n\tif in.Webhooks != nil {\n\t\tin, out := &in.Webhooks, &out.Webhooks\n\t\t*out = make([]WebhookSecret, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *MaintenanceInfo) DeepCopyInto(out *MaintenanceInfo) {\n\t*out = *in\n\treturn\n}", "func (in *KopsNode) DeepCopyInto(out *KopsNode) {\n\t*out = *in\n\treturn\n}", "func (in *FalconAPI) DeepCopyInto(out *FalconAPI) {\n\t*out = *in\n}", "func (in *EBS) DeepCopyInto(out *EBS) {\n\t*out = *in\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n\treturn\n}", "func (in *Empty) DeepCopyInto(out *Empty) {\n\t*out = *in\n\tout.XXX_NoUnkeyedLiteral = in.XXX_NoUnkeyedLiteral\n\tif in.XXX_unrecognized != nil {\n\t\tin, out := &in.XXX_unrecognized, &out.XXX_unrecognized\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ComponentDistGit) DeepCopyInto(out *ComponentDistGit) {\n\t*out = *in\n\treturn\n}", "func (in *Memory) DeepCopyInto(out *Memory) {\n\t*out = *in\n\tout.Required = in.Required.DeepCopy()\n}", "func (in *Persistence) DeepCopyInto(out *Persistence) {\n\t*out = *in\n\tout.Size = in.Size.DeepCopy()\n\treturn\n}", "func (in *ManagedDisk) DeepCopyInto(out *ManagedDisk) {\n\t*out = *in\n}", "func (e *Email) DeepCopyInto(out *Email) {\n\t*out = *e\n}", "func (in *ImageInfo) DeepCopyInto(out *ImageInfo) {\n\t*out = *in\n}", "func (in *ShootRef) DeepCopyInto(out *ShootRef) {\n\t*out = *in\n}", "func (in *N3000Fpga) DeepCopyInto(out *N3000Fpga) {\n\t*out = *in\n}", "func (in *NetflowType) DeepCopyInto(out *NetflowType) {\n\t*out = *in\n\treturn\n}", "func (in *BuiltInAdapter) DeepCopyInto(out *BuiltInAdapter) {\n\t*out = *in\n}", "func (in *Node) DeepCopyInto(out *Node) {\n\t*out = *in\n\tif in.FailStatus != nil {\n\t\tin, out := &in.FailStatus, &out.FailStatus\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MigratingSlots != nil {\n\t\tin, out := &in.MigratingSlots, &out.MigratingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.ImportingSlots != nil {\n\t\tin, out := &in.ImportingSlots, &out.ImportingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n}", "func (in *CPUSpec) DeepCopyInto(out *CPUSpec) {\n\t*out = *in\n}", "func (in *LoopState) DeepCopyInto(out *LoopState) {\n\t*out = *in\n}" ]
[ "0.8215289", "0.81280124", "0.81039286", "0.80862963", "0.8083811", "0.80673146", "0.8064545", "0.8026454", "0.8012046", "0.7996313", "0.799204", "0.79887754", "0.7987097", "0.7986994", "0.7986994", "0.79854053", "0.7975989", "0.7972486", "0.79695636", "0.79695636", "0.79695636", "0.7967528", "0.79624444", "0.7961954", "0.7945754", "0.7945754", "0.7944541", "0.79428566", "0.7942668", "0.7942668", "0.7940451", "0.793851", "0.7936731", "0.79294837", "0.79252166", "0.7915377", "0.7911627", "0.7911138", "0.7909384", "0.790913", "0.7908773", "0.7905649", "0.79050326", "0.7904594", "0.7904594", "0.7904235", "0.79036915", "0.79020816", "0.78988886", "0.78977424", "0.7891376", "0.7891024", "0.7889831", "0.78890276", "0.7887135", "0.788637", "0.7885264", "0.7885264", "0.7884786", "0.7880785", "0.78745943", "0.78745943", "0.78745407", "0.78734446", "0.78724426", "0.78713626", "0.78713554", "0.78652424", "0.7863321", "0.7863321", "0.7863321", "0.7863293", "0.7862628", "0.7860664", "0.7858556", "0.785785", "0.78571486", "0.7851332", "0.78453225", "0.78448987", "0.78415996", "0.7837483", "0.7837037", "0.7836443", "0.78351796", "0.78329664", "0.7831094", "0.7829445", "0.7826582", "0.7824499", "0.78242797", "0.78227437", "0.78192484", "0.7818843", "0.78128535", "0.7812535", "0.78111476", "0.78111106", "0.781107", "0.78093034", "0.7808775" ]
0.0
-1
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ScaleSpec.
func (in *ScaleSpec) DeepCopy() *ScaleSpec { if in == nil { return nil } out := new(ScaleSpec) in.DeepCopyInto(out) return out }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in *Scale) DeepCopy() *Scale {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Scale)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScalableTargetSpec) DeepCopy() *ScalableTargetSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalableTargetSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScalingPolicySpec) DeepCopy() *ScalingPolicySpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalingPolicySpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerSpec) DeepCopy() *ScheduledPodScalerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScalerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *MetricsSpec) DeepCopy() *MetricsSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MetricsSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Spec) DeepCopy() *Spec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Spec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Spec) DeepCopy() *Spec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Spec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerSpec) DeepCopy() *SchedulingScalerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in ChartSpec) DeepCopy() ChartSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ChartSpec)\n\tin.DeepCopyInto(out)\n\treturn *out\n}", "func (in *ScaleRule) DeepCopy() *ScaleRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (r Rectangle) Scale(factor float64) Rectangle {\n\treturn Rectangle{\n\t\tMin: r.Min.Mul(factor),\n\t\tMax: r.Max.Mul(factor),\n\t}\n}", "func (self *T) Scale(f float64) *T {\n\tself[0] *= f\n\tself[1] *= f\n\treturn self\n}", "func (in *ScaleTarget) DeepCopy() *ScaleTarget {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleTarget)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (wv *Spectrum) Scale(s float32) {\n\twv.C[0] *= s\n\twv.C[1] *= s\n\twv.C[2] *= s\n\twv.C[3] *= s\n}", "func (scaleSet *VirtualMachineScaleSet) GetSpec() genruntime.ConvertibleSpec {\n\treturn &scaleSet.Spec\n}", "func (in *SpeakerSpec) DeepCopy() *SpeakerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SpeakerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (self *T) Scale(f float32) *T {\n\tself[0][0] *= f\n\tself[1][1] *= f\n\treturn self\n}", "func (in *PrometheusSpec) DeepCopy() *PrometheusSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PrometheusSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PrometheusSpec) DeepCopy() *PrometheusSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PrometheusSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PrometheusSpec) DeepCopy() *PrometheusSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PrometheusSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func Scale(value float64) *SimpleElement { return newSEFloat(\"scale\", value) }", "func (p Point) Scale(s Length) Point {\n\treturn Point{p.X * s, p.Y * s}\n}", "func (this *RectangleShape) Scale(factor Vector2f) {\n\tC.sfRectangleShape_scale(this.cptr, factor.toC())\n}", "func (in *HierarchySpec) DeepCopy() *HierarchySpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HierarchySpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (s SamplesC64) Scale(r float32) {\n\tsimd.ScaleComplex(r, s)\n}", "func (in *FlexibleServers_FirewallRule_Spec) DeepCopy() *FlexibleServers_FirewallRule_Spec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(FlexibleServers_FirewallRule_Spec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SplunkResourcesSpec) DeepCopy() *SplunkResourcesSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SplunkResourcesSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RSSPodSpec) DeepCopy() *RSSPodSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RSSPodSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (p *P1D) Scale(factor float64) {\n\tp.bng.scaleW(factor)\n}", "func (s *UpdateTaskSetInput) SetScale(v *Scale) *UpdateTaskSetInput {\n\ts.Scale = v\n\treturn s\n}", "func (in *ScaleList) DeepCopy() *ScaleList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (s *CreateTaskSetInput) SetScale(v *Scale) *CreateTaskSetInput {\n\ts.Scale = v\n\treturn s\n}", "func (in *SplitterSpec) DeepCopy() *SplitterSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SplitterSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ReplicationSpec) DeepCopy() *ReplicationSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ReplicationSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (p Period) Scale(factor float64) *Period {\n\tresult, _ := p.ScaleWithOverflowCheck(factor)\n\treturn result\n}", "func (tfs *tiflashScaler) Scale(tc *v1alpha1.TidbCluster, oldSet *apps.StatefulSet, newSet *apps.StatefulSet) error {\n\tscaling, _, _, _ := scaleOne(oldSet, newSet)\n\tif scaling > 0 {\n\t\treturn tfs.ScaleOut(tc, oldSet, newSet)\n\t} else if scaling < 0 {\n\t\treturn tfs.ScaleIn(tc, oldSet, newSet)\n\t}\n\t// we only sync auto scaler annotations when we are finishing syncing scaling\n\treturn tfs.SyncAutoScalerAnn(tc, oldSet)\n}", "func Scale(f float64, d Number) Number {\n\treturn Number{Real: f * d.Real, E1mag: f * d.E1mag, E2mag: f * d.E2mag, E1E2mag: f * d.E1E2mag}\n}", "func (in *SensorSpec) DeepCopy() *SensorSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SensorSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (ki *KernelInfo) Scale(scale float64, normalizeType KernelNormalizeType) {\n\tC.ScaleKernelInfo(ki.info, C.double(scale), C.GeometryFlags(normalizeType))\n\truntime.KeepAlive(ki)\n}", "func (in *AzsbLimitsSpec) DeepCopy() *AzsbLimitsSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AzsbLimitsSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PipelineSpec) DeepCopy() *PipelineSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PipelineSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PipelineSpec) DeepCopy() *PipelineSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PipelineSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PipelineSpec) DeepCopy() *PipelineSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PipelineSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (t *Transform) SetScale(v *Vector) ITransform {\n\tt.Scale = v\n\treturn t\n}", "func (in *StatsSpec) DeepCopy() *StatsSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(StatsSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PoolSpec) DeepCopy() *PoolSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PoolSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PoolSpec) DeepCopy() *PoolSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PoolSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PoolSpec) DeepCopy() *PoolSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PoolSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PoolSpec) DeepCopy() *PoolSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PoolSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (s *TaskSet) SetScale(v *Scale) *TaskSet {\n\ts.Scale = v\n\treturn s\n}", "func (in *MetricSpec) DeepCopy() *MetricSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MetricSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (p Point) Scale(s float64) Point {\n\treturn NewPoint(p.X*s, p.Y*s)\n}", "func (in *PSPSpec) DeepCopy() *PSPSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PSPSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (q1 Quat) Scale(c float32) Quat {\n\treturn Quat{q1.W * c, Vec3{q1.V[0] * c, q1.V[1] * c, q1.V[2] * c}}\n}", "func (in *PDSpec) DeepCopy() *PDSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PDSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SubnetSpec) DeepCopy() *SubnetSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubnetSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (this *Transformable) Scale(factor Vector2f) {\n\tC.sfTransformable_scale(this.cptr, factor.toC())\n}", "func (in *LabelSpec) DeepCopy() *LabelSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(LabelSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *LabelSpec) DeepCopy() *LabelSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(LabelSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *LabelSpec) DeepCopy() *LabelSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(LabelSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *LabelSpec) DeepCopy() *LabelSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(LabelSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c mockK8sClient) Scale(resource *kubernetes.Workload, replicas int32) error {\n\tc.Counts.NumPods = replicas\n\treturn nil\n}", "func (in *RocketmqSpec) DeepCopy() *RocketmqSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RocketmqSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AWSMachinePoolSpec) DeepCopy() *AWSMachinePoolSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AWSMachinePoolSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SubscriptionSpec) DeepCopy() *SubscriptionSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubscriptionSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SubscriptionSpec) DeepCopy() *SubscriptionSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubscriptionSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SinkSpec) DeepCopy() *SinkSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SinkSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (p *Point) Scale(v float64) {\n\tp.x *= v\n\tp.y *= v\n}", "func (w *windowImpl) Scale(dr image.Rectangle, src screen.Texture, sr image.Rectangle, op draw.Op, opts *screen.DrawOptions) {\n\tpanic(\"not implemented\") // TODO: Implement\n}", "func (in *SDSpec) DeepCopy() *SDSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SDSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PlexSpec) DeepCopy() *PlexSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PlexSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *StreamSpec) DeepCopy() *StreamSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(StreamSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *FalconContainerSpec) DeepCopy() *FalconContainerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(FalconContainerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *StatefulSetSpec) DeepCopy() *StatefulSetSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(StatefulSetSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (t *Transform) SetScale(sx, sy float64) *Transform {\n\tt.Scale1.X = sx - 1\n\tt.Scale1.Y = sy - 1\n\treturn t\n}", "func (r Rectangle) Scale(factor float32) Rectangle {\n\tret := Rectangle{Width: int32(float32(r.Width) * factor),\n\t\tHeight: int32(float32(r.Height) * factor)}\n\tret.X = r.X + (r.Width-ret.Width)/2\n\tret.Y = r.Y + (r.Height-ret.Height)/2\n\treturn ret\n}", "func (in *PredictorSpec) DeepCopy() *PredictorSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PredictorSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *BlogPostSpec) DeepCopy() *BlogPostSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(BlogPostSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WorkloadSpec) DeepCopy() *WorkloadSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WorkloadSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (p Point) Scale(f float64) Point {\n\treturn Point{p[0] * f, p[1] * f, p[2] * f}\n}", "func (in *SubscriberSpec) DeepCopy() *SubscriberSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubscriberSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *S3Spec) DeepCopy() *S3Spec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(S3Spec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (p *Proc) Scale(x, y float64) {\n\tp.stk.scale(x, y)\n}", "func (in *EKSManagedSpec) DeepCopy() *EKSManagedSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(EKSManagedSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *KMSIssuerSpec) DeepCopy() *KMSIssuerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(KMSIssuerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *MetricsCollectorSpec) DeepCopy() *MetricsCollectorSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MetricsCollectorSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (m *IoK8sAPIAutoscalingV1ScaleSpec) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (in *Component_Spec) DeepCopy() *Component_Spec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Component_Spec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c2d *C2DMatrix) Scale(xScale, yScale float64) {\n\tvar mat Matrix\n\n\tmat.m11 = xScale\n\tmat.m12 = 0\n\tmat.m13 = 0\n\n\tmat.m21 = 0\n\tmat.m22 = yScale\n\tmat.m23 = 0\n\n\tmat.m31 = 0\n\tmat.m32 = 0\n\tmat.m33 = 1\n\n\t//and multiply\n\tc2d.MatrixMultiply(mat)\n}", "func (s *Surface) Scale(x, y float64) {\n\ts.Ctx.Call(\"scale\", x, y)\n}", "func (in *StageSpec) DeepCopy() *StageSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(StageSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *StackSpec) DeepCopy() *StackSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(StackSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *KubeStateMetricsSpec) DeepCopy() *KubeStateMetricsSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(KubeStateMetricsSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *FlexibleServer_Spec) DeepCopy() *FlexibleServer_Spec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(FlexibleServer_Spec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SSMParameterSpec) DeepCopy() *SSMParameterSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SSMParameterSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PushSpec) DeepCopy() *PushSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PushSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ResourceGroup_Spec) DeepCopy() *ResourceGroup_Spec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ResourceGroup_Spec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PortSpec) DeepCopy() *PortSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PortSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ResourceSpec) DeepCopy() *ResourceSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ResourceSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ResourceSpec) DeepCopy() *ResourceSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ResourceSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}" ]
[ "0.6918439", "0.64695114", "0.64396256", "0.6130816", "0.60759723", "0.6040713", "0.6040713", "0.59715873", "0.59645355", "0.5837462", "0.5815961", "0.579574", "0.5686585", "0.5682257", "0.56207305", "0.55996025", "0.5592483", "0.5588218", "0.5588218", "0.5588218", "0.558774", "0.55732876", "0.55653965", "0.55582356", "0.5544847", "0.5534013", "0.551814", "0.55148774", "0.5479581", "0.5476742", "0.5456335", "0.54550725", "0.54446816", "0.5436417", "0.54361045", "0.54169625", "0.5411694", "0.5383028", "0.538037", "0.5360117", "0.5353644", "0.5353644", "0.5353644", "0.5352152", "0.5322532", "0.5319017", "0.5319017", "0.5319017", "0.5319017", "0.53170013", "0.53082025", "0.52994484", "0.528416", "0.52800876", "0.52786386", "0.526812", "0.52619845", "0.5257846", "0.5257846", "0.5257846", "0.5257846", "0.5247499", "0.5240209", "0.5230823", "0.5228992", "0.5228992", "0.5214967", "0.5214291", "0.52125627", "0.5210101", "0.5208209", "0.52073395", "0.5199783", "0.51990163", "0.51895255", "0.518907", "0.5188367", "0.5177411", "0.5172265", "0.5155679", "0.5154415", "0.51509404", "0.5141544", "0.5140989", "0.51399195", "0.5136068", "0.51352555", "0.5129671", "0.5129225", "0.512529", "0.5123889", "0.51212776", "0.51189226", "0.5118761", "0.51163715", "0.51127666", "0.5103802", "0.5100321", "0.5097782", "0.5097782" ]
0.883849
0
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be nonnil.
func (in *ScaleTarget) DeepCopyInto(out *ScaleTarget) { *out = *in if in.Selectors != nil { in, out := &in.Selectors, &out.Selectors *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RunInfo) DeepCopyInto(out *RunInfo) {\n\t*out = *r\n}", "func (in *Base) DeepCopyInto(out *Base) {\n\t*out = *in\n\treturn\n}", "func (in *ForkObject) DeepCopyInto(out *ForkObject) {\n\t*out = *in\n}", "func (in *TargetObjectInfo) DeepCopyInto(out *TargetObjectInfo) {\n\t*out = *in\n}", "func (in *DebugObjectInfo) DeepCopyInto(out *DebugObjectInfo) {\n\t*out = *in\n}", "func (in *Input) DeepCopyInto(out *Input) {\n\t*out = *in\n}", "func (u *SSN) DeepCopyInto(out *SSN) {\n\t*out = *u\n}", "func (in *ExistPvc) DeepCopyInto(out *ExistPvc) {\n\t*out = *in\n}", "func (in *DockerStep) DeepCopyInto(out *DockerStep) {\n\t*out = *in\n\tif in.Inline != nil {\n\t\tin, out := &in.Inline, &out.Inline\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tout.Auth = in.Auth\n\treturn\n}", "func (in *Container) DeepCopyInto(out *Container) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.Command != nil {\n\t\tin, out := &in.Command, &out.Command\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.LifeCycleScript != nil {\n\t\tin, out := &in.LifeCycleScript, &out.LifeCycleScript\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *RuntimeRef) DeepCopyInto(out *RuntimeRef) {\n\t*out = *in\n}", "func (in *Ibft2) DeepCopyInto(out *Ibft2) {\n\t*out = *in\n\treturn\n}", "func (in *TestResult) DeepCopyInto(out *TestResult) {\n\t*out = *in\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *Haproxy) DeepCopyInto(out *Haproxy) {\n\t*out = *in\n\treturn\n}", "func (in *SSH) DeepCopyInto(out *SSH) {\n\t*out = *in\n\treturn\n}", "func (in *Runtime) DeepCopyInto(out *Runtime) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (b *Base64) DeepCopyInto(out *Base64) {\n\t*out = *b\n}", "func (in *EventDependencyTransformer) DeepCopyInto(out *EventDependencyTransformer) {\n\t*out = *in\n\treturn\n}", "func (in *StageOutput) DeepCopyInto(out *StageOutput) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Dependent) DeepCopyInto(out *Dependent) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *GitFileGeneratorItem) DeepCopyInto(out *GitFileGeneratorItem) {\n\t*out = *in\n}", "func (in *AnsibleStep) DeepCopyInto(out *AnsibleStep) {\n\t*out = *in\n\treturn\n}", "func (in *Forks) DeepCopyInto(out *Forks) {\n\t*out = *in\n\tif in.DAO != nil {\n\t\tin, out := &in.DAO, &out.DAO\n\t\t*out = new(uint)\n\t\t**out = **in\n\t}\n}", "func (in *ContainerPort) DeepCopyInto(out *ContainerPort) {\n\t*out = *in\n}", "func (in *General) DeepCopyInto(out *General) {\n\t*out = *in\n\treturn\n}", "func (in *IsoContainer) DeepCopyInto(out *IsoContainer) {\n\t*out = *in\n}", "func (in *Git) DeepCopyInto(out *Git) {\n\t*out = *in\n\treturn\n}", "func (in *BackupProgress) DeepCopyInto(out *BackupProgress) {\n\t*out = *in\n}", "func (in *ConfigFile) DeepCopyInto(out *ConfigFile) {\n\t*out = *in\n}", "func (in *DataDisk) DeepCopyInto(out *DataDisk) {\n\t*out = *in\n}", "func (in *PhaseStep) DeepCopyInto(out *PhaseStep) {\n\t*out = *in\n}", "func (u *MAC) DeepCopyInto(out *MAC) {\n\t*out = *u\n}", "func (in *Variable) DeepCopyInto(out *Variable) {\n\t*out = *in\n}", "func (in *RestoreProgress) DeepCopyInto(out *RestoreProgress) {\n\t*out = *in\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *NamespacedObjectReference) DeepCopyInto(out *NamespacedObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Path) DeepCopyInto(out *Path) {\n\t*out = *in\n\treturn\n}", "func (in *GitDirectoryGeneratorItem) DeepCopyInto(out *GitDirectoryGeneratorItem) {\n\t*out = *in\n}", "func (in *NamePath) DeepCopyInto(out *NamePath) {\n\t*out = *in\n\treturn\n}", "func (in *ConsoleCreateObj) DeepCopyInto(out *ConsoleCreateObj) {\n\t*out = *in\n}", "func (in *UsedPipelineRun) DeepCopyInto(out *UsedPipelineRun) {\n\t*out = *in\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n}", "func (in *BuildTemplate) DeepCopyInto(out *BuildTemplate) {\n\t*out = *in\n\tif in.Cmd != nil {\n\t\tin, out := &in.Cmd, &out.Cmd\n\t\t*out = make([]BuildTemplateStep, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\treturn\n}", "func (in *ObjectInfo) DeepCopyInto(out *ObjectInfo) {\n\t*out = *in\n\tout.GroupVersionKind = in.GroupVersionKind\n\treturn\n}", "func (in *Files) DeepCopyInto(out *Files) {\n\t*out = *in\n}", "func (in *Source) DeepCopyInto(out *Source) {\n\t*out = *in\n\tif in.Dependencies != nil {\n\t\tin, out := &in.Dependencies, &out.Dependencies\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MavenRepositories != nil {\n\t\tin, out := &in.MavenRepositories, &out.MavenRepositories\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\treturn\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *StackBuild) DeepCopyInto(out *StackBuild) {\n\t*out = *in\n\treturn\n}", "func (in *BuildTaskRef) DeepCopyInto(out *BuildTaskRef) {\n\t*out = *in\n\treturn\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *PathInfo) DeepCopyInto(out *PathInfo) {\n\t*out = *in\n}", "func (in *PoA) DeepCopyInto(out *PoA) {\n\t*out = *in\n}", "func (in *Section) DeepCopyInto(out *Section) {\n\t*out = *in\n\tif in.SecretRefs != nil {\n\t\tin, out := &in.SecretRefs, &out.SecretRefs\n\t\t*out = make([]SecretReference, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Files != nil {\n\t\tin, out := &in.Files, &out.Files\n\t\t*out = make([]FileMount, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *DNSSelection) DeepCopyInto(out *DNSSelection) {\n\t*out = *in\n\tif in.Include != nil {\n\t\tin, out := &in.Include, &out.Include\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Exclude != nil {\n\t\tin, out := &in.Exclude, &out.Exclude\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n}", "func (in *ReleaseVersion) DeepCopyInto(out *ReleaseVersion) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *PathRule) DeepCopyInto(out *PathRule) {\n\t*out = *in\n\treturn\n}", "func (in *Command) DeepCopyInto(out *Command) {\n\t*out = *in\n\tif in.Flags != nil {\n\t\tin, out := &in.Flags, &out.Flags\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Value != nil {\n\t\tin, out := &in.Value, &out.Value\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *DockerLifecycleData) DeepCopyInto(out *DockerLifecycleData) {\n\t*out = *in\n}", "func (in *RunScriptStepConfig) DeepCopyInto(out *RunScriptStepConfig) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Checksum) DeepCopyInto(out *Checksum) {\n\t*out = *in\n}", "func (in *DomainNameOutput) DeepCopyInto(out *DomainNameOutput) {\n\t*out = *in\n}", "func (in *InterfaceStruct) DeepCopyInto(out *InterfaceStruct) {\n\t*out = *in\n\tif in.val != nil {\n\t\tin, out := &in.val, &out.val\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Ref) DeepCopyInto(out *Ref) {\n\t*out = *in\n}", "func (in *MemorySpec) DeepCopyInto(out *MemorySpec) {\n\t*out = *in\n}", "func (in *BuildJenkinsInfo) DeepCopyInto(out *BuildJenkinsInfo) {\n\t*out = *in\n\treturn\n}", "func (in *KopsNode) DeepCopyInto(out *KopsNode) {\n\t*out = *in\n\treturn\n}", "func (in *MaintenanceInfo) DeepCopyInto(out *MaintenanceInfo) {\n\t*out = *in\n\treturn\n}", "func (in *VirtualDatabaseBuildObject) DeepCopyInto(out *VirtualDatabaseBuildObject) {\n\t*out = *in\n\tif in.Incremental != nil {\n\t\tin, out := &in.Incremental, &out.Incremental\n\t\t*out = new(bool)\n\t\t**out = **in\n\t}\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]v1.EnvVar, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\tout.Git = in.Git\n\tin.Source.DeepCopyInto(&out.Source)\n\tif in.Webhooks != nil {\n\t\tin, out := &in.Webhooks, &out.Webhooks\n\t\t*out = make([]WebhookSecret, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *FalconAPI) DeepCopyInto(out *FalconAPI) {\n\t*out = *in\n}", "func (in *EBS) DeepCopyInto(out *EBS) {\n\t*out = *in\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n\treturn\n}", "func (in *Empty) DeepCopyInto(out *Empty) {\n\t*out = *in\n\tout.XXX_NoUnkeyedLiteral = in.XXX_NoUnkeyedLiteral\n\tif in.XXX_unrecognized != nil {\n\t\tin, out := &in.XXX_unrecognized, &out.XXX_unrecognized\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ComponentDistGit) DeepCopyInto(out *ComponentDistGit) {\n\t*out = *in\n\treturn\n}", "func (in *Persistence) DeepCopyInto(out *Persistence) {\n\t*out = *in\n\tout.Size = in.Size.DeepCopy()\n\treturn\n}", "func (in *Memory) DeepCopyInto(out *Memory) {\n\t*out = *in\n\tout.Required = in.Required.DeepCopy()\n}", "func (in *ManagedDisk) DeepCopyInto(out *ManagedDisk) {\n\t*out = *in\n}", "func (e *Email) DeepCopyInto(out *Email) {\n\t*out = *e\n}", "func (in *ImageInfo) DeepCopyInto(out *ImageInfo) {\n\t*out = *in\n}", "func (in *ShootRef) DeepCopyInto(out *ShootRef) {\n\t*out = *in\n}", "func (in *NetflowType) DeepCopyInto(out *NetflowType) {\n\t*out = *in\n\treturn\n}", "func (in *N3000Fpga) DeepCopyInto(out *N3000Fpga) {\n\t*out = *in\n}", "func (in *BuiltInAdapter) DeepCopyInto(out *BuiltInAdapter) {\n\t*out = *in\n}", "func (in *Node) DeepCopyInto(out *Node) {\n\t*out = *in\n\tif in.FailStatus != nil {\n\t\tin, out := &in.FailStatus, &out.FailStatus\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MigratingSlots != nil {\n\t\tin, out := &in.MigratingSlots, &out.MigratingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.ImportingSlots != nil {\n\t\tin, out := &in.ImportingSlots, &out.ImportingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n}", "func (in *CPUSpec) DeepCopyInto(out *CPUSpec) {\n\t*out = *in\n}", "func (in *LoopState) DeepCopyInto(out *LoopState) {\n\t*out = *in\n}" ]
[ "0.8215148", "0.8128148", "0.8104491", "0.8086232", "0.8083645", "0.80681837", "0.8064712", "0.80272263", "0.80118906", "0.79957503", "0.79923207", "0.79894227", "0.79878217", "0.7987706", "0.7987706", "0.79856145", "0.7976737", "0.797243", "0.79705614", "0.79705614", "0.79705614", "0.7967998", "0.7963185", "0.7962239", "0.7946799", "0.7946799", "0.79451364", "0.79437023", "0.79437023", "0.79423654", "0.79407156", "0.79375064", "0.79369694", "0.7929554", "0.7925828", "0.79153883", "0.79121333", "0.7912032", "0.7910158", "0.79093456", "0.79087806", "0.7906067", "0.7906014", "0.7905399", "0.7905399", "0.79051214", "0.790477", "0.79011744", "0.7899582", "0.7897098", "0.7891637", "0.78907233", "0.78905463", "0.78897065", "0.78873104", "0.7886752", "0.7885397", "0.7885397", "0.7885259", "0.78815824", "0.787546", "0.787546", "0.7875398", "0.78739077", "0.78724843", "0.78717405", "0.78714716", "0.7865966", "0.7864238", "0.7864238", "0.7864238", "0.7863405", "0.7862614", "0.7860687", "0.78587526", "0.7858436", "0.78570235", "0.78514445", "0.7846122", "0.78443074", "0.78416294", "0.7837446", "0.78372633", "0.78368735", "0.78350383", "0.7833183", "0.78313106", "0.7830074", "0.78268486", "0.78255475", "0.7825175", "0.78235906", "0.78204864", "0.78198004", "0.7812933", "0.7811604", "0.78113776", "0.7810981", "0.78103817", "0.7809776", "0.78089356" ]
0.0
-1
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ScaleTarget.
func (in *ScaleTarget) DeepCopy() *ScaleTarget { if in == nil { return nil } out := new(ScaleTarget) in.DeepCopyInto(out) return out }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in *Scale) DeepCopy() *Scale {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Scale)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScalableTarget) DeepCopy() *ScalableTarget {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalableTarget)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScaleRule) DeepCopy() *ScaleRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (self *T) Scale(f float64) *T {\n\tself[0] *= f\n\tself[1] *= f\n\treturn self\n}", "func (o HorizontalPodAutoscalerSpecOutput) ScaleTargetRef() CrossVersionObjectReferenceOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerSpec) CrossVersionObjectReference { return v.ScaleTargetRef }).(CrossVersionObjectReferenceOutput)\n}", "func (o HorizontalPodAutoscalerSpecOutput) ScaleTargetRef() CrossVersionObjectReferenceOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerSpec) CrossVersionObjectReference { return v.ScaleTargetRef }).(CrossVersionObjectReferenceOutput)\n}", "func (t *Transform) SetScale(v *Vector) ITransform {\n\tt.Scale = v\n\treturn t\n}", "func (p Point) Scale(s Length) Point {\n\treturn Point{p.X * s, p.Y * s}\n}", "func (p *Point) Scale(v float64) {\n\tp.x *= v\n\tp.y *= v\n}", "func (t *Transform) Scale(sx, sy float64) {\n\tout := fmt.Sprintf(\"scale(%g,%g)\", sx, sy)\n\n\tt.transforms = append(t.transforms, out)\n}", "func (tfs *tiflashScaler) Scale(tc *v1alpha1.TidbCluster, oldSet *apps.StatefulSet, newSet *apps.StatefulSet) error {\n\tscaling, _, _, _ := scaleOne(oldSet, newSet)\n\tif scaling > 0 {\n\t\treturn tfs.ScaleOut(tc, oldSet, newSet)\n\t} else if scaling < 0 {\n\t\treturn tfs.ScaleIn(tc, oldSet, newSet)\n\t}\n\t// we only sync auto scaler annotations when we are finishing syncing scaling\n\treturn tfs.SyncAutoScalerAnn(tc, oldSet)\n}", "func (in *ScaleList) DeepCopy() *ScaleList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (s *UpdateTaskSetInput) SetScale(v *Scale) *UpdateTaskSetInput {\n\ts.Scale = v\n\treturn s\n}", "func (o BeanstalkScheduledTaskOutput) ScaleTargetCapacity() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BeanstalkScheduledTask) *string { return v.ScaleTargetCapacity }).(pulumi.StringPtrOutput)\n}", "func (in *ScalableTargetList) DeepCopy() *ScalableTargetList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalableTargetList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (s *TaskSet) SetScale(v *Scale) *TaskSet {\n\ts.Scale = v\n\treturn s\n}", "func (self *T) Scale(f float32) *T {\n\tself[0][0] *= f\n\tself[1][1] *= f\n\treturn self\n}", "func (o HorizontalPodAutoscalerSpecPatchOutput) ScaleTargetRef() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerSpecPatch) *CrossVersionObjectReferencePatch { return v.ScaleTargetRef }).(CrossVersionObjectReferencePatchPtrOutput)\n}", "func (o HorizontalPodAutoscalerSpecPatchOutput) ScaleTargetRef() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerSpecPatch) *CrossVersionObjectReferencePatch { return v.ScaleTargetRef }).(CrossVersionObjectReferencePatchPtrOutput)\n}", "func (s *CreateTaskSetInput) SetScale(v *Scale) *CreateTaskSetInput {\n\ts.Scale = v\n\treturn s\n}", "func (in *ScaleSpec) DeepCopy() *ScaleSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (t *Transform) SetScale(sx, sy float64) *Transform {\n\tt.Scale1.X = sx - 1\n\tt.Scale1.Y = sy - 1\n\treturn t\n}", "func (self Transform) Scale(scaleX, scaleY float32) {\n\tC.sfTransform_scale(self.Cref, C.float(scaleX), C.float(scaleY))\n}", "func (this *Transformable) Scale(factor Vector2f) {\n\tC.sfTransformable_scale(this.cptr, factor.toC())\n}", "func (in *ElasticsearchDataSetScaling) DeepCopy() *ElasticsearchDataSetScaling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ElasticsearchDataSetScaling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o ArgoCDSpecServerAutoscaleHpaOutput) ScaleTargetRef() ArgoCDSpecServerAutoscaleHpaScaleTargetRefOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecServerAutoscaleHpa) ArgoCDSpecServerAutoscaleHpaScaleTargetRef {\n\t\treturn v.ScaleTargetRef\n\t}).(ArgoCDSpecServerAutoscaleHpaScaleTargetRefOutput)\n}", "func (c *canvasRenderer) Scale(amount sprec.Vec2) {\n\tc.currentLayer.Transform = sprec.Mat4Prod(\n\t\tc.currentLayer.Transform,\n\t\tsprec.ScaleMat4(amount.X, amount.Y, 1.0),\n\t)\n}", "func (t *Transform) Scale() lmath.Vec3 {\n\tt.access.RLock()\n\ts := t.scale\n\tt.access.RUnlock()\n\treturn s\n}", "func (p Point) Scale(s float64) Point {\n\treturn NewPoint(p.X*s, p.Y*s)\n}", "func (o HorizontalPodAutoscalerSpecPatchPtrOutput) ScaleTargetRef() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerSpecPatch) *CrossVersionObjectReferencePatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScaleTargetRef\n\t}).(CrossVersionObjectReferencePatchPtrOutput)\n}", "func (o HorizontalPodAutoscalerSpecPatchPtrOutput) ScaleTargetRef() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerSpecPatch) *CrossVersionObjectReferencePatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScaleTargetRef\n\t}).(CrossVersionObjectReferencePatchPtrOutput)\n}", "func (in *SetCanaryScale) DeepCopy() *SetCanaryScale {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SetCanaryScale)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o ElastigroupScheduledTaskOutput) ScaleTargetCapacity() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupScheduledTask) *string { return v.ScaleTargetCapacity }).(pulumi.StringPtrOutput)\n}", "func (c *CanaryDeployer) Scale(cd *flaggerv1.Canary, replicas int32) error {\n\ttargetName := cd.Spec.TargetRef.Name\n\tdep, err := c.kubeClient.AppsV1().Deployments(cd.Namespace).Get(targetName, metav1.GetOptions{})\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn fmt.Errorf(\"deployment %s.%s not found\", targetName, cd.Namespace)\n\t\t}\n\t\treturn fmt.Errorf(\"deployment %s.%s query error %v\", targetName, cd.Namespace, err)\n\t}\n\n\tdepCopy := dep.DeepCopy()\n\tdepCopy.Spec.Replicas = int32p(replicas)\n\n\t_, err = c.kubeClient.AppsV1().Deployments(dep.Namespace).Update(depCopy)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"scaling %s.%s to %v failed: %v\", depCopy.GetName(), depCopy.Namespace, replicas, err)\n\t}\n\treturn nil\n}", "func (this *Transformable) SetScale(scale Vector2f) {\n\tC.sfTransformable_setScale(this.cptr, scale.toC())\n}", "func (o HorizontalPodAutoscalerSpecPtrOutput) ScaleTargetRef() CrossVersionObjectReferencePtrOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerSpec) *CrossVersionObjectReference {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.ScaleTargetRef\n\t}).(CrossVersionObjectReferencePtrOutput)\n}", "func (o HorizontalPodAutoscalerSpecPtrOutput) ScaleTargetRef() CrossVersionObjectReferencePtrOutput {\n\treturn o.ApplyT(func(v *HorizontalPodAutoscalerSpec) *CrossVersionObjectReference {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.ScaleTargetRef\n\t}).(CrossVersionObjectReferencePtrOutput)\n}", "func (s *Surface) Scale(x, y float64) {\n\ts.Ctx.Call(\"scale\", x, y)\n}", "func (k *kubectlContext) Scale(resource string, scale uint) error {\n\tout, err := k.do(\"scale\", fmt.Sprintf(\"--replicas=%d\", scale), resource)\n\tk.t.Log(string(out))\n\treturn err\n}", "func (p Point) Scale(f float64) Point {\n\treturn Point{p[0] * f, p[1] * f, p[2] * f}\n}", "func Scale(value float64) *SimpleElement { return newSEFloat(\"scale\", value) }", "func (in *ScalableTargetSpec) DeepCopy() *ScalableTargetSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalableTargetSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (m Matrix) Scale(scale vec32.Vector) Matrix {\n\treturn Mul(m, Matrix{\n\t\t{scale[0], 0, 0, 0},\n\t\t{0, scale[1], 0, 0},\n\t\t{0, 0, scale[2], 0},\n\t\t{0, 0, 0, 1},\n\t})\n}", "func (v *Vertex) Scale(l float64) {\n\tv.x *= l\n\tv.y *= l\n}", "func (p *P1D) Scale(factor float64) {\n\tp.bng.scaleW(factor)\n}", "func (p *Proc) Scale(x, y float64) {\n\tp.stk.scale(x, y)\n}", "func (in *ScalableTarget_SDK) DeepCopy() *ScalableTarget_SDK {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalableTarget_SDK)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (g *GameObject) SetScale(scale float64) {\r\n\tg.Hitbox.maxX *= scale / g.Scale\r\n\tg.Hitbox.maxY *= scale / g.Scale\r\n\tg.Scale = scale\r\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * 1\n\tv.Y = v.Y * 1\n}", "func (w *windowImpl) Scale(dr image.Rectangle, src screen.Texture, sr image.Rectangle, op draw.Op, opts *screen.DrawOptions) {\n\tpanic(\"not implemented\") // TODO: Implement\n}", "func (a *Workload) Scale(ctx context.Context, instances int32) error {\n\treturn retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\t// Retrieve the latest version of Deployment before attempting update\n\t\t// RetryOnConflict uses exponential backoff to avoid exhausting the apiserver\n\t\tdeployment, err := a.Deployment(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdeployment.Spec.Replicas = &instances\n\n\t\t_, err = a.cluster.Kubectl.AppsV1().Deployments(a.app.Org).Update(\n\t\t\tctx, deployment, metav1.UpdateOptions{})\n\n\t\treturn err\n\t})\n}", "func (in Targets) DeepCopy() Targets {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Targets)\n\tin.DeepCopyInto(out)\n\treturn *out\n}", "func (m *Matrix3) Scale(s float64) {\n\tfor i, x := range m {\n\t\tm[i] = x * s\n\t}\n}", "func (p *Plane) Scale(scaleVec mgl32.Vec3) {\n\tp.model.Scale = scaleVec\n\tp.centroid = CalculateCentroid(p.vertexValues.Vertices, p.model.Scale)\n\tp.boundingBox = ScaleBoundingBox(p.boundingBox, scaleVec)\n}", "func (o ArgoCDSpecServerAutoscaleHpaPtrOutput) ScaleTargetRef() ArgoCDSpecServerAutoscaleHpaScaleTargetRefPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecServerAutoscaleHpa) *ArgoCDSpecServerAutoscaleHpaScaleTargetRef {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.ScaleTargetRef\n\t}).(ArgoCDSpecServerAutoscaleHpaScaleTargetRefPtrOutput)\n}", "func (t *Tree) Scale(s float32) {\n\tif t.Leaf != nil {\n\t\tfor i, x := range t.Leaf.OutputDelta {\n\t\t\tt.Leaf.OutputDelta[i] = x * s\n\t\t}\n\t} else {\n\t\tt.Branch.FalseBranch.Scale(s)\n\t\tt.Branch.TrueBranch.Scale(s)\n\t}\n}", "func (c *LinehaulCostComputation) Scale(factor float64) {\n\tc.BaseLinehaul = c.BaseLinehaul.MultiplyFloat64(factor)\n\tc.OriginLinehaulFactor = c.OriginLinehaulFactor.MultiplyFloat64(factor)\n\tc.DestinationLinehaulFactor = c.DestinationLinehaulFactor.MultiplyFloat64(factor)\n\tc.ShorthaulCharge = c.ShorthaulCharge.MultiplyFloat64(factor)\n\tc.LinehaulChargeTotal = c.LinehaulChargeTotal.MultiplyFloat64(factor)\n}", "func (in *ManagedMachinePoolScaling) DeepCopy() *ManagedMachinePoolScaling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ManagedMachinePoolScaling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o ContainerOutput) Scale() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *Container) pulumi.IntOutput { return v.Scale }).(pulumi.IntOutput)\n}", "func Scale(v *Vertex, f float64) {\n\tv.X *= f\n\tv.Y *= f\n}", "func (in *ScaleStatus) DeepCopy() *ScaleStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c2d *C2DMatrix) Scale(xScale, yScale float64) {\n\tvar mat Matrix\n\n\tmat.m11 = xScale\n\tmat.m12 = 0\n\tmat.m13 = 0\n\n\tmat.m21 = 0\n\tmat.m22 = yScale\n\tmat.m23 = 0\n\n\tmat.m31 = 0\n\tmat.m32 = 0\n\tmat.m33 = 1\n\n\t//and multiply\n\tc2d.MatrixMultiply(mat)\n}", "func (c *ProcessClient) Scale(ctx context.Context, guid string, scale *resource.ProcessScale) (*resource.Process, error) {\n\tvar process resource.Process\n\t_, err := c.client.post(ctx, path.Format(\"/v3/processes/%s/actions/scale\", guid), scale, &process)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &process, nil\n}", "func (canvas *Canvas) Scale(x, y float32) {\n\twriteCommand(canvas.contents, \"cm\", x, 0, 0, y, 0, 0)\n}", "func Scale(v *Vertex, f float64) {\n\tv.x *= f\n\tv.y *= f\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X *= f\n\tv.Y *= f\n}", "func (dw *DrawingWand) Scale(x, y float64) {\n\tC.MagickDrawScale(dw.dw, C.double(x), C.double(y))\n}", "func (a *ReplaySnapshotArgs) SetScale(scale float64) *ReplaySnapshotArgs {\n\ta.Scale = &scale\n\treturn a\n}", "func (v *Vector) ScaleTo(s float64) {\n\tv.X = s * v.X\n\tv.Y = s * v.Y\n\tv.Z = s * v.Z\n}", "func (m *Manager) Scale(shardIDs []int, shardCount int) (err error) {\n\tsg, err := NewShardGroup(m, shardIDs, shardCount)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = sg.Start()\n\treturn\n}", "func (aip *AzureInfrastructureProvider) Scale(request entities.ScaleRequest) (entities.InfrastructureOperation, derrors.Error) {\n\treturn NewScalerOperation(aip.credentials, request, aip.config)\n}", "func (ki *KernelInfo) Scale(scale float64, normalizeType KernelNormalizeType) {\n\tC.ScaleKernelInfo(ki.info, C.double(scale), C.GeometryFlags(normalizeType))\n\truntime.KeepAlive(ki)\n}", "func (s *Service) Scale(ctx context.Context, scale int, timeout int) error {\n\tif s.specificiesHostPort() {\n\t\tlogrus.Warnf(\"The \\\"%s\\\" service specifies a port on the host. If multiple containers for this service are created on a single host, the port will clash.\", s.Name())\n\t}\n\n\tcontainers, err := s.collectContainers(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(containers) > scale {\n\t\tfoundCount := 0\n\t\tfor _, c := range containers {\n\t\t\tfoundCount++\n\t\t\tif foundCount > scale {\n\t\t\t\ttimeout = s.stopTimeout(timeout)\n\t\t\t\tif err := c.Stop(ctx, timeout); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// FIXME(vdemeester) remove volume in scale by default ?\n\t\t\t\tif err := c.Remove(ctx, false); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(containers) < scale {\n\t\terr := s.ensureImageExists(ctx, false, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err = s.constructContainers(ctx, scale); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn s.up(ctx, \"\", false, options.Up{})\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}", "func (v *Vertex) Scale(f float64) {\n\tv.X = v.X * f\n\tv.Y = v.Y * f\n}", "func (v Vec3) Scale(s float64) Vec3 {\n\treturn Vec3{v[0] * s, v[1] * s, v[2] * s}\n}", "func (v *Vertex) Scale(f float64) {\n\tv.x = v.x * f\n\tv.y = v.y * f\n}", "func (v *Vertex) Scale(f float64) {\r\n\tv.X = v.X * f\r\n\tv.Y = v.Y * f\r\n}", "func (this *RectangleShape) Scale(factor Vector2f) {\n\tC.sfRectangleShape_scale(this.cptr, factor.toC())\n}", "func (self Text) Scale(x, y float32) {\n\tv := C.sfVector2f{C.float(x), C.float(y)}\n\tC.sfText_scale(self.Cref, v)\n}", "func (v *Vertex) Scale(f float64) {\n v.X = v.X * f\n v.Y = v.Y * f\n}", "func Scale(f float64, d Number) Number {\n\treturn Number{Real: f * d.Real, E1mag: f * d.E1mag, E2mag: f * d.E2mag, E1E2mag: f * d.E1E2mag}\n}", "func (v *Vertex) Scale(f float64) {\n v.X = v.X * f\n v.Y = v.Y * f\n}", "func (auto *Autoscaler) scaleScalerTargetRef(desiredInstance uint, scaler *commtypes.BcsAutoscaler) error {\n\ttargetRef := scaler.Spec.ScaleTargetRef\n\n\tvar err error\n\tswitch targetRef.Kind {\n\tcase commtypes.AutoscalerTargetRefDeployment:\n\t\terr = auto.scalerController.ScaleDeployment(targetRef.Namespace, targetRef.Name, desiredInstance)\n\n\tcase commtypes.AutoscalerTargetRefApplication:\n\t\terr = auto.scalerController.ScaleApplication(targetRef.Namespace, targetRef.Name, desiredInstance)\n\t}\n\n\treturn err\n}", "func (t *Transform) GetScale() *Vector {\n\treturn t.Scale\n}", "func (dev *pwm_context) Scale(value int) error {\n\tif dev.period == -1 {\n\t\tif err := dev.ReadPeriod(); err != nil {\n\t\t\treturn fmt.Errorf(\"pwm: error running Scale: %s\", err)\n\t\t}\n\t}\n\n\tduty := (float64(value) - dev.min) / dev.span\n\tfmt.Printf(\"pwm: Scaling pin[%d] from value: %d to duty: %f\\n\", dev.pin, value, duty)\n\treturn dev.WriteDuty(int(float64(dev.period) * duty))\n}", "func (xf *Transform) SetScale(scale float32) {\n\txf.Scale = mgl32.Vec2{scale, scale}\n}", "func (in *ScalableTargetStatus) DeepCopy() *ScalableTargetStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalableTargetStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (wv *Spectrum) Scale(s float32) {\n\twv.C[0] *= s\n\twv.C[1] *= s\n\twv.C[2] *= s\n\twv.C[3] *= s\n}", "func Scale(p point, factor int) point {\n\treturn point{p.x * factor, p.y * factor, p.z * factor}\n}", "func (b *IconButton) Scale(scale float32) *IconButton {\n\tb.size = b.th.TextSize.Scale(scale * 0.72)\n\treturn b\n}", "func (v Vector) Scale(c float64) Vector {\n\tfor i, x := range v {\n\t\tv[i] = x * c\n\t}\n\treturn v\n}", "func Scale(s float64) Matrix {\n\treturn Matrix{s, 0, 0, s, 0, 0}\n}", "func (o ContainerServiceOutput) Scale() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *ContainerService) pulumi.IntOutput { return v.Scale }).(pulumi.IntOutput)\n}", "func TestScale(t *testing.T) {\n\tvar i, j uint\n\tfor i = 0; i < 100; i++ {\n\t\ta := makeRandomVector(i)\n\t\tx := rand.ExpFloat64()\n\t\tb := Scale(a, x)\n\n\t\tfor j = 0; j < i; j++ {\n\t\t\tif b.dims[j] != a.dims[j]*x {\n\t\t\t\tt.Error(\"Scalar Multiplication failed, \",\n\t\t\t\t\t\"didn't get expected values.\")\n\t\t\t\tt.Logf(\"%f * %f != %f\", a.dims[j], x, b.dims[j])\n\t\t\t}\n\t\t}\n\n\t\t// Test in-place scalar multiplication\n\t\tb = a.Copy()\n\t\tb.Scale(x)\n\n\t\tfor j = 0; j < i; j++ {\n\t\t\tif b.dims[j] != a.dims[j]*x {\n\t\t\t\tt.Error(\"In-place Scalar Multiplication failed, \",\n\t\t\t\t\t\"didn't get expected values.\")\n\t\t\t\tt.Logf(\"%f * %f != %f\", a.dims[j], x, b.dims[j])\n\t\t\t}\n\t\t}\n\t}\n}" ]
[ "0.76370376", "0.67633396", "0.62799335", "0.619151", "0.6033552", "0.6033552", "0.59817666", "0.5977553", "0.5958769", "0.5904952", "0.58848196", "0.5880546", "0.58670145", "0.5864372", "0.5860537", "0.58537394", "0.58474916", "0.5838018", "0.5838018", "0.581858", "0.57586914", "0.5754123", "0.5752271", "0.57396567", "0.5722573", "0.5700078", "0.5695789", "0.5683854", "0.5667518", "0.56472635", "0.56472635", "0.5629776", "0.5607624", "0.5580664", "0.55200195", "0.5518552", "0.5518552", "0.5510044", "0.55061644", "0.5489746", "0.5487856", "0.5466632", "0.54475456", "0.5432742", "0.5424253", "0.5422268", "0.54146767", "0.5404326", "0.53996104", "0.5394163", "0.5391897", "0.53731906", "0.5355917", "0.5344168", "0.5337772", "0.5332615", "0.5310572", "0.5304799", "0.53047043", "0.5292223", "0.5272121", "0.5270699", "0.52652985", "0.526467", "0.52638865", "0.52526534", "0.52436936", "0.5220361", "0.52165574", "0.5197337", "0.51908517", "0.51814145", "0.51808006", "0.517906", "0.517906", "0.517906", "0.517906", "0.517906", "0.517906", "0.517906", "0.51657933", "0.51651967", "0.5154451", "0.5141216", "0.5140734", "0.5139211", "0.5113194", "0.51068604", "0.5103148", "0.5097859", "0.50967586", "0.5094036", "0.5069006", "0.50597733", "0.5057474", "0.5056787", "0.5048073", "0.5047808", "0.50423855", "0.5028737" ]
0.8381954
0
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be nonnil.
func (in *ScheduledPodScaler) DeepCopyInto(out *ScheduledPodScaler) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Status = in.Status }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RunInfo) DeepCopyInto(out *RunInfo) {\n\t*out = *r\n}", "func (in *Base) DeepCopyInto(out *Base) {\n\t*out = *in\n\treturn\n}", "func (in *ForkObject) DeepCopyInto(out *ForkObject) {\n\t*out = *in\n}", "func (in *TargetObjectInfo) DeepCopyInto(out *TargetObjectInfo) {\n\t*out = *in\n}", "func (in *DebugObjectInfo) DeepCopyInto(out *DebugObjectInfo) {\n\t*out = *in\n}", "func (in *Input) DeepCopyInto(out *Input) {\n\t*out = *in\n}", "func (u *SSN) DeepCopyInto(out *SSN) {\n\t*out = *u\n}", "func (in *ExistPvc) DeepCopyInto(out *ExistPvc) {\n\t*out = *in\n}", "func (in *DockerStep) DeepCopyInto(out *DockerStep) {\n\t*out = *in\n\tif in.Inline != nil {\n\t\tin, out := &in.Inline, &out.Inline\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tout.Auth = in.Auth\n\treturn\n}", "func (in *Container) DeepCopyInto(out *Container) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.Command != nil {\n\t\tin, out := &in.Command, &out.Command\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.LifeCycleScript != nil {\n\t\tin, out := &in.LifeCycleScript, &out.LifeCycleScript\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *RuntimeRef) DeepCopyInto(out *RuntimeRef) {\n\t*out = *in\n}", "func (in *Ibft2) DeepCopyInto(out *Ibft2) {\n\t*out = *in\n\treturn\n}", "func (in *TestResult) DeepCopyInto(out *TestResult) {\n\t*out = *in\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *Haproxy) DeepCopyInto(out *Haproxy) {\n\t*out = *in\n\treturn\n}", "func (in *SSH) DeepCopyInto(out *SSH) {\n\t*out = *in\n\treturn\n}", "func (in *Runtime) DeepCopyInto(out *Runtime) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (b *Base64) DeepCopyInto(out *Base64) {\n\t*out = *b\n}", "func (in *EventDependencyTransformer) DeepCopyInto(out *EventDependencyTransformer) {\n\t*out = *in\n\treturn\n}", "func (in *StageOutput) DeepCopyInto(out *StageOutput) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Dependent) DeepCopyInto(out *Dependent) {\n\t*out = *in\n\treturn\n}", "func (in *GitFileGeneratorItem) DeepCopyInto(out *GitFileGeneratorItem) {\n\t*out = *in\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *AnsibleStep) DeepCopyInto(out *AnsibleStep) {\n\t*out = *in\n\treturn\n}", "func (in *Forks) DeepCopyInto(out *Forks) {\n\t*out = *in\n\tif in.DAO != nil {\n\t\tin, out := &in.DAO, &out.DAO\n\t\t*out = new(uint)\n\t\t**out = **in\n\t}\n}", "func (in *ContainerPort) DeepCopyInto(out *ContainerPort) {\n\t*out = *in\n}", "func (in *General) DeepCopyInto(out *General) {\n\t*out = *in\n\treturn\n}", "func (in *IsoContainer) DeepCopyInto(out *IsoContainer) {\n\t*out = *in\n}", "func (in *Git) DeepCopyInto(out *Git) {\n\t*out = *in\n\treturn\n}", "func (in *ConfigFile) DeepCopyInto(out *ConfigFile) {\n\t*out = *in\n}", "func (in *BackupProgress) DeepCopyInto(out *BackupProgress) {\n\t*out = *in\n}", "func (in *DataDisk) DeepCopyInto(out *DataDisk) {\n\t*out = *in\n}", "func (in *PhaseStep) DeepCopyInto(out *PhaseStep) {\n\t*out = *in\n}", "func (u *MAC) DeepCopyInto(out *MAC) {\n\t*out = *u\n}", "func (in *Variable) DeepCopyInto(out *Variable) {\n\t*out = *in\n}", "func (in *RestoreProgress) DeepCopyInto(out *RestoreProgress) {\n\t*out = *in\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *NamespacedObjectReference) DeepCopyInto(out *NamespacedObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Path) DeepCopyInto(out *Path) {\n\t*out = *in\n\treturn\n}", "func (in *GitDirectoryGeneratorItem) DeepCopyInto(out *GitDirectoryGeneratorItem) {\n\t*out = *in\n}", "func (in *NamePath) DeepCopyInto(out *NamePath) {\n\t*out = *in\n\treturn\n}", "func (in *ConsoleCreateObj) DeepCopyInto(out *ConsoleCreateObj) {\n\t*out = *in\n}", "func (in *UsedPipelineRun) DeepCopyInto(out *UsedPipelineRun) {\n\t*out = *in\n}", "func (in *BuildTemplate) DeepCopyInto(out *BuildTemplate) {\n\t*out = *in\n\tif in.Cmd != nil {\n\t\tin, out := &in.Cmd, &out.Cmd\n\t\t*out = make([]BuildTemplateStep, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n}", "func (in *ObjectInfo) DeepCopyInto(out *ObjectInfo) {\n\t*out = *in\n\tout.GroupVersionKind = in.GroupVersionKind\n\treturn\n}", "func (in *Files) DeepCopyInto(out *Files) {\n\t*out = *in\n}", "func (in *Source) DeepCopyInto(out *Source) {\n\t*out = *in\n\tif in.Dependencies != nil {\n\t\tin, out := &in.Dependencies, &out.Dependencies\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MavenRepositories != nil {\n\t\tin, out := &in.MavenRepositories, &out.MavenRepositories\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\treturn\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *StackBuild) DeepCopyInto(out *StackBuild) {\n\t*out = *in\n\treturn\n}", "func (in *BuildTaskRef) DeepCopyInto(out *BuildTaskRef) {\n\t*out = *in\n\treturn\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *PathInfo) DeepCopyInto(out *PathInfo) {\n\t*out = *in\n}", "func (in *PoA) DeepCopyInto(out *PoA) {\n\t*out = *in\n}", "func (in *Section) DeepCopyInto(out *Section) {\n\t*out = *in\n\tif in.SecretRefs != nil {\n\t\tin, out := &in.SecretRefs, &out.SecretRefs\n\t\t*out = make([]SecretReference, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Files != nil {\n\t\tin, out := &in.Files, &out.Files\n\t\t*out = make([]FileMount, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n}", "func (in *DNSSelection) DeepCopyInto(out *DNSSelection) {\n\t*out = *in\n\tif in.Include != nil {\n\t\tin, out := &in.Include, &out.Include\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Exclude != nil {\n\t\tin, out := &in.Exclude, &out.Exclude\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ReleaseVersion) DeepCopyInto(out *ReleaseVersion) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Command) DeepCopyInto(out *Command) {\n\t*out = *in\n\tif in.Flags != nil {\n\t\tin, out := &in.Flags, &out.Flags\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Value != nil {\n\t\tin, out := &in.Value, &out.Value\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *PathRule) DeepCopyInto(out *PathRule) {\n\t*out = *in\n\treturn\n}", "func (in *DockerLifecycleData) DeepCopyInto(out *DockerLifecycleData) {\n\t*out = *in\n}", "func (in *RunScriptStepConfig) DeepCopyInto(out *RunScriptStepConfig) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Checksum) DeepCopyInto(out *Checksum) {\n\t*out = *in\n}", "func (in *DomainNameOutput) DeepCopyInto(out *DomainNameOutput) {\n\t*out = *in\n}", "func (in *InterfaceStruct) DeepCopyInto(out *InterfaceStruct) {\n\t*out = *in\n\tif in.val != nil {\n\t\tin, out := &in.val, &out.val\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Ref) DeepCopyInto(out *Ref) {\n\t*out = *in\n}", "func (in *MemorySpec) DeepCopyInto(out *MemorySpec) {\n\t*out = *in\n}", "func (in *BuildJenkinsInfo) DeepCopyInto(out *BuildJenkinsInfo) {\n\t*out = *in\n\treturn\n}", "func (in *VirtualDatabaseBuildObject) DeepCopyInto(out *VirtualDatabaseBuildObject) {\n\t*out = *in\n\tif in.Incremental != nil {\n\t\tin, out := &in.Incremental, &out.Incremental\n\t\t*out = new(bool)\n\t\t**out = **in\n\t}\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]v1.EnvVar, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\tout.Git = in.Git\n\tin.Source.DeepCopyInto(&out.Source)\n\tif in.Webhooks != nil {\n\t\tin, out := &in.Webhooks, &out.Webhooks\n\t\t*out = make([]WebhookSecret, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *MaintenanceInfo) DeepCopyInto(out *MaintenanceInfo) {\n\t*out = *in\n\treturn\n}", "func (in *KopsNode) DeepCopyInto(out *KopsNode) {\n\t*out = *in\n\treturn\n}", "func (in *FalconAPI) DeepCopyInto(out *FalconAPI) {\n\t*out = *in\n}", "func (in *EBS) DeepCopyInto(out *EBS) {\n\t*out = *in\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n\treturn\n}", "func (in *Empty) DeepCopyInto(out *Empty) {\n\t*out = *in\n\tout.XXX_NoUnkeyedLiteral = in.XXX_NoUnkeyedLiteral\n\tif in.XXX_unrecognized != nil {\n\t\tin, out := &in.XXX_unrecognized, &out.XXX_unrecognized\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ComponentDistGit) DeepCopyInto(out *ComponentDistGit) {\n\t*out = *in\n\treturn\n}", "func (in *Memory) DeepCopyInto(out *Memory) {\n\t*out = *in\n\tout.Required = in.Required.DeepCopy()\n}", "func (in *Persistence) DeepCopyInto(out *Persistence) {\n\t*out = *in\n\tout.Size = in.Size.DeepCopy()\n\treturn\n}", "func (in *ManagedDisk) DeepCopyInto(out *ManagedDisk) {\n\t*out = *in\n}", "func (e *Email) DeepCopyInto(out *Email) {\n\t*out = *e\n}", "func (in *ImageInfo) DeepCopyInto(out *ImageInfo) {\n\t*out = *in\n}", "func (in *ShootRef) DeepCopyInto(out *ShootRef) {\n\t*out = *in\n}", "func (in *N3000Fpga) DeepCopyInto(out *N3000Fpga) {\n\t*out = *in\n}", "func (in *NetflowType) DeepCopyInto(out *NetflowType) {\n\t*out = *in\n\treturn\n}", "func (in *BuiltInAdapter) DeepCopyInto(out *BuiltInAdapter) {\n\t*out = *in\n}", "func (in *Node) DeepCopyInto(out *Node) {\n\t*out = *in\n\tif in.FailStatus != nil {\n\t\tin, out := &in.FailStatus, &out.FailStatus\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MigratingSlots != nil {\n\t\tin, out := &in.MigratingSlots, &out.MigratingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.ImportingSlots != nil {\n\t\tin, out := &in.ImportingSlots, &out.ImportingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n}", "func (in *CPUSpec) DeepCopyInto(out *CPUSpec) {\n\t*out = *in\n}", "func (in *LoopState) DeepCopyInto(out *LoopState) {\n\t*out = *in\n}" ]
[ "0.8215289", "0.81280124", "0.81039286", "0.80862963", "0.8083811", "0.80673146", "0.8064545", "0.8026454", "0.8012046", "0.7996313", "0.799204", "0.79887754", "0.7987097", "0.7986994", "0.7986994", "0.79854053", "0.7975989", "0.7972486", "0.79695636", "0.79695636", "0.79695636", "0.7967528", "0.79624444", "0.7961954", "0.7945754", "0.7945754", "0.7944541", "0.79428566", "0.7942668", "0.7942668", "0.7940451", "0.793851", "0.7936731", "0.79294837", "0.79252166", "0.7915377", "0.7911627", "0.7911138", "0.7909384", "0.790913", "0.7908773", "0.7905649", "0.79050326", "0.7904594", "0.7904594", "0.7904235", "0.79036915", "0.79020816", "0.78988886", "0.78977424", "0.7891376", "0.7891024", "0.7889831", "0.78890276", "0.7887135", "0.788637", "0.7885264", "0.7885264", "0.7884786", "0.7880785", "0.78745943", "0.78745943", "0.78745407", "0.78734446", "0.78724426", "0.78713626", "0.78713554", "0.78652424", "0.7863321", "0.7863321", "0.7863321", "0.7863293", "0.7862628", "0.7860664", "0.7858556", "0.785785", "0.78571486", "0.7851332", "0.78453225", "0.78448987", "0.78415996", "0.7837483", "0.7837037", "0.7836443", "0.78351796", "0.78329664", "0.7831094", "0.7829445", "0.7826582", "0.7824499", "0.78242797", "0.78227437", "0.78192484", "0.7818843", "0.78128535", "0.7812535", "0.78111476", "0.78111106", "0.781107", "0.78093034", "0.7808775" ]
0.0
-1
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ScheduledPodScaler.
func (in *ScheduledPodScaler) DeepCopy() *ScheduledPodScaler { if in == nil { return nil } out := new(ScheduledPodScaler) in.DeepCopyInto(out) return out }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in *ScheduledPodScalerSpec) DeepCopy() *ScheduledPodScalerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScalerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScaler) DeepCopy() *SchedulingScaler {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScaler)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerList) DeepCopy() *ScheduledPodScalerList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScalerList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerStatus) DeepCopy() *ScheduledPodScalerStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScalerStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerSchedule) DeepCopy() *SchedulingScalerSchedule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerSchedule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerStatus) DeepCopy() *SchedulingScalerStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerList) DeepCopy() *SchedulingScalerList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingPolicy) DeepCopy() *SchedulingPolicy {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingPolicy)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *HorizontalPodAutoscaling) DeepCopy() *HorizontalPodAutoscaling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HorizontalPodAutoscaling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *ScheduledScalerController) scheduledScalerUpdate(old, new interface{}) {\n\toldScheduledScaler := old.(*scalingv1alpha1.ScheduledScaler)\n\tnewScheduledScaler := new.(*scalingv1alpha1.ScheduledScaler)\n\tif reflect.DeepEqual(oldScheduledScaler.Spec, newScheduledScaler.Spec) {\n\t\treturn\n\t}\n\tc.scheduledScalerDelete(old)\n\tc.scheduledScalerAdd(new)\n}", "func NewScheduledScalerController(\n\tinformerFactory informers.SharedInformerFactory,\n\trestdevClient clientset.Interface,\n\tkubeClient *kubernetes.Clientset,\n) *ScheduledScalerController {\n\tscheduledScalerInformer := informerFactory.Scaling().V1alpha1().ScheduledScalers()\n\tscheduledScalersLister := scheduledScalerInformer.Lister()\n\tvar scheduledScalerTargets []ScheduledScalerTarget\n\n\tc := &ScheduledScalerController{\n\t\tinformerFactory: informerFactory,\n\t\trestdevClient: restdevClient,\n\t\tkubeClient: kubeClient,\n\t\tscheduledScalersLister: scheduledScalersLister,\n\t\tscheduledScalersSynced: scheduledScalerInformer.Informer().HasSynced,\n\t\tscheduledScalerTargets: scheduledScalerTargets,\n\t}\n\tscheduledScalerInformer.Informer().AddEventHandler(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: c.scheduledScalerAdd,\n\t\t\tUpdateFunc: c.scheduledScalerUpdate,\n\t\t\tDeleteFunc: c.scheduledScalerDelete,\n\t\t},\n\t)\n\treturn c\n}", "func (in *SchedulingScalerSpec) DeepCopy() *SchedulingScalerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *ScheduledScalerController) scheduledScalerAdd(obj interface{}) {\n\tscheduledScaler := obj.(*scalingv1alpha1.ScheduledScaler)\n\tif scheduledScaler.Spec.Target.Kind == \"HorizontalPodAutoscaler\" {\n\t\tc.scheduledScalerHpaCronAdd(obj)\n\t} else if scheduledScaler.Spec.Target.Kind == \"InstanceGroup\" {\n\t\tc.scheduledScalerIgCronAdd(obj)\n\t}\n}", "func (in *ScalingPolicy) DeepCopy() *ScalingPolicy {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalingPolicy)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AutoScheduling) DeepCopy() *AutoScheduling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AutoScheduling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewPodScheduling(ctx *pulumi.Context,\n\tname string, args *PodSchedulingArgs, opts ...pulumi.ResourceOption) (*PodScheduling, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Spec == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Spec'\")\n\t}\n\targs.ApiVersion = pulumi.StringPtr(\"resource.k8s.io/v1alpha1\")\n\targs.Kind = pulumi.StringPtr(\"PodScheduling\")\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource PodScheduling\n\terr := ctx.RegisterResource(\"kubernetes:resource.k8s.io/v1alpha1:PodScheduling\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func podScheduledState() *corev1.Pod {\n\treturn mustLoadPodRecording(podStatePath(\"scheduled\"))\n}", "func (in *SchedulingPolicyStatus) DeepCopy() *SchedulingPolicyStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingPolicyStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (k *kubeScheduler) Schedule(pod api.Pod, unused algorithm.MinionLister) (string, error) {\n\tlog.Infof(\"Try to schedule pod %v\\n\", pod.Name)\n\tctx := api.WithNamespace(api.NewDefaultContext(), pod.Namespace)\n\n\t// default upstream scheduler passes pod.Name as binding.PodID\n\tpodKey, err := makePodKey(ctx, pod.Name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tk.api.Lock()\n\tdefer k.api.Unlock()\n\n\tif taskID, ok := k.api.taskForPod(podKey); !ok {\n\t\t// There's a bit of a potential race here, a pod could have been yielded() but\n\t\t// and then before we get *here* it could be deleted. We use meta to index the pod\n\t\t// in the store since that's what k8s client/cache/reflector does.\n\t\tmeta, err := meta.Accessor(&pod)\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"aborting Schedule, unable to understand pod object %+v\", &pod)\n\t\t\treturn \"\", noSuchPodErr\n\t\t}\n\t\tif deleted := k.podStore.Poll(meta.Name(), queue.DELETE_EVENT); deleted {\n\t\t\t// avoid scheduling a pod that's been deleted between yieldPod() and Schedule()\n\t\t\tlog.Infof(\"aborting Schedule, pod has been deleted %+v\", &pod)\n\t\t\treturn \"\", noSuchPodErr\n\t\t}\n\t\treturn k.doSchedule(k.api.registerPodTask(k.api.createPodTask(ctx, &pod)))\n\t} else {\n\t\tswitch task, state := k.api.getTask(taskID); state {\n\t\tcase statePending:\n\t\t\tif task.launched {\n\t\t\t\treturn \"\", fmt.Errorf(\"task %s has already been launched, aborting schedule\", taskID)\n\t\t\t} else {\n\t\t\t\treturn k.doSchedule(task, nil)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"task %s is not pending, nothing to schedule\", taskID)\n\t\t}\n\t}\n}", "func (in *VerticalPodAutoscaling) DeepCopy() *VerticalPodAutoscaling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(VerticalPodAutoscaling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ElasticsearchDataSetScaling) DeepCopy() *ElasticsearchDataSetScaling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ElasticsearchDataSetScaling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RolloutPause) DeepCopy() *RolloutPause {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RolloutPause)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (k *KubernetesScheduler) Schedule(pod api.Pod, unused algorithm.MinionLister) (string, error) {\n\tlog.Infof(\"Try to schedule pod %v\\n\", pod.ID)\n\n\tk.Lock()\n\tdefer k.Unlock()\n\n\tif taskID, ok := k.podToTask[pod.ID]; !ok {\n\t\treturn \"\", fmt.Errorf(\"Pod %s cannot be resolved to a task\", pod.ID)\n\t} else {\n\t\tif task, found := k.pendingTasks[taskID]; !found {\n\t\t\treturn \"\", fmt.Errorf(\"Task %s is not pending, nothing to schedule\", taskID)\n\t\t} else {\n\t\t\treturn k.doSchedule(task)\n\t\t}\n\t}\n}", "func (in *ScheduledSparkApplication) DeepCopy() *ScheduledSparkApplication {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledSparkApplication)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingPolicyList) DeepCopy() *SchedulingPolicyList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingPolicyList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WatermarkHorizontalPodAutoscaler) DeepCopy() *WatermarkHorizontalPodAutoscaler {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WatermarkHorizontalPodAutoscaler)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Pod) DeepCopy() *Pod {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Pod)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Pod) DeepCopy() *Pod {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Pod)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *Pod) DeepCopy() *Pod {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Pod)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScalingPolicyStatus) DeepCopy() *ScalingPolicyStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalingPolicyStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o AutoscalingPolicyPtrOutput) ScalingSchedules() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *AutoscalingPolicy) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScalingSchedules\n\t}).(pulumi.StringMapOutput)\n}", "func (in *ScheduledAction) DeepCopy() *ScheduledAction {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledAction)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScaler) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ScheduledPodScalerList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (o BackendOutput) CapacityScaler() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v Backend) *float64 { return v.CapacityScaler }).(pulumi.Float64PtrOutput)\n}", "func (in *ManagedMachinePoolScaling) DeepCopy() *ManagedMachinePoolScaling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ManagedMachinePoolScaling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o AutoscalingPolicyOutput) ScalingSchedules() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v AutoscalingPolicy) map[string]string { return v.ScalingSchedules }).(pulumi.StringMapOutput)\n}", "func (o AutoscalingPolicyResponsePtrOutput) ScalingSchedules() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *AutoscalingPolicyResponse) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScalingSchedules\n\t}).(pulumi.StringMapOutput)\n}", "func (in *RollingUpdateDeployment) DeepCopy() *RollingUpdateDeployment {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RollingUpdateDeployment)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewPodSchedulingPolicy() *PodSchedulingPolicy {\n\treturn &PodSchedulingPolicy{\n\t\tPlacement: NewPodPlacement(),\n\t}\n}", "func (in *SchedulerEnhancer) DeepCopy() *SchedulerEnhancer {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulerEnhancer)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o ResourcePolicySnapshotSchedulePolicyOutput) Schedule() ResourcePolicySnapshotSchedulePolicySchedulePtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicySnapshotSchedulePolicy) *ResourcePolicySnapshotSchedulePolicySchedule {\n\t\treturn v.Schedule\n\t}).(ResourcePolicySnapshotSchedulePolicySchedulePtrOutput)\n}", "func (in *Autoscaling) DeepCopy() *Autoscaling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Autoscaling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o KubernetesClusterAutoScalerProfileOutput) NewPodScaleUpDelay() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterAutoScalerProfile) *string { return v.NewPodScaleUpDelay }).(pulumi.StringPtrOutput)\n}", "func (o AutoscalingPolicyResponseOutput) ScalingSchedules() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v AutoscalingPolicyResponse) map[string]string { return v.ScalingSchedules }).(pulumi.StringMapOutput)\n}", "func (in *ScaleRule) DeepCopy() *ScaleRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *ChaosPod) DeepCopy() *ChaosPod {\n\tif c == nil {\n\t\treturn nil\n\t}\n\tout := new(ChaosPod)\n\tc.DeepCopyInto(out)\n\treturn out\n}", "func (in *Schedule) DeepCopy() *Schedule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Schedule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (schedulerClient *Scheduler) AutoScale(ignoreTimeSchedule bool){\n\tcalender := InitAutoScalingCalender()\n\ttimeZone := os.Getenv(\"TIME_ZONE\")\n\tif timeZone == \"\"{\n\t\ttimeZone = \"America/Edmonton\"\n\t}\n\tloc ,_ := time.LoadLocation(timeZone)\n\tlog.Println(\"Time Zone is set to \",loc.String())\n\tfor {\n\t\t// Check if auto scaling on\n\t\tif AutoScaleByTime(calender,time.Now().In(loc)) || ignoreTimeSchedule {\n\t\t\t// Get the list of nodes in\tthe workerPool\n\t\t\tnodesList := schedulerClient.clusterClient.getWorkersNodesIP(schedulerClient.workerPool)\n\t\t\t// Get the list of pods with matching node selector\n\t\t\tnodeSelector := make(map[string]string)\n\t\t\tnodeSelector[\"pool\"] = schedulerClient.workerPool\n\t\t\tpodsList := schedulerClient.GetPodListWithLabels(schedulerClient.nameSpace,nodeSelector)\n\t\t\t// podList nil means there is error getting the pod\n\t\t\tif podsList == nil {\n\t\t\t\tlog.Println(\"Can't get pod list in the workerPool, skip this round\")\n\t\t\t\ttime.Sleep(schedulerClient.timeInterval * time.Second) //check after the interval\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// It is a bit abnormal to have 0 pod in the cluster, but it is not fatal\n\t\t\tif len(podsList) == 0 {\n\t\t\t\tlog.Println(\"Warning: podList is empty\")\n\t\t\t}\n\t\t\t// In practice, the worker pool can't be empty\n\t\t\tif len(nodesList) == 0 {\n\t\t\t\tlog.Println(\"worker pool should not have 0 nodes, skip this round\")\n\t\t\t\ttime.Sleep(schedulerClient.timeInterval * time.Second) //check after the interval\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t//Find unused nodes\n\t\t\tunusedNodes := FindUnusedNodes(podsList,nodesList)\n\t\t\t//Log message\n\t\t\tschedulerClient.DebugMessage(nodesList,podsList,unusedNodes)\n\t\t\t// Make decision to scale in or out the workerPool, using v1 algorithm\n\t\t\tscaleOut,scaleIn,err := SparkAlgoV1(len(nodesList),int(math.Max(0,float64(len(unusedNodes)-FindPendingNodes(podsList)))),schedulerClient.extraNode,\n\t\t\t\tschedulerClient.minNode,schedulerClient.maxNode)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\ttime.Sleep(schedulerClient.timeInterval * time.Second) //check after the interval\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif scaleIn{\n\t\t\t\tremoveIndex := rand.Intn(len(unusedNodes)) //randomly pick a node to drop\n\t\t\t\tschedulerClient.ScaleIn(schedulerClient.workerPool,unusedNodes[removeIndex]) //remove the pod\n\t\t\t}else if scaleOut{\n\t\t\t\tschedulerClient.ScaleOut(schedulerClient.workerPool)\n\t\t\t}\n\t\t}else{\n\t\t\t// Auto scaling mode off, turn on maximum number of allowed worker nodes\n\t\t\tlog.Println(\"Cluster AutoScaling is OFF, set the nodes number to max\")\n\t\t\tnodesList := schedulerClient.clusterClient.getWorkersNodesIP(schedulerClient.workerPool)\n\t\t\tif len(nodesList) == 0 {\n\t\t\t\tlog.Println(\"Warning: Node list is empty, skip this round\")\n\t\t\t\ttime.Sleep(schedulerClient.timeInterval * time.Second) //check after the interval\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(nodesList) < schedulerClient.maxNode {\n\t\t\t\tschedulerClient.ScaleOut(schedulerClient.workerPool)\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(schedulerClient.timeInterval * time.Second) //check after the interval\n\t}\n}", "func (o MrScalarTaskScalingUpPolicyOutput) Period() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingUpPolicy) *int { return v.Period }).(pulumi.IntPtrOutput)\n}", "func (o DrillSpecPodConfigOutput) PodScheduling() DrillSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfig) *DrillSpecPodConfigPodScheduling { return v.PodScheduling }).(DrillSpecPodConfigPodSchedulingPtrOutput)\n}", "func (in *ScalingPolicyList) DeepCopy() *ScalingPolicyList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalingPolicyList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o PgbenchSpecPodConfigOutput) PodScheduling() PgbenchSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfig) *PgbenchSpecPodConfigPodScheduling { return v.PodScheduling }).(PgbenchSpecPodConfigPodSchedulingPtrOutput)\n}", "func (o ResourcePolicySnapshotSchedulePolicyResponseOutput) Schedule() ResourcePolicySnapshotSchedulePolicyScheduleResponseOutput {\n\treturn o.ApplyT(func(v ResourcePolicySnapshotSchedulePolicyResponse) ResourcePolicySnapshotSchedulePolicyScheduleResponse {\n\t\treturn v.Schedule\n\t}).(ResourcePolicySnapshotSchedulePolicyScheduleResponseOutput)\n}", "func (in *RSSPodSpec) DeepCopy() *RSSPodSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RSSPodSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o IopingSpecPodConfigOutput) PodScheduling() IopingSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfig) *IopingSpecPodConfigPodScheduling { return v.PodScheduling }).(IopingSpecPodConfigPodSchedulingPtrOutput)\n}", "func (in *WatermarkHorizontalPodAutoscalerStatus) DeepCopy() *WatermarkHorizontalPodAutoscalerStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WatermarkHorizontalPodAutoscalerStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledSparkApplicationStatus) DeepCopy() *ScheduledSparkApplicationStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledSparkApplicationStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o ResourcePolicySnapshotSchedulePolicyPtrOutput) Schedule() ResourcePolicySnapshotSchedulePolicySchedulePtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicySnapshotSchedulePolicy) *ResourcePolicySnapshotSchedulePolicySchedule {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Schedule\n\t}).(ResourcePolicySnapshotSchedulePolicySchedulePtrOutput)\n}", "func (in *ScalingPolicySpec) DeepCopy() *ScalingPolicySpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalingPolicySpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o MrScalarCoreScalingUpPolicyOutput) Period() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v MrScalarCoreScalingUpPolicy) *int { return v.Period }).(pulumi.IntPtrOutput)\n}", "func (in *PreferredDuringSchedulingIgnoredDuringExecution) DeepCopy() *PreferredDuringSchedulingIgnoredDuringExecution {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PreferredDuringSchedulingIgnoredDuringExecution)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o MrScalarTaskScalingDownPolicyOutput) Period() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingDownPolicy) *int { return v.Period }).(pulumi.IntPtrOutput)\n}", "func (in *ScheduledPodScalerList) DeepCopyInto(out *ScheduledPodScalerList) {\n\t*out = *in\n\tout.TypeMeta = in.TypeMeta\n\tin.ListMeta.DeepCopyInto(&out.ListMeta)\n\tif in.Items != nil {\n\t\tin, out := &in.Items, &out.Items\n\t\t*out = make([]ScheduledPodScaler, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n}", "func (j *ScheduledJob) ScheduledRunTime() time.Time {\n\treturn j.scheduledTime\n}", "func (in *SchedulingPolicySpec) DeepCopy() *SchedulingPolicySpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingPolicySpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o KubernetesClusterAutoScalerProfilePtrOutput) NewPodScaleUpDelay() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterAutoScalerProfile) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.NewPodScaleUpDelay\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicySnapshotSchedulePolicyResponsePtrOutput) Schedule() ResourcePolicySnapshotSchedulePolicyScheduleResponsePtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicySnapshotSchedulePolicyResponse) *ResourcePolicySnapshotSchedulePolicyScheduleResponse {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Schedule\n\t}).(ResourcePolicySnapshotSchedulePolicyScheduleResponsePtrOutput)\n}", "func (p *pollerAutoScaler) Start() {\n\tlogger := p.logger.Sugar()\n\tp.wg.Add(1)\n\tgo func() {\n\t\tdefer p.wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-p.ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-time.After(p.cooldownTime):\n\t\t\t\tcurrentResource := autoscaler.ResourceUnit(p.sem.GetLimit())\n\t\t\t\tcurrentUsages, err := p.pollerUsageEstimator.Estimate()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Warnw(\"poller autoscaler skip due to estimator error\", \"error\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tproposedResource := p.recommender.Recommend(currentResource, currentUsages)\n\t\t\t\tlogger.Debugw(\"poller autoscaler recommendation\",\n\t\t\t\t\t\"currentUsage\", currentUsages,\n\t\t\t\t\t\"current\", uint64(currentResource),\n\t\t\t\t\t\"recommend\", uint64(proposedResource),\n\t\t\t\t\t\"isDryRun\", p.isDryRun)\n\t\t\t\tif !p.isDryRun {\n\t\t\t\t\tp.sem.SetLimit(int(proposedResource))\n\t\t\t\t}\n\t\t\t\tp.pollerUsageEstimator.Reset()\n\n\t\t\t\t// hooks\n\t\t\t\tfor i := range p.onAutoScale {\n\t\t\t\t\tp.onAutoScale[i]()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn\n}", "func (o ResourcePolicyInstanceSchedulePolicyScheduleOutput) Schedule() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicySchedule) *string { return v.Schedule }).(pulumi.StringPtrOutput)\n}", "func (o SysbenchSpecOutput) PodScheduling() SysbenchSpecPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v SysbenchSpec) *SysbenchSpecPodScheduling { return v.PodScheduling }).(SysbenchSpecPodSchedulingPtrOutput)\n}", "func (o QperfSpecClientConfigurationOutput) PodScheduling() QperfSpecClientConfigurationPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfiguration) *QperfSpecClientConfigurationPodScheduling {\n\t\treturn v.PodScheduling\n\t}).(QperfSpecClientConfigurationPodSchedulingPtrOutput)\n}", "func NewScheduledAction(ctx *pulumi.Context,\n\tname string, args *ScheduledActionArgs, opts ...pulumi.ResourceOpt) (*ScheduledAction, error) {\n\tif args == nil || args.ResourceId == nil {\n\t\treturn nil, errors.New(\"missing required argument 'ResourceId'\")\n\t}\n\tif args == nil || args.ServiceNamespace == nil {\n\t\treturn nil, errors.New(\"missing required argument 'ServiceNamespace'\")\n\t}\n\tinputs := make(map[string]interface{})\n\tif args == nil {\n\t\tinputs[\"endTime\"] = nil\n\t\tinputs[\"name\"] = nil\n\t\tinputs[\"resourceId\"] = nil\n\t\tinputs[\"scalableDimension\"] = nil\n\t\tinputs[\"scalableTargetAction\"] = nil\n\t\tinputs[\"schedule\"] = nil\n\t\tinputs[\"serviceNamespace\"] = nil\n\t\tinputs[\"startTime\"] = nil\n\t} else {\n\t\tinputs[\"endTime\"] = args.EndTime\n\t\tinputs[\"name\"] = args.Name\n\t\tinputs[\"resourceId\"] = args.ResourceId\n\t\tinputs[\"scalableDimension\"] = args.ScalableDimension\n\t\tinputs[\"scalableTargetAction\"] = args.ScalableTargetAction\n\t\tinputs[\"schedule\"] = args.Schedule\n\t\tinputs[\"serviceNamespace\"] = args.ServiceNamespace\n\t\tinputs[\"startTime\"] = args.StartTime\n\t}\n\tinputs[\"arn\"] = nil\n\ts, err := ctx.RegisterResource(\"aws:appautoscaling/scheduledAction:ScheduledAction\", name, true, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ScheduledAction{s: s}, nil\n}", "func (in *DeploymentStrategy_RollingUpdateDeployment) DeepCopy() *DeploymentStrategy_RollingUpdateDeployment {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DeploymentStrategy_RollingUpdateDeployment)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScalingPolicy_SDK) DeepCopy() *ScalingPolicy_SDK {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalingPolicy_SDK)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o DrillSpecPodConfigPtrOutput) PodScheduling() DrillSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v *DrillSpecPodConfig) *DrillSpecPodConfigPodScheduling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PodScheduling\n\t}).(DrillSpecPodConfigPodSchedulingPtrOutput)\n}", "func (o QperfSpecServerConfigurationOutput) PodScheduling() QperfSpecServerConfigurationPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfiguration) *QperfSpecServerConfigurationPodScheduling {\n\t\treturn v.PodScheduling\n\t}).(QperfSpecServerConfigurationPodSchedulingPtrOutput)\n}", "func (in *ScheduledPodScaler) DeepCopyInto(out *ScheduledPodScaler) {\n\t*out = *in\n\tout.TypeMeta = in.TypeMeta\n\tin.ObjectMeta.DeepCopyInto(&out.ObjectMeta)\n\tin.Spec.DeepCopyInto(&out.Spec)\n\tout.Status = in.Status\n}", "func (in *TaskScheduleStatus) DeepCopy() *TaskScheduleStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TaskScheduleStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScalingActivity) DeepCopy() *ScalingActivity {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalingActivity)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o PgbenchSpecPodConfigPtrOutput) PodScheduling() PgbenchSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v *PgbenchSpecPodConfig) *PgbenchSpecPodConfigPodScheduling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PodScheduling\n\t}).(PgbenchSpecPodConfigPodSchedulingPtrOutput)\n}", "func (o IopingSpecPodConfigPtrOutput) PodScheduling() IopingSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecPodConfig) *IopingSpecPodConfigPodScheduling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PodScheduling\n\t}).(IopingSpecPodConfigPodSchedulingPtrOutput)\n}", "func (o SysbenchSpecPtrOutput) PodScheduling() SysbenchSpecPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v *SysbenchSpec) *SysbenchSpecPodScheduling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PodScheduling\n\t}).(SysbenchSpecPodSchedulingPtrOutput)\n}", "func (o QperfSpecClientConfigurationPtrOutput) PodScheduling() QperfSpecClientConfigurationPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v *QperfSpecClientConfiguration) *QperfSpecClientConfigurationPodScheduling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PodScheduling\n\t}).(QperfSpecClientConfigurationPodSchedulingPtrOutput)\n}", "func (o MrScalarCoreScalingDownPolicyOutput) Period() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v MrScalarCoreScalingDownPolicy) *int { return v.Period }).(pulumi.IntPtrOutput)\n}", "func (in *PodAntiAffinity) DeepCopy() *PodAntiAffinity {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PodAntiAffinity)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ChaosPodStatus) DeepCopy() *ChaosPodStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ChaosPodStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduleStatus) DeepCopy() *ScheduleStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduleStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o BackendResponseOutput) CapacityScaler() pulumi.Float64Output {\n\treturn o.ApplyT(func(v BackendResponse) float64 { return v.CapacityScaler }).(pulumi.Float64Output)\n}", "func (o MrScalarTaskScalingUpPolicyOutput) Cooldown() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingUpPolicy) *int { return v.Cooldown }).(pulumi.IntPtrOutput)\n}", "func (in *ShadowPod) DeepCopy() *ShadowPod {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ShadowPod)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o ResourcePolicyInstanceSchedulePolicySchedulePtrOutput) Schedule() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyInstanceSchedulePolicySchedule) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Schedule\n\t}).(pulumi.StringPtrOutput)\n}", "func (o QperfSpecServerConfigurationPtrOutput) PodScheduling() QperfSpecServerConfigurationPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v *QperfSpecServerConfiguration) *QperfSpecServerConfigurationPodScheduling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PodScheduling\n\t}).(QperfSpecServerConfigurationPodSchedulingPtrOutput)\n}", "func (in *PodStatus) DeepCopy() *PodStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PodStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerSpec) DeepCopyInto(out *ScheduledPodScalerSpec) {\n\t*out = *in\n\tin.ScaleTarget.DeepCopyInto(&out.ScaleTarget)\n\tif in.ScaleRules != nil {\n\t\tin, out := &in.ScaleRules, &out.ScaleRules\n\t\t*out = make([]ScaleRule, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\tout.DefaultScaleSpec = in.DefaultScaleSpec\n}", "func (o BeanstalkScheduledTaskOutput) ScaleMinCapacity() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BeanstalkScheduledTask) *string { return v.ScaleMinCapacity }).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicyScheduleResponsePtrOutput) Schedule() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyInstanceSchedulePolicyScheduleResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Schedule\n\t}).(pulumi.StringPtrOutput)\n}", "func (in *AppAutoscalingRule) DeepCopy() *AppAutoscalingRule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AppAutoscalingRule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewScalingService(namespace string, deploymentName string, appInterface appsv1.AppsV1Interface) *ScalingService {\n\treturn &ScalingService{\n\t\tnamespace: namespace,\n\t\tdeploymentName: deploymentName,\n\t\tappInterface: appInterface,\n\t}\n}", "func (o MrScalarTaskScalingDownPolicyOutput) Cooldown() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingDownPolicy) *int { return v.Cooldown }).(pulumi.IntPtrOutput)\n}" ]
[ "0.71119064", "0.693392", "0.6830506", "0.6721001", "0.61442715", "0.5926196", "0.57947385", "0.56189704", "0.52660084", "0.5264063", "0.52457696", "0.51870626", "0.5126987", "0.5046777", "0.50401556", "0.49712822", "0.49698833", "0.49486116", "0.48586017", "0.4850098", "0.48220474", "0.47868323", "0.47170848", "0.47013527", "0.46938348", "0.46832883", "0.4681198", "0.4681198", "0.4681198", "0.46787933", "0.4676777", "0.46626598", "0.46625766", "0.4638486", "0.4631405", "0.45908138", "0.457847", "0.45736048", "0.45713872", "0.4567452", "0.45550638", "0.4497004", "0.44942233", "0.44806844", "0.4469779", "0.44567052", "0.44558123", "0.44433117", "0.44383004", "0.44319853", "0.4426515", "0.44209495", "0.44195384", "0.441394", "0.44113764", "0.440802", "0.43984807", "0.43734524", "0.4370152", "0.4360974", "0.43535468", "0.43532845", "0.43415108", "0.4341318", "0.43407506", "0.433358", "0.43304032", "0.43288276", "0.43271422", "0.4321477", "0.4316153", "0.43091285", "0.42919177", "0.4291094", "0.42909047", "0.42831197", "0.4282863", "0.42817065", "0.4265545", "0.42608216", "0.42485037", "0.42436132", "0.42291263", "0.4225091", "0.42210302", "0.4214087", "0.42065507", "0.41993394", "0.4198799", "0.41886726", "0.41782534", "0.41691688", "0.41674197", "0.4146413", "0.4144455", "0.41443282", "0.4141405", "0.41331884", "0.41318822", "0.41260144" ]
0.8683148
0
DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ScheduledPodScaler) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in *ConsoleQuickStart) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ServingRuntime) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Keevakind) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Run) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Pentesting) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Version) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DroidVirt) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ConsoleSample) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ConsoleQuickStartList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Kernel) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ConsoleService) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *AppBinding) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Execution) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *PipelineRun) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Runner) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Terminal) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Terminal) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ConsoleCLIDownload) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *CliApp) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DirectorBind) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t} else {\n\t\treturn nil\n\t}\n}", "func (in *DiscoveryService) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Baremetal) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Egeria) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Qliksense) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Idler) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DroidVirtList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *RpaasBind) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Host) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ServingRuntimeList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *RedisEnterprise) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *SSLProxy) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ConsoleLink) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *GitHubBinding) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *MobileSecurityServiceBind) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DOMachine) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Space) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Space) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *KeevakindList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DockerBind) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t} else {\n\t\treturn nil\n\t}\n}", "func (in *RPMCompose) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Build) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Build) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Build) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Build) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *SecretEngine) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *VultrMachine) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *SpaceBinding) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Redis) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Ray) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Redpanda) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *KeptnCore) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Crd) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Sidekick) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *RunList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Test) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ManagedSeed) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Method) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DirectorBindList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t} else {\n\t\treturn nil\n\t}\n}", "func (in *IdGenerate) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *FundPool) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ExecutionList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *FalconContainer) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ChaosApi) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *RestQL) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *RedisGCache) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *VirtualDatabase) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *VirtualService) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *AppBindingList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Notary) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *QliksenseList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DataExport) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DataExport) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *FusionAppInstance) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *IdGenerateList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DataDownload) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Guestbook) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Memcached) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *User) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ConsoleCLIDownloadList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *GlobalUser) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *PipelineRunList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Hawtio) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *RTCPeerConnection) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *CliAppList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *VirtualNodeList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *GitHubBindingList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *EventingBackend) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *AtRest) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *OpenStackPlaybookGenerator) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Registry) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *UsersDB2) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Ghost) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DiscoveryServiceCertificate) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *WorkflowRun) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *SD) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *CrunchyBridgeConnection) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ManagedSeedList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Manager) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Framework) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *FusionApp) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *AcrPullBinding) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}" ]
[ "0.7313599", "0.7159773", "0.71078354", "0.7100193", "0.7057998", "0.70420074", "0.70387673", "0.7031404", "0.6999637", "0.69742507", "0.6972281", "0.6956138", "0.6953254", "0.6950686", "0.69374573", "0.6936299", "0.6936299", "0.6927747", "0.69247913", "0.6922769", "0.69127214", "0.6902181", "0.6896763", "0.6894812", "0.6889313", "0.68881094", "0.6887458", "0.6879301", "0.6877712", "0.6876597", "0.6865727", "0.68619525", "0.6861538", "0.6852549", "0.6851781", "0.68490577", "0.68490577", "0.68476194", "0.6840962", "0.684016", "0.6838154", "0.6838154", "0.6838154", "0.6838154", "0.68358874", "0.68346894", "0.68321526", "0.68307495", "0.6830184", "0.6830017", "0.68267465", "0.68189156", "0.68154013", "0.6813562", "0.681344", "0.6808154", "0.68024194", "0.67948806", "0.6791351", "0.6784467", "0.67842543", "0.6783978", "0.6783462", "0.67833954", "0.6783365", "0.6770771", "0.6770513", "0.6768317", "0.6765802", "0.67632216", "0.67578137", "0.67578137", "0.6751275", "0.6748667", "0.6746846", "0.6743474", "0.6741314", "0.67410016", "0.6737114", "0.67363214", "0.67354834", "0.6734794", "0.67344004", "0.67342824", "0.67335016", "0.6729829", "0.67296517", "0.6726572", "0.6726253", "0.6722515", "0.6720636", "0.6718909", "0.6716448", "0.6714742", "0.6713263", "0.6712911", "0.67121726", "0.6711576", "0.67104757", "0.6710014", "0.6709131" ]
0.0
-1
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be nonnil.
func (in *ScheduledPodScalerList) DeepCopyInto(out *ScheduledPodScalerList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]ScheduledPodScaler, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RunInfo) DeepCopyInto(out *RunInfo) {\n\t*out = *r\n}", "func (in *Base) DeepCopyInto(out *Base) {\n\t*out = *in\n\treturn\n}", "func (in *ForkObject) DeepCopyInto(out *ForkObject) {\n\t*out = *in\n}", "func (in *TargetObjectInfo) DeepCopyInto(out *TargetObjectInfo) {\n\t*out = *in\n}", "func (in *DebugObjectInfo) DeepCopyInto(out *DebugObjectInfo) {\n\t*out = *in\n}", "func (in *Input) DeepCopyInto(out *Input) {\n\t*out = *in\n}", "func (u *SSN) DeepCopyInto(out *SSN) {\n\t*out = *u\n}", "func (in *ExistPvc) DeepCopyInto(out *ExistPvc) {\n\t*out = *in\n}", "func (in *DockerStep) DeepCopyInto(out *DockerStep) {\n\t*out = *in\n\tif in.Inline != nil {\n\t\tin, out := &in.Inline, &out.Inline\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tout.Auth = in.Auth\n\treturn\n}", "func (in *Container) DeepCopyInto(out *Container) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.Command != nil {\n\t\tin, out := &in.Command, &out.Command\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.LifeCycleScript != nil {\n\t\tin, out := &in.LifeCycleScript, &out.LifeCycleScript\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *RuntimeRef) DeepCopyInto(out *RuntimeRef) {\n\t*out = *in\n}", "func (in *Ibft2) DeepCopyInto(out *Ibft2) {\n\t*out = *in\n\treturn\n}", "func (in *TestResult) DeepCopyInto(out *TestResult) {\n\t*out = *in\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *Haproxy) DeepCopyInto(out *Haproxy) {\n\t*out = *in\n\treturn\n}", "func (in *SSH) DeepCopyInto(out *SSH) {\n\t*out = *in\n\treturn\n}", "func (in *Runtime) DeepCopyInto(out *Runtime) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (b *Base64) DeepCopyInto(out *Base64) {\n\t*out = *b\n}", "func (in *EventDependencyTransformer) DeepCopyInto(out *EventDependencyTransformer) {\n\t*out = *in\n\treturn\n}", "func (in *StageOutput) DeepCopyInto(out *StageOutput) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Dependent) DeepCopyInto(out *Dependent) {\n\t*out = *in\n\treturn\n}", "func (in *GitFileGeneratorItem) DeepCopyInto(out *GitFileGeneratorItem) {\n\t*out = *in\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *AnsibleStep) DeepCopyInto(out *AnsibleStep) {\n\t*out = *in\n\treturn\n}", "func (in *Forks) DeepCopyInto(out *Forks) {\n\t*out = *in\n\tif in.DAO != nil {\n\t\tin, out := &in.DAO, &out.DAO\n\t\t*out = new(uint)\n\t\t**out = **in\n\t}\n}", "func (in *ContainerPort) DeepCopyInto(out *ContainerPort) {\n\t*out = *in\n}", "func (in *General) DeepCopyInto(out *General) {\n\t*out = *in\n\treturn\n}", "func (in *IsoContainer) DeepCopyInto(out *IsoContainer) {\n\t*out = *in\n}", "func (in *Git) DeepCopyInto(out *Git) {\n\t*out = *in\n\treturn\n}", "func (in *ConfigFile) DeepCopyInto(out *ConfigFile) {\n\t*out = *in\n}", "func (in *BackupProgress) DeepCopyInto(out *BackupProgress) {\n\t*out = *in\n}", "func (in *DataDisk) DeepCopyInto(out *DataDisk) {\n\t*out = *in\n}", "func (u *MAC) DeepCopyInto(out *MAC) {\n\t*out = *u\n}", "func (in *PhaseStep) DeepCopyInto(out *PhaseStep) {\n\t*out = *in\n}", "func (in *Variable) DeepCopyInto(out *Variable) {\n\t*out = *in\n}", "func (in *RestoreProgress) DeepCopyInto(out *RestoreProgress) {\n\t*out = *in\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Path) DeepCopyInto(out *Path) {\n\t*out = *in\n\treturn\n}", "func (in *NamespacedObjectReference) DeepCopyInto(out *NamespacedObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *GitDirectoryGeneratorItem) DeepCopyInto(out *GitDirectoryGeneratorItem) {\n\t*out = *in\n}", "func (in *NamePath) DeepCopyInto(out *NamePath) {\n\t*out = *in\n\treturn\n}", "func (in *ConsoleCreateObj) DeepCopyInto(out *ConsoleCreateObj) {\n\t*out = *in\n}", "func (in *UsedPipelineRun) DeepCopyInto(out *UsedPipelineRun) {\n\t*out = *in\n}", "func (in *BuildTemplate) DeepCopyInto(out *BuildTemplate) {\n\t*out = *in\n\tif in.Cmd != nil {\n\t\tin, out := &in.Cmd, &out.Cmd\n\t\t*out = make([]BuildTemplateStep, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n}", "func (in *ObjectInfo) DeepCopyInto(out *ObjectInfo) {\n\t*out = *in\n\tout.GroupVersionKind = in.GroupVersionKind\n\treturn\n}", "func (in *Files) DeepCopyInto(out *Files) {\n\t*out = *in\n}", "func (in *Source) DeepCopyInto(out *Source) {\n\t*out = *in\n\tif in.Dependencies != nil {\n\t\tin, out := &in.Dependencies, &out.Dependencies\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MavenRepositories != nil {\n\t\tin, out := &in.MavenRepositories, &out.MavenRepositories\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\treturn\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *StackBuild) DeepCopyInto(out *StackBuild) {\n\t*out = *in\n\treturn\n}", "func (in *BuildTaskRef) DeepCopyInto(out *BuildTaskRef) {\n\t*out = *in\n\treturn\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *PathInfo) DeepCopyInto(out *PathInfo) {\n\t*out = *in\n}", "func (in *PoA) DeepCopyInto(out *PoA) {\n\t*out = *in\n}", "func (in *Section) DeepCopyInto(out *Section) {\n\t*out = *in\n\tif in.SecretRefs != nil {\n\t\tin, out := &in.SecretRefs, &out.SecretRefs\n\t\t*out = make([]SecretReference, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Files != nil {\n\t\tin, out := &in.Files, &out.Files\n\t\t*out = make([]FileMount, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *DNSSelection) DeepCopyInto(out *DNSSelection) {\n\t*out = *in\n\tif in.Include != nil {\n\t\tin, out := &in.Include, &out.Include\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Exclude != nil {\n\t\tin, out := &in.Exclude, &out.Exclude\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n}", "func (in *ReleaseVersion) DeepCopyInto(out *ReleaseVersion) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Command) DeepCopyInto(out *Command) {\n\t*out = *in\n\tif in.Flags != nil {\n\t\tin, out := &in.Flags, &out.Flags\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Value != nil {\n\t\tin, out := &in.Value, &out.Value\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *PathRule) DeepCopyInto(out *PathRule) {\n\t*out = *in\n\treturn\n}", "func (in *DockerLifecycleData) DeepCopyInto(out *DockerLifecycleData) {\n\t*out = *in\n}", "func (in *RunScriptStepConfig) DeepCopyInto(out *RunScriptStepConfig) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Checksum) DeepCopyInto(out *Checksum) {\n\t*out = *in\n}", "func (in *DomainNameOutput) DeepCopyInto(out *DomainNameOutput) {\n\t*out = *in\n}", "func (in *InterfaceStruct) DeepCopyInto(out *InterfaceStruct) {\n\t*out = *in\n\tif in.val != nil {\n\t\tin, out := &in.val, &out.val\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Ref) DeepCopyInto(out *Ref) {\n\t*out = *in\n}", "func (in *MemorySpec) DeepCopyInto(out *MemorySpec) {\n\t*out = *in\n}", "func (in *BuildJenkinsInfo) DeepCopyInto(out *BuildJenkinsInfo) {\n\t*out = *in\n\treturn\n}", "func (in *MaintenanceInfo) DeepCopyInto(out *MaintenanceInfo) {\n\t*out = *in\n\treturn\n}", "func (in *KopsNode) DeepCopyInto(out *KopsNode) {\n\t*out = *in\n\treturn\n}", "func (in *VirtualDatabaseBuildObject) DeepCopyInto(out *VirtualDatabaseBuildObject) {\n\t*out = *in\n\tif in.Incremental != nil {\n\t\tin, out := &in.Incremental, &out.Incremental\n\t\t*out = new(bool)\n\t\t**out = **in\n\t}\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]v1.EnvVar, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\tout.Git = in.Git\n\tin.Source.DeepCopyInto(&out.Source)\n\tif in.Webhooks != nil {\n\t\tin, out := &in.Webhooks, &out.Webhooks\n\t\t*out = make([]WebhookSecret, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *FalconAPI) DeepCopyInto(out *FalconAPI) {\n\t*out = *in\n}", "func (in *EBS) DeepCopyInto(out *EBS) {\n\t*out = *in\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n\treturn\n}", "func (in *Empty) DeepCopyInto(out *Empty) {\n\t*out = *in\n\tout.XXX_NoUnkeyedLiteral = in.XXX_NoUnkeyedLiteral\n\tif in.XXX_unrecognized != nil {\n\t\tin, out := &in.XXX_unrecognized, &out.XXX_unrecognized\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ComponentDistGit) DeepCopyInto(out *ComponentDistGit) {\n\t*out = *in\n\treturn\n}", "func (in *Persistence) DeepCopyInto(out *Persistence) {\n\t*out = *in\n\tout.Size = in.Size.DeepCopy()\n\treturn\n}", "func (in *Memory) DeepCopyInto(out *Memory) {\n\t*out = *in\n\tout.Required = in.Required.DeepCopy()\n}", "func (in *ManagedDisk) DeepCopyInto(out *ManagedDisk) {\n\t*out = *in\n}", "func (e *Email) DeepCopyInto(out *Email) {\n\t*out = *e\n}", "func (in *ImageInfo) DeepCopyInto(out *ImageInfo) {\n\t*out = *in\n}", "func (in *ShootRef) DeepCopyInto(out *ShootRef) {\n\t*out = *in\n}", "func (in *N3000Fpga) DeepCopyInto(out *N3000Fpga) {\n\t*out = *in\n}", "func (in *NetflowType) DeepCopyInto(out *NetflowType) {\n\t*out = *in\n\treturn\n}", "func (in *Node) DeepCopyInto(out *Node) {\n\t*out = *in\n\tif in.FailStatus != nil {\n\t\tin, out := &in.FailStatus, &out.FailStatus\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MigratingSlots != nil {\n\t\tin, out := &in.MigratingSlots, &out.MigratingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.ImportingSlots != nil {\n\t\tin, out := &in.ImportingSlots, &out.ImportingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n}", "func (in *BuiltInAdapter) DeepCopyInto(out *BuiltInAdapter) {\n\t*out = *in\n}", "func (in *CPUSpec) DeepCopyInto(out *CPUSpec) {\n\t*out = *in\n}", "func (in *LoopState) DeepCopyInto(out *LoopState) {\n\t*out = *in\n}" ]
[ "0.82140106", "0.8126535", "0.81022906", "0.8084453", "0.8082179", "0.8066081", "0.80639637", "0.8025491", "0.80101854", "0.799523", "0.7991342", "0.7987356", "0.7986576", "0.7985699", "0.7985699", "0.7984981", "0.797478", "0.7971586", "0.79687244", "0.79687244", "0.79687244", "0.79678345", "0.79614115", "0.7960733", "0.7944655", "0.7944655", "0.7943215", "0.7941649", "0.7941243", "0.7941243", "0.79378724", "0.79368085", "0.7935971", "0.7928204", "0.7923904", "0.7914545", "0.79109156", "0.79108113", "0.7909308", "0.7908406", "0.7907184", "0.7905054", "0.7904249", "0.7903368", "0.7903368", "0.7903242", "0.790292", "0.79007226", "0.7897853", "0.78962654", "0.7890594", "0.78894955", "0.7888876", "0.788784", "0.7886201", "0.7885162", "0.7884385", "0.7884385", "0.7883503", "0.7879703", "0.7874587", "0.7874587", "0.787378", "0.7872028", "0.78700566", "0.7869837", "0.7869523", "0.78650844", "0.7862038", "0.7862038", "0.7862038", "0.7861828", "0.7861702", "0.78603035", "0.78564954", "0.7856292", "0.7855615", "0.7850385", "0.7844564", "0.78438544", "0.784034", "0.78360575", "0.7836031", "0.78359294", "0.78349257", "0.7832275", "0.78290117", "0.78285843", "0.7826192", "0.7824835", "0.7824337", "0.7822347", "0.78192776", "0.7817813", "0.78121626", "0.78112394", "0.7810061", "0.7809953", "0.7809784", "0.78087157", "0.78077066" ]
0.0
-1
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ScheduledPodScalerList.
func (in *ScheduledPodScalerList) DeepCopy() *ScheduledPodScalerList { if in == nil { return nil } out := new(ScheduledPodScalerList) in.DeepCopyInto(out) return out }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in *ScheduledPodScaler) DeepCopy() *ScheduledPodScaler {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScaler)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerList) DeepCopy() *SchedulingScalerList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerStatus) DeepCopy() *ScheduledPodScalerStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScalerStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerSpec) DeepCopy() *ScheduledPodScalerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScalerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingPolicyList) DeepCopy() *SchedulingPolicyList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingPolicyList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScaler) DeepCopy() *SchedulingScaler {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScaler)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScalingPolicyList) DeepCopy() *ScalingPolicyList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalingPolicyList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerStatus) DeepCopy() *SchedulingScalerStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewScheduledScalerController(\n\tinformerFactory informers.SharedInformerFactory,\n\trestdevClient clientset.Interface,\n\tkubeClient *kubernetes.Clientset,\n) *ScheduledScalerController {\n\tscheduledScalerInformer := informerFactory.Scaling().V1alpha1().ScheduledScalers()\n\tscheduledScalersLister := scheduledScalerInformer.Lister()\n\tvar scheduledScalerTargets []ScheduledScalerTarget\n\n\tc := &ScheduledScalerController{\n\t\tinformerFactory: informerFactory,\n\t\trestdevClient: restdevClient,\n\t\tkubeClient: kubeClient,\n\t\tscheduledScalersLister: scheduledScalersLister,\n\t\tscheduledScalersSynced: scheduledScalerInformer.Informer().HasSynced,\n\t\tscheduledScalerTargets: scheduledScalerTargets,\n\t}\n\tscheduledScalerInformer.Informer().AddEventHandler(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: c.scheduledScalerAdd,\n\t\t\tUpdateFunc: c.scheduledScalerUpdate,\n\t\t\tDeleteFunc: c.scheduledScalerDelete,\n\t\t},\n\t)\n\treturn c\n}", "func (in *ScheduleList) DeepCopy() *ScheduleList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduleList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ScheduledSparkApplicationList) DeepCopy() *ScheduledSparkApplicationList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledSparkApplicationList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *ScheduledScalerController) scheduledScalerUpdate(old, new interface{}) {\n\toldScheduledScaler := old.(*scalingv1alpha1.ScheduledScaler)\n\tnewScheduledScaler := new.(*scalingv1alpha1.ScheduledScaler)\n\tif reflect.DeepEqual(oldScheduledScaler.Spec, newScheduledScaler.Spec) {\n\t\treturn\n\t}\n\tc.scheduledScalerDelete(old)\n\tc.scheduledScalerAdd(new)\n}", "func (in *WatermarkHorizontalPodAutoscalerList) DeepCopy() *WatermarkHorizontalPodAutoscalerList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WatermarkHorizontalPodAutoscalerList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulerEnhancerList) DeepCopy() *SchedulerEnhancerList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulerEnhancerList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScaleList) DeepCopy() *ScaleList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerSchedule) DeepCopy() *SchedulingScalerSchedule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerSchedule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerList) DeepCopyInto(out *ScheduledPodScalerList) {\n\t*out = *in\n\tout.TypeMeta = in.TypeMeta\n\tin.ListMeta.DeepCopyInto(&out.ListMeta)\n\tif in.Items != nil {\n\t\tin, out := &in.Items, &out.Items\n\t\t*out = make([]ScheduledPodScaler, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n}", "func (in *TaskScheduleList) DeepCopy() *TaskScheduleList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TaskScheduleList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PagerdutyServiceList) DeepCopy() *PagerdutyServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PagerdutyServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *ScheduledScalerController) scheduledScalerAdd(obj interface{}) {\n\tscheduledScaler := obj.(*scalingv1alpha1.ScheduledScaler)\n\tif scheduledScaler.Spec.Target.Kind == \"HorizontalPodAutoscaler\" {\n\t\tc.scheduledScalerHpaCronAdd(obj)\n\t} else if scheduledScaler.Spec.Target.Kind == \"InstanceGroup\" {\n\t\tc.scheduledScalerIgCronAdd(obj)\n\t}\n}", "func (in *PipelineRunList) DeepCopy() *PipelineRunList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PipelineRunList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PagerdutyRulesetList) DeepCopy() *PagerdutyRulesetList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PagerdutyRulesetList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func cmdListPolicySchedules(ccmd *cobra.Command, args []string) {\n\taplSvc := apl.NewClient()\n\n\toutput := runListCommand(&policyScheduleParams, aplSvc.PolicySchedules.List)\n\n\tif output != nil {\n\t\tfields := []string{\"ID\", \"Name\", \"ResourceType\", \"Status\", \"CreatedTime\"}\n\t\tprintTableResultsCustom(output.([]apl.PolicySchedule), fields)\n\t}\n}", "func (in *ManagerScheduleRequestList) DeepCopy() *ManagerScheduleRequestList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ManagerScheduleRequestList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in ResourceList) DeepCopy() ResourceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ResourceList)\n\tin.DeepCopyInto(out)\n\treturn *out\n}", "func (in *NamespacedControllerResourceList) DeepCopy() *NamespacedControllerResourceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(NamespacedControllerResourceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ChaosPodList) DeepCopy() *ChaosPodList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ChaosPodList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServingRuntimeList) DeepCopy() *ServingRuntimeList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServingRuntimeList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in NamespacedResourceList) DeepCopy() NamespacedResourceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(NamespacedResourceList)\n\tin.DeepCopyInto(out)\n\treturn *out\n}", "func (in *SchedulingScalerList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *PodSpecWorkloadList) DeepCopy() *PodSpecWorkloadList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PodSpecWorkloadList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SesActiveReceiptRuleSetList) DeepCopy() *SesActiveReceiptRuleSetList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SesActiveReceiptRuleSetList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *podConverter) ConvertList(originalList interface{}) (convertedList interface{}, err error) {\n\tpodList, ok := originalList.(*corev1.PodList)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to convert object to pod list\")\n\t}\n\t// We need to set continue in order to allow the pagination to work on converted\n\t// pod list object\n\tstrippedPodList := corev1.PodList{\n\t\tListMeta: metaV1.ListMeta{\n\t\t\tContinue: podList.Continue,\n\t\t\tResourceVersion: podList.ResourceVersion,\n\t\t},\n\t}\n\tfor _, pod := range podList.Items {\n\t\tstrippedPod := c.stripDownPod(&pod)\n\t\tstrippedPodList.Items = append(strippedPodList.Items, *strippedPod)\n\t}\n\treturn &strippedPodList, nil\n}", "func (in *CiliumBGPPeeringPolicyList) DeepCopy() *CiliumBGPPeeringPolicyList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CiliumBGPPeeringPolicyList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ResourceSigningProfileList) DeepCopy() *ResourceSigningProfileList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ResourceSigningProfileList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RedshiftEventSubscriptionList) DeepCopy() *RedshiftEventSubscriptionList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RedshiftEventSubscriptionList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScalableTargetList) DeepCopy() *ScalableTargetList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalableTargetList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SonicwallNetworkPolicyList) DeepCopy() *SonicwallNetworkPolicyList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SonicwallNetworkPolicyList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RpaasPlanList) DeepCopy() *RpaasPlanList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RpaasPlanList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *scheduledJobs) List(opts api.ListOptions) (result *batch.ScheduledJobList, err error) {\n\tresult = &batch.ScheduledJobList{}\n\terr = c.r.Get().Namespace(c.ns).Resource(\"scheduledjobs\").VersionedParams(&opts, api.ParameterCodec).Do().Into(result)\n\treturn\n}", "func (in *MobileSecurityServiceList) DeepCopy() *MobileSecurityServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MobileSecurityServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ArgusWatcherList) DeepCopy() *ArgusWatcherList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ArgusWatcherList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func podScheduledState() *corev1.Pod {\n\treturn mustLoadPodRecording(podStatePath(\"scheduled\"))\n}", "func (c *horizontalPodAutoscalers) List(ctx context.Context, opts metav1.ListOptions) (result *v1.HorizontalPodAutoscalerList, err error) {\n\tns := c.getNs(c.ns)\n\tresult, err = c.hpa.List(ctx, opts)\n\tif err != nil {\n\t\tcode := getStatusCode(err)\n\t\tc.metrics.ClientMetricErrors.WithLabelValues(\"hpa\", \"list\", \"\", ns, code).Inc()\n\t\treturn\n\t}\n\tc.metrics.ClientMetricSuccess.WithLabelValues(\"hpa\", \"list\", \"\", ns).Inc()\n\treturn\n}", "func (in *ShadowPodList) DeepCopy() *ShadowPodList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ShadowPodList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SecurityhubStandardsSubscriptionList) DeepCopy() *SecurityhubStandardsSubscriptionList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SecurityhubStandardsSubscriptionList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *MobileSecurityServiceDBList) DeepCopy() *MobileSecurityServiceDBList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MobileSecurityServiceDBList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AgentSchedInfoList) DeepCopy() *AgentSchedInfoList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AgentSchedInfoList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *CatalogServiceClaimList) DeepCopy() *CatalogServiceClaimList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CatalogServiceClaimList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ReaperList) DeepCopy() *ReaperList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ReaperList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SpinnakerServiceList) DeepCopy() *SpinnakerServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SpinnakerServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingPolicy) DeepCopy() *SchedulingPolicy {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingPolicy)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c Client) List(listParams *stripe.SubscriptionScheduleListParams) *Iter {\n\treturn &Iter{stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListContainer, error) {\n\t\tlist := &stripe.SubscriptionScheduleList{}\n\t\terr := c.B.CallRaw(http.MethodGet, \"/v1/subscription_schedules\", c.Key, b, p, list)\n\n\t\tret := make([]interface{}, len(list.Data))\n\t\tfor i, v := range list.Data {\n\t\t\tret[i] = v\n\t\t}\n\n\t\treturn ret, list, err\n\t})}\n}", "func (in *AWSManagedControlPlaneList) DeepCopy() *AWSManagedControlPlaneList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AWSManagedControlPlaneList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RegistryCronJobList) DeepCopy() *RegistryCronJobList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RegistryCronJobList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (i *Iter) SubscriptionScheduleList() *stripe.SubscriptionScheduleList {\n\treturn i.List().(*stripe.SubscriptionScheduleList)\n}", "func (in *ResourceList) DeepCopy() *ResourceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ResourceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ResourceList) DeepCopy() *ResourceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ResourceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerSpec) DeepCopy() *SchedulingScalerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *FlexibleServersFirewallRuleList) DeepCopy() *FlexibleServersFirewallRuleList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(FlexibleServersFirewallRuleList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DopplerSecretList) DeepCopy() *DopplerSecretList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DopplerSecretList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerList) DeepCopyInto(out *SchedulingScalerList) {\n\t*out = *in\n\tout.TypeMeta = in.TypeMeta\n\tout.ListMeta = in.ListMeta\n\tif in.Items != nil {\n\t\tin, out := &in.Items, &out.Items\n\t\t*out = make([]SchedulingScaler, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\treturn\n}", "func (in *HorizontalPodAutoscaling) DeepCopy() *HorizontalPodAutoscaling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HorizontalPodAutoscaling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RemoteShuffleServiceList) DeepCopy() *RemoteShuffleServiceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RemoteShuffleServiceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RunnerList) DeepCopy() *RunnerList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RunnerList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewWatchAutoscalingV1NamespacedHorizontalPodAutoscalerList(ctx *middleware.Context, handler WatchAutoscalingV1NamespacedHorizontalPodAutoscalerListHandler) *WatchAutoscalingV1NamespacedHorizontalPodAutoscalerList {\n\treturn &WatchAutoscalingV1NamespacedHorizontalPodAutoscalerList{Context: ctx, Handler: handler}\n}", "func (in *SippScenarioRunList) DeepCopy() *SippScenarioRunList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SippScenarioRunList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ControllerResourceList) DeepCopy() *ControllerResourceList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ControllerResourceList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o AutoscalingPolicyPtrOutput) ScalingSchedules() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *AutoscalingPolicy) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScalingSchedules\n\t}).(pulumi.StringMapOutput)\n}", "func (in *SchedulingPolicyStatus) DeepCopy() *SchedulingPolicyStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingPolicyStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RunList) DeepCopy() *RunList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RunList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SubscriptionList) DeepCopy() *SubscriptionList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubscriptionList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SubscriptionList) DeepCopy() *SubscriptionList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubscriptionList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o ApplicationSpecRolloutplanRolloutbatchesOutput) PodList() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationSpecRolloutplanRolloutbatches) []string { return v.PodList }).(pulumi.StringArrayOutput)\n}", "func (in *ProxySQLSettingsList) DeepCopy() *ProxySQLSettingsList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ProxySQLSettingsList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PolicyList) DeepCopy() *PolicyList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PolicyList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PolicyList) DeepCopy() *PolicyList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PolicyList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PolicyList) DeepCopy() *PolicyList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PolicyList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (a *Client) WatchPolicyV1beta1PodSecurityPolicyList(params *WatchPolicyV1beta1PodSecurityPolicyListParams) (*WatchPolicyV1beta1PodSecurityPolicyListOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewWatchPolicyV1beta1PodSecurityPolicyListParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"watchPolicyV1beta1PodSecurityPolicyList\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/apis/policy/v1beta1/watch/podsecuritypolicies\",\n\t\tProducesMediaTypes: []string{\"application/json\", \"application/json;stream=watch\", \"application/vnd.kubernetes.protobuf\", \"application/vnd.kubernetes.protobuf;stream=watch\", \"application/yaml\"},\n\t\tConsumesMediaTypes: []string{\"*/*\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &WatchPolicyV1beta1PodSecurityPolicyListReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*WatchPolicyV1beta1PodSecurityPolicyListOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for watchPolicyV1beta1PodSecurityPolicyList: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (s *appautoscalingPolicyLister) List(selector labels.Selector) (ret []*v1alpha1.AppautoscalingPolicy, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.AppautoscalingPolicy))\n\t})\n\treturn ret, err\n}", "func (o AutoscalingPolicyOutput) ScalingSchedules() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v AutoscalingPolicy) map[string]string { return v.ScalingSchedules }).(pulumi.StringMapOutput)\n}", "func (in *AnalysisRunList) DeepCopy() *AnalysisRunList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AnalysisRunList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PrintPoliciesList) DeepCopy() *PrintPoliciesList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PrintPoliciesList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AcrPullBindingList) DeepCopy() *AcrPullBindingList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AcrPullBindingList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o AutoscalingPolicyResponsePtrOutput) ScalingSchedules() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *AutoscalingPolicyResponse) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScalingSchedules\n\t}).(pulumi.StringMapOutput)\n}", "func (in *ComponentSchematicList) DeepCopy() *ComponentSchematicList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ComponentSchematicList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RequestValidatorList) DeepCopy() *RequestValidatorList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RequestValidatorList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RolloutList) DeepCopy() *RolloutList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RolloutList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *StreamProcessorList) DeepCopy() *StreamProcessorList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(StreamProcessorList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ConfigMapSecretList) DeepCopy() *ConfigMapSecretList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ConfigMapSecretList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SidekickList) DeepCopy() *SidekickList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SidekickList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ResourceEventList) DeepCopy() *ResourceEventList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ResourceEventList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AdmissionWebhookConfigurationList) DeepCopy() *AdmissionWebhookConfigurationList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AdmissionWebhookConfigurationList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SDList) DeepCopy() *SDList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SDList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WorkflowRunList) DeepCopy() *WorkflowRunList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WorkflowRunList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *KubeEventsRuleList) DeepCopy() *KubeEventsRuleList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(KubeEventsRuleList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *TemplatedSecretList) DeepCopy() *TemplatedSecretList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TemplatedSecretList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PodmigrationList) DeepCopy() *PodmigrationList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PodmigrationList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o AutoscalingPolicyResponseOutput) ScalingSchedules() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v AutoscalingPolicyResponse) map[string]string { return v.ScalingSchedules }).(pulumi.StringMapOutput)\n}" ]
[ "0.7750979", "0.7559887", "0.6551569", "0.6509302", "0.6166534", "0.6004988", "0.58682466", "0.5656365", "0.5619697", "0.55305785", "0.54600435", "0.54446167", "0.54325646", "0.5428292", "0.5374004", "0.52421725", "0.5234001", "0.51786524", "0.5168573", "0.5000829", "0.49904522", "0.4945905", "0.49228135", "0.49135762", "0.49038017", "0.49025542", "0.48940226", "0.488865", "0.4884627", "0.48691565", "0.4858265", "0.4792092", "0.4779957", "0.47794178", "0.4773856", "0.4758986", "0.47516346", "0.47315755", "0.4731241", "0.47191498", "0.471586", "0.4714637", "0.47045097", "0.46990323", "0.46707168", "0.46613058", "0.46582365", "0.46416125", "0.46294987", "0.4619436", "0.46164936", "0.4616367", "0.461633", "0.46154344", "0.4613828", "0.45919237", "0.4580839", "0.45731163", "0.45731163", "0.45689625", "0.45653197", "0.4558383", "0.4555218", "0.455184", "0.45508295", "0.45415848", "0.45408097", "0.45201194", "0.45171767", "0.4515247", "0.4509236", "0.4507091", "0.44930774", "0.44930774", "0.44916603", "0.44909763", "0.4477185", "0.4477185", "0.4477185", "0.4473423", "0.44573405", "0.44557923", "0.4436622", "0.44348824", "0.44340703", "0.44323972", "0.44285095", "0.44252425", "0.43974617", "0.439421", "0.4388197", "0.43860936", "0.4384566", "0.4380796", "0.43791497", "0.4374866", "0.4373358", "0.43703216", "0.4369798", "0.43683726" ]
0.8506346
0
DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ScheduledPodScalerList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in *ConsoleQuickStart) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ServingRuntime) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Keevakind) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Run) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Pentesting) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Version) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DroidVirt) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ConsoleSample) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ConsoleQuickStartList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Kernel) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ConsoleService) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *AppBinding) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Execution) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *PipelineRun) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Runner) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Terminal) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Terminal) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ConsoleCLIDownload) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *CliApp) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DirectorBind) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t} else {\n\t\treturn nil\n\t}\n}", "func (in *DiscoveryService) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Baremetal) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Egeria) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Qliksense) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Idler) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *RpaasBind) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DroidVirtList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Host) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ServingRuntimeList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *RedisEnterprise) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *SSLProxy) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ConsoleLink) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *GitHubBinding) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *MobileSecurityServiceBind) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DOMachine) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Space) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Space) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *KeevakindList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DockerBind) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t} else {\n\t\treturn nil\n\t}\n}", "func (in *RPMCompose) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Build) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Build) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Build) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Build) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *SecretEngine) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *VultrMachine) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *SpaceBinding) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Redis) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Ray) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Redpanda) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *KeptnCore) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Crd) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Sidekick) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Test) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *RunList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ManagedSeed) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Method) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DirectorBindList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t} else {\n\t\treturn nil\n\t}\n}", "func (in *IdGenerate) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ExecutionList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *FundPool) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *FalconContainer) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *RestQL) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *RedisGCache) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ChaosApi) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *VirtualDatabase) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *VirtualService) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *AppBindingList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Notary) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *QliksenseList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DataExport) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DataExport) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *FusionAppInstance) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *IdGenerateList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DataDownload) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Guestbook) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *User) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Memcached) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ConsoleCLIDownloadList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *PipelineRunList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *GlobalUser) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *CliAppList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Hawtio) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *VirtualNodeList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *RTCPeerConnection) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *EventingBackend) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *GitHubBindingList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *AtRest) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *OpenStackPlaybookGenerator) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Registry) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *UsersDB2) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Ghost) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *WorkflowRun) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *DiscoveryServiceCertificate) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *SD) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *CrunchyBridgeConnection) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *ManagedSeedList) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *PyTorchJob) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Manager) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *Framework) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}", "func (in *FusionApp) DeepCopyObject() runtime.Object {\n\tif c := in.DeepCopy(); c != nil {\n\t\treturn c\n\t}\n\treturn nil\n}" ]
[ "0.7311342", "0.7156597", "0.7103883", "0.70991915", "0.7054586", "0.7039165", "0.7035086", "0.70284057", "0.69967586", "0.6971953", "0.6969126", "0.69532204", "0.6950954", "0.6948572", "0.69361", "0.6933072", "0.6933072", "0.692678", "0.6922488", "0.69198173", "0.69095355", "0.6897871", "0.68928355", "0.68921006", "0.6887237", "0.68849045", "0.6884421", "0.68758804", "0.6874541", "0.6873571", "0.68616486", "0.68584895", "0.6858347", "0.6850145", "0.6849406", "0.68446445", "0.68446445", "0.6843653", "0.6838536", "0.6838176", "0.6836276", "0.6836276", "0.6836276", "0.6836276", "0.6833141", "0.6831596", "0.6828097", "0.682682", "0.68264115", "0.68260664", "0.68236995", "0.681544", "0.68123156", "0.6812016", "0.6811409", "0.68039876", "0.68015194", "0.67918044", "0.678819", "0.67815363", "0.67808676", "0.6780768", "0.67803", "0.6779626", "0.6779587", "0.6766908", "0.67665863", "0.6764979", "0.67615294", "0.67603123", "0.67544574", "0.67544574", "0.67474705", "0.67450285", "0.6743412", "0.67396", "0.67373306", "0.6736187", "0.67352176", "0.67333025", "0.6733183", "0.67318976", "0.6731568", "0.67300814", "0.67297643", "0.6726818", "0.6726361", "0.67233855", "0.6723238", "0.67199624", "0.67171913", "0.6715264", "0.67127943", "0.6712638", "0.670966", "0.6709269", "0.67080003", "0.67075443", "0.67073816", "0.6707319", "0.6707138" ]
0.0
-1
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be nonnil.
func (in *ScheduledPodScalerSpec) DeepCopyInto(out *ScheduledPodScalerSpec) { *out = *in in.ScaleTarget.DeepCopyInto(&out.ScaleTarget) if in.ScaleRules != nil { in, out := &in.ScaleRules, &out.ScaleRules *out = make([]ScaleRule, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } out.DefaultScaleSpec = in.DefaultScaleSpec }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RunInfo) DeepCopyInto(out *RunInfo) {\n\t*out = *r\n}", "func (in *Base) DeepCopyInto(out *Base) {\n\t*out = *in\n\treturn\n}", "func (in *ForkObject) DeepCopyInto(out *ForkObject) {\n\t*out = *in\n}", "func (in *TargetObjectInfo) DeepCopyInto(out *TargetObjectInfo) {\n\t*out = *in\n}", "func (in *DebugObjectInfo) DeepCopyInto(out *DebugObjectInfo) {\n\t*out = *in\n}", "func (in *Input) DeepCopyInto(out *Input) {\n\t*out = *in\n}", "func (u *SSN) DeepCopyInto(out *SSN) {\n\t*out = *u\n}", "func (in *ExistPvc) DeepCopyInto(out *ExistPvc) {\n\t*out = *in\n}", "func (in *DockerStep) DeepCopyInto(out *DockerStep) {\n\t*out = *in\n\tif in.Inline != nil {\n\t\tin, out := &in.Inline, &out.Inline\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tout.Auth = in.Auth\n\treturn\n}", "func (in *Container) DeepCopyInto(out *Container) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.Command != nil {\n\t\tin, out := &in.Command, &out.Command\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.LifeCycleScript != nil {\n\t\tin, out := &in.LifeCycleScript, &out.LifeCycleScript\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *RuntimeRef) DeepCopyInto(out *RuntimeRef) {\n\t*out = *in\n}", "func (in *Ibft2) DeepCopyInto(out *Ibft2) {\n\t*out = *in\n\treturn\n}", "func (in *TestResult) DeepCopyInto(out *TestResult) {\n\t*out = *in\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *Haproxy) DeepCopyInto(out *Haproxy) {\n\t*out = *in\n\treturn\n}", "func (in *SSH) DeepCopyInto(out *SSH) {\n\t*out = *in\n\treturn\n}", "func (in *Runtime) DeepCopyInto(out *Runtime) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (b *Base64) DeepCopyInto(out *Base64) {\n\t*out = *b\n}", "func (in *EventDependencyTransformer) DeepCopyInto(out *EventDependencyTransformer) {\n\t*out = *in\n\treturn\n}", "func (in *StageOutput) DeepCopyInto(out *StageOutput) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Dependent) DeepCopyInto(out *Dependent) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *GitFileGeneratorItem) DeepCopyInto(out *GitFileGeneratorItem) {\n\t*out = *in\n}", "func (in *AnsibleStep) DeepCopyInto(out *AnsibleStep) {\n\t*out = *in\n\treturn\n}", "func (in *Forks) DeepCopyInto(out *Forks) {\n\t*out = *in\n\tif in.DAO != nil {\n\t\tin, out := &in.DAO, &out.DAO\n\t\t*out = new(uint)\n\t\t**out = **in\n\t}\n}", "func (in *ContainerPort) DeepCopyInto(out *ContainerPort) {\n\t*out = *in\n}", "func (in *General) DeepCopyInto(out *General) {\n\t*out = *in\n\treturn\n}", "func (in *IsoContainer) DeepCopyInto(out *IsoContainer) {\n\t*out = *in\n}", "func (in *Git) DeepCopyInto(out *Git) {\n\t*out = *in\n\treturn\n}", "func (in *BackupProgress) DeepCopyInto(out *BackupProgress) {\n\t*out = *in\n}", "func (in *ConfigFile) DeepCopyInto(out *ConfigFile) {\n\t*out = *in\n}", "func (in *DataDisk) DeepCopyInto(out *DataDisk) {\n\t*out = *in\n}", "func (in *PhaseStep) DeepCopyInto(out *PhaseStep) {\n\t*out = *in\n}", "func (u *MAC) DeepCopyInto(out *MAC) {\n\t*out = *u\n}", "func (in *Variable) DeepCopyInto(out *Variable) {\n\t*out = *in\n}", "func (in *RestoreProgress) DeepCopyInto(out *RestoreProgress) {\n\t*out = *in\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *NamespacedObjectReference) DeepCopyInto(out *NamespacedObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Path) DeepCopyInto(out *Path) {\n\t*out = *in\n\treturn\n}", "func (in *GitDirectoryGeneratorItem) DeepCopyInto(out *GitDirectoryGeneratorItem) {\n\t*out = *in\n}", "func (in *NamePath) DeepCopyInto(out *NamePath) {\n\t*out = *in\n\treturn\n}", "func (in *ConsoleCreateObj) DeepCopyInto(out *ConsoleCreateObj) {\n\t*out = *in\n}", "func (in *UsedPipelineRun) DeepCopyInto(out *UsedPipelineRun) {\n\t*out = *in\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n}", "func (in *BuildTemplate) DeepCopyInto(out *BuildTemplate) {\n\t*out = *in\n\tif in.Cmd != nil {\n\t\tin, out := &in.Cmd, &out.Cmd\n\t\t*out = make([]BuildTemplateStep, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\treturn\n}", "func (in *ObjectInfo) DeepCopyInto(out *ObjectInfo) {\n\t*out = *in\n\tout.GroupVersionKind = in.GroupVersionKind\n\treturn\n}", "func (in *Files) DeepCopyInto(out *Files) {\n\t*out = *in\n}", "func (in *Source) DeepCopyInto(out *Source) {\n\t*out = *in\n\tif in.Dependencies != nil {\n\t\tin, out := &in.Dependencies, &out.Dependencies\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MavenRepositories != nil {\n\t\tin, out := &in.MavenRepositories, &out.MavenRepositories\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\treturn\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *StackBuild) DeepCopyInto(out *StackBuild) {\n\t*out = *in\n\treturn\n}", "func (in *BuildTaskRef) DeepCopyInto(out *BuildTaskRef) {\n\t*out = *in\n\treturn\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *PathInfo) DeepCopyInto(out *PathInfo) {\n\t*out = *in\n}", "func (in *PoA) DeepCopyInto(out *PoA) {\n\t*out = *in\n}", "func (in *Section) DeepCopyInto(out *Section) {\n\t*out = *in\n\tif in.SecretRefs != nil {\n\t\tin, out := &in.SecretRefs, &out.SecretRefs\n\t\t*out = make([]SecretReference, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Files != nil {\n\t\tin, out := &in.Files, &out.Files\n\t\t*out = make([]FileMount, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *DNSSelection) DeepCopyInto(out *DNSSelection) {\n\t*out = *in\n\tif in.Include != nil {\n\t\tin, out := &in.Include, &out.Include\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Exclude != nil {\n\t\tin, out := &in.Exclude, &out.Exclude\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n}", "func (in *ReleaseVersion) DeepCopyInto(out *ReleaseVersion) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *PathRule) DeepCopyInto(out *PathRule) {\n\t*out = *in\n\treturn\n}", "func (in *Command) DeepCopyInto(out *Command) {\n\t*out = *in\n\tif in.Flags != nil {\n\t\tin, out := &in.Flags, &out.Flags\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Value != nil {\n\t\tin, out := &in.Value, &out.Value\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *DockerLifecycleData) DeepCopyInto(out *DockerLifecycleData) {\n\t*out = *in\n}", "func (in *RunScriptStepConfig) DeepCopyInto(out *RunScriptStepConfig) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Checksum) DeepCopyInto(out *Checksum) {\n\t*out = *in\n}", "func (in *DomainNameOutput) DeepCopyInto(out *DomainNameOutput) {\n\t*out = *in\n}", "func (in *InterfaceStruct) DeepCopyInto(out *InterfaceStruct) {\n\t*out = *in\n\tif in.val != nil {\n\t\tin, out := &in.val, &out.val\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Ref) DeepCopyInto(out *Ref) {\n\t*out = *in\n}", "func (in *MemorySpec) DeepCopyInto(out *MemorySpec) {\n\t*out = *in\n}", "func (in *BuildJenkinsInfo) DeepCopyInto(out *BuildJenkinsInfo) {\n\t*out = *in\n\treturn\n}", "func (in *KopsNode) DeepCopyInto(out *KopsNode) {\n\t*out = *in\n\treturn\n}", "func (in *MaintenanceInfo) DeepCopyInto(out *MaintenanceInfo) {\n\t*out = *in\n\treturn\n}", "func (in *VirtualDatabaseBuildObject) DeepCopyInto(out *VirtualDatabaseBuildObject) {\n\t*out = *in\n\tif in.Incremental != nil {\n\t\tin, out := &in.Incremental, &out.Incremental\n\t\t*out = new(bool)\n\t\t**out = **in\n\t}\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]v1.EnvVar, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\tout.Git = in.Git\n\tin.Source.DeepCopyInto(&out.Source)\n\tif in.Webhooks != nil {\n\t\tin, out := &in.Webhooks, &out.Webhooks\n\t\t*out = make([]WebhookSecret, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *FalconAPI) DeepCopyInto(out *FalconAPI) {\n\t*out = *in\n}", "func (in *EBS) DeepCopyInto(out *EBS) {\n\t*out = *in\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n\treturn\n}", "func (in *Empty) DeepCopyInto(out *Empty) {\n\t*out = *in\n\tout.XXX_NoUnkeyedLiteral = in.XXX_NoUnkeyedLiteral\n\tif in.XXX_unrecognized != nil {\n\t\tin, out := &in.XXX_unrecognized, &out.XXX_unrecognized\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ComponentDistGit) DeepCopyInto(out *ComponentDistGit) {\n\t*out = *in\n\treturn\n}", "func (in *Persistence) DeepCopyInto(out *Persistence) {\n\t*out = *in\n\tout.Size = in.Size.DeepCopy()\n\treturn\n}", "func (in *Memory) DeepCopyInto(out *Memory) {\n\t*out = *in\n\tout.Required = in.Required.DeepCopy()\n}", "func (in *ManagedDisk) DeepCopyInto(out *ManagedDisk) {\n\t*out = *in\n}", "func (e *Email) DeepCopyInto(out *Email) {\n\t*out = *e\n}", "func (in *ImageInfo) DeepCopyInto(out *ImageInfo) {\n\t*out = *in\n}", "func (in *ShootRef) DeepCopyInto(out *ShootRef) {\n\t*out = *in\n}", "func (in *NetflowType) DeepCopyInto(out *NetflowType) {\n\t*out = *in\n\treturn\n}", "func (in *N3000Fpga) DeepCopyInto(out *N3000Fpga) {\n\t*out = *in\n}", "func (in *BuiltInAdapter) DeepCopyInto(out *BuiltInAdapter) {\n\t*out = *in\n}", "func (in *Node) DeepCopyInto(out *Node) {\n\t*out = *in\n\tif in.FailStatus != nil {\n\t\tin, out := &in.FailStatus, &out.FailStatus\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MigratingSlots != nil {\n\t\tin, out := &in.MigratingSlots, &out.MigratingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.ImportingSlots != nil {\n\t\tin, out := &in.ImportingSlots, &out.ImportingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n}", "func (in *CPUSpec) DeepCopyInto(out *CPUSpec) {\n\t*out = *in\n}", "func (in *LoopState) DeepCopyInto(out *LoopState) {\n\t*out = *in\n}" ]
[ "0.8215148", "0.8128148", "0.8104491", "0.8086232", "0.8083645", "0.80681837", "0.8064712", "0.80272263", "0.80118906", "0.79957503", "0.79923207", "0.79894227", "0.79878217", "0.7987706", "0.7987706", "0.79856145", "0.7976737", "0.797243", "0.79705614", "0.79705614", "0.79705614", "0.7967998", "0.7963185", "0.7962239", "0.7946799", "0.7946799", "0.79451364", "0.79437023", "0.79437023", "0.79423654", "0.79407156", "0.79375064", "0.79369694", "0.7929554", "0.7925828", "0.79153883", "0.79121333", "0.7912032", "0.7910158", "0.79093456", "0.79087806", "0.7906067", "0.7906014", "0.7905399", "0.7905399", "0.79051214", "0.790477", "0.79011744", "0.7899582", "0.7897098", "0.7891637", "0.78907233", "0.78905463", "0.78897065", "0.78873104", "0.7886752", "0.7885397", "0.7885397", "0.7885259", "0.78815824", "0.787546", "0.787546", "0.7875398", "0.78739077", "0.78724843", "0.78717405", "0.78714716", "0.7865966", "0.7864238", "0.7864238", "0.7864238", "0.7863405", "0.7862614", "0.7860687", "0.78587526", "0.7858436", "0.78570235", "0.78514445", "0.7846122", "0.78443074", "0.78416294", "0.7837446", "0.78372633", "0.78368735", "0.78350383", "0.7833183", "0.78313106", "0.7830074", "0.78268486", "0.78255475", "0.7825175", "0.78235906", "0.78204864", "0.78198004", "0.7812933", "0.7811604", "0.78113776", "0.7810981", "0.78103817", "0.7809776", "0.78089356" ]
0.0
-1
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ScheduledPodScalerSpec.
func (in *ScheduledPodScalerSpec) DeepCopy() *ScheduledPodScalerSpec { if in == nil { return nil } out := new(ScheduledPodScalerSpec) in.DeepCopyInto(out) return out }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in *ScheduledPodScaler) DeepCopy() *ScheduledPodScaler {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScaler)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerSpec) DeepCopy() *SchedulingScalerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScaler) DeepCopy() *SchedulingScaler {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScaler)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerList) DeepCopy() *ScheduledPodScalerList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScalerList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerSchedule) DeepCopy() *SchedulingScalerSchedule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerSchedule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerStatus) DeepCopy() *ScheduledPodScalerStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScalerStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingPolicySpec) DeepCopy() *SchedulingPolicySpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingPolicySpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScalingPolicySpec) DeepCopy() *ScalingPolicySpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalingPolicySpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RSSPodSpec) DeepCopy() *RSSPodSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RSSPodSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerList) DeepCopy() *SchedulingScalerList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerStatus) DeepCopy() *SchedulingScalerStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServingRuntimePodSpec) DeepCopy() *ServingRuntimePodSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServingRuntimePodSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduleSpec) DeepCopy() *ScheduleSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduleSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulerEnhancerSpec) DeepCopy() *SchedulerEnhancerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulerEnhancerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DeploymentV1PodSpec) DeepCopy() *DeploymentV1PodSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DeploymentV1PodSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingPolicy) DeepCopy() *SchedulingPolicy {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingPolicy)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PagerdutyServiceSpec) DeepCopy() *PagerdutyServiceSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PagerdutyServiceSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RollingUpdateSpec) DeepCopy() *RollingUpdateSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RollingUpdateSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RollingUpdateSpec) DeepCopy() *RollingUpdateSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RollingUpdateSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledSparkApplicationSpec) DeepCopy() *ScheduledSparkApplicationSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledSparkApplicationSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (c *ScheduledScalerController) scheduledScalerUpdate(old, new interface{}) {\n\toldScheduledScaler := old.(*scalingv1alpha1.ScheduledScaler)\n\tnewScheduledScaler := new.(*scalingv1alpha1.ScheduledScaler)\n\tif reflect.DeepEqual(oldScheduledScaler.Spec, newScheduledScaler.Spec) {\n\t\treturn\n\t}\n\tc.scheduledScalerDelete(old)\n\tc.scheduledScalerAdd(new)\n}", "func NewScheduledScalerController(\n\tinformerFactory informers.SharedInformerFactory,\n\trestdevClient clientset.Interface,\n\tkubeClient *kubernetes.Clientset,\n) *ScheduledScalerController {\n\tscheduledScalerInformer := informerFactory.Scaling().V1alpha1().ScheduledScalers()\n\tscheduledScalersLister := scheduledScalerInformer.Lister()\n\tvar scheduledScalerTargets []ScheduledScalerTarget\n\n\tc := &ScheduledScalerController{\n\t\tinformerFactory: informerFactory,\n\t\trestdevClient: restdevClient,\n\t\tkubeClient: kubeClient,\n\t\tscheduledScalersLister: scheduledScalersLister,\n\t\tscheduledScalersSynced: scheduledScalerInformer.Informer().HasSynced,\n\t\tscheduledScalerTargets: scheduledScalerTargets,\n\t}\n\tscheduledScalerInformer.Informer().AddEventHandler(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc: c.scheduledScalerAdd,\n\t\t\tUpdateFunc: c.scheduledScalerUpdate,\n\t\t\tDeleteFunc: c.scheduledScalerDelete,\n\t\t},\n\t)\n\treturn c\n}", "func (in *ChaosPodSpec) DeepCopy() *ChaosPodSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ChaosPodSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScaleSpec) DeepCopy() *ScaleSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SparkPodSpec) DeepCopy() *SparkPodSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SparkPodSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *TaskScheduleSpec) DeepCopy() *TaskScheduleSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TaskScheduleSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *NamespacedControllerResourceSpec) DeepCopy() *NamespacedControllerResourceSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(NamespacedControllerResourceSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WatermarkHorizontalPodAutoscalerSpec) DeepCopy() *WatermarkHorizontalPodAutoscalerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WatermarkHorizontalPodAutoscalerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AutoScalingSpec) DeepCopy() *AutoScalingSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AutoScalingSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SesActiveReceiptRuleSetSpec) DeepCopy() *SesActiveReceiptRuleSetSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SesActiveReceiptRuleSetSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func podScheduledState() *corev1.Pod {\n\treturn mustLoadPodRecording(podStatePath(\"scheduled\"))\n}", "func (in *DeploymentV1PodTemplateSpec) DeepCopy() *DeploymentV1PodTemplateSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DeploymentV1PodTemplateSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PodSpecWorkloadSpec) DeepCopy() *PodSpecWorkloadSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PodSpecWorkloadSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DeploymentV1Spec) DeepCopy() *DeploymentV1Spec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DeploymentV1Spec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DaemonsetsSpec) DeepCopy() *DaemonsetsSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DaemonsetsSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AgentSchedInfoSpec) DeepCopy() *AgentSchedInfoSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AgentSchedInfoSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PagerdutyRulesetSpec) DeepCopy() *PagerdutyRulesetSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PagerdutyRulesetSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SubscriptionSpec) DeepCopy() *SubscriptionSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubscriptionSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SubscriptionSpec) DeepCopy() *SubscriptionSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubscriptionSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func NewPodScheduling(ctx *pulumi.Context,\n\tname string, args *PodSchedulingArgs, opts ...pulumi.ResourceOption) (*PodScheduling, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Spec == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Spec'\")\n\t}\n\targs.ApiVersion = pulumi.StringPtr(\"resource.k8s.io/v1alpha1\")\n\targs.Kind = pulumi.StringPtr(\"PodScheduling\")\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource PodScheduling\n\terr := ctx.RegisterResource(\"kubernetes:resource.k8s.io/v1alpha1:PodScheduling\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (in *HorizontalPodAutoscaling) DeepCopy() *HorizontalPodAutoscaling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(HorizontalPodAutoscaling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SDSpec) DeepCopy() *SDSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SDSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o PgbenchSpecPodConfigOutput) PodScheduling() PgbenchSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v PgbenchSpecPodConfig) *PgbenchSpecPodConfigPodScheduling { return v.PodScheduling }).(PgbenchSpecPodConfigPodSchedulingPtrOutput)\n}", "func (in *ShadowPodSpec) DeepCopy() *ShadowPodSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ShadowPodSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PDSpec) DeepCopy() *PDSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PDSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (p PodSpec) Copy() interface{} {\n\tk8sP := k8sV1.Pod(p)\n\treturn PodSpec(*k8sP.DeepCopy())\n}", "func (o SysbenchSpecOutput) PodScheduling() SysbenchSpecPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v SysbenchSpec) *SysbenchSpecPodScheduling { return v.PodScheduling }).(SysbenchSpecPodSchedulingPtrOutput)\n}", "func (o DrillSpecPodConfigOutput) PodScheduling() DrillSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v DrillSpecPodConfig) *DrillSpecPodConfigPodScheduling { return v.PodScheduling }).(DrillSpecPodConfigPodSchedulingPtrOutput)\n}", "func (in *AWSManagedControlPlaneSpec) DeepCopy() *AWSManagedControlPlaneSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AWSManagedControlPlaneSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PolicySpec) DeepCopy() *PolicySpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PolicySpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PolicySpec) DeepCopy() *PolicySpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PolicySpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PolicySpec) DeepCopy() *PolicySpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PolicySpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AutoScheduling) DeepCopy() *AutoScheduling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AutoScheduling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingPolicyStatus) DeepCopy() *SchedulingPolicyStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingPolicyStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o QperfSpecServerConfigurationOutput) PodScheduling() QperfSpecServerConfigurationPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v QperfSpecServerConfiguration) *QperfSpecServerConfigurationPodScheduling {\n\t\treturn v.PodScheduling\n\t}).(QperfSpecServerConfigurationPodSchedulingPtrOutput)\n}", "func (in *PrometheusAdapterSpec) DeepCopy() *PrometheusAdapterSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PrometheusAdapterSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerSpec) DeepCopyInto(out *ScheduledPodScalerSpec) {\n\t*out = *in\n\tin.ScaleTarget.DeepCopyInto(&out.ScaleTarget)\n\tif in.ScaleRules != nil {\n\t\tin, out := &in.ScaleRules, &out.ScaleRules\n\t\t*out = make([]ScaleRule, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\tout.DefaultScaleSpec = in.DefaultScaleSpec\n}", "func (c *ScheduledScalerController) scheduledScalerAdd(obj interface{}) {\n\tscheduledScaler := obj.(*scalingv1alpha1.ScheduledScaler)\n\tif scheduledScaler.Spec.Target.Kind == \"HorizontalPodAutoscaler\" {\n\t\tc.scheduledScalerHpaCronAdd(obj)\n\t} else if scheduledScaler.Spec.Target.Kind == \"InstanceGroup\" {\n\t\tc.scheduledScalerIgCronAdd(obj)\n\t}\n}", "func (o QperfSpecClientConfigurationOutput) PodScheduling() QperfSpecClientConfigurationPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfiguration) *QperfSpecClientConfigurationPodScheduling {\n\t\treturn v.PodScheduling\n\t}).(QperfSpecClientConfigurationPodSchedulingPtrOutput)\n}", "func (o IopingSpecPodConfigOutput) PodScheduling() IopingSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfig) *IopingSpecPodConfigPodScheduling { return v.PodScheduling }).(IopingSpecPodConfigPodSchedulingPtrOutput)\n}", "func (in *SchedulerEnhancer) DeepCopy() *SchedulerEnhancer {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulerEnhancer)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PSPSpec) DeepCopy() *PSPSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PSPSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RedshiftEventSubscriptionSpec) DeepCopy() *RedshiftEventSubscriptionSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RedshiftEventSubscriptionSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledAction) DeepCopy() *ScheduledAction {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledAction)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *StatsSpec) DeepCopy() *StatsSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(StatsSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingPolicyList) DeepCopy() *SchedulingPolicyList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingPolicyList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ReaperSpec) DeepCopy() *ReaperSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ReaperSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o AutoscalingPolicyPtrOutput) ScalingSchedules() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *AutoscalingPolicy) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScalingSchedules\n\t}).(pulumi.StringMapOutput)\n}", "func (o BackendOutput) CapacityScaler() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v Backend) *float64 { return v.CapacityScaler }).(pulumi.Float64PtrOutput)\n}", "func (o PgbenchSpecPodConfigPtrOutput) PodScheduling() PgbenchSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v *PgbenchSpecPodConfig) *PgbenchSpecPodConfigPodScheduling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PodScheduling\n\t}).(PgbenchSpecPodConfigPodSchedulingPtrOutput)\n}", "func (in *CiliumBGPPeeringPolicySpec) DeepCopy() *CiliumBGPPeeringPolicySpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CiliumBGPPeeringPolicySpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o DrillSpecPodConfigPtrOutput) PodScheduling() DrillSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v *DrillSpecPodConfig) *DrillSpecPodConfigPodScheduling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PodScheduling\n\t}).(DrillSpecPodConfigPodSchedulingPtrOutput)\n}", "func (in *Schedule) DeepCopy() *Schedule {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(Schedule)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o QperfSpecClientConfigurationPtrOutput) PodScheduling() QperfSpecClientConfigurationPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v *QperfSpecClientConfiguration) *QperfSpecClientConfigurationPodScheduling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PodScheduling\n\t}).(QperfSpecClientConfigurationPodSchedulingPtrOutput)\n}", "func (o SysbenchSpecPtrOutput) PodScheduling() SysbenchSpecPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v *SysbenchSpec) *SysbenchSpecPodScheduling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PodScheduling\n\t}).(SysbenchSpecPodSchedulingPtrOutput)\n}", "func (o QperfSpecServerConfigurationPtrOutput) PodScheduling() QperfSpecServerConfigurationPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v *QperfSpecServerConfiguration) *QperfSpecServerConfigurationPodScheduling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PodScheduling\n\t}).(QperfSpecServerConfigurationPodSchedulingPtrOutput)\n}", "func (service *Service) ToPodSpec() (*v1.PodSpec, error) {\n\tresources, err := createResources(service)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpodSpec := &v1.PodSpec{\n\t\tContainers: []v1.Container{\n\t\t\t{\n\t\t\t\tName: ContainerName,\n\t\t\t\tImage: service.Image,\n\t\t\t\tEnv: convertEnvVars(service.Environment.Vars),\n\t\t\t\tVolumeMounts: []v1.VolumeMount{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: VolumeName,\n\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t\tMountPath: VolumePath,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tName: ConfigVolumeName,\n\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t\tMountPath: ConfigPath,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCommand: []string{\"/bin/sh\"},\n\t\t\t\tArgs: []string{\"-c\", fmt.Sprintf(\"%s/%s\", VolumePath, WatchdogName)},\n\t\t\t\tResources: resources,\n\t\t\t},\n\t\t},\n\t\tVolumes: []v1.Volume{\n\t\t\t{\n\t\t\t\tName: VolumeName,\n\t\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\t\tPersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{\n\t\t\t\t\t\tClaimName: PVCName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: ConfigVolumeName,\n\t\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\t\tConfigMap: &v1.ConfigMapVolumeSource{\n\t\t\t\t\t\tLocalObjectReference: v1.LocalObjectReference{\n\t\t\t\t\t\t\tName: service.Name,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t// Add the required environment variables for the watchdog\n\taddWatchdogEnvVars(podSpec)\n\n\treturn podSpec, nil\n}", "func (o AutoscalingPolicyResponsePtrOutput) ScalingSchedules() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *AutoscalingPolicyResponse) map[string]string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScalingSchedules\n\t}).(pulumi.StringMapOutput)\n}", "func (in *SecurityhubStandardsSubscriptionSpec) DeepCopy() *SecurityhubStandardsSubscriptionSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SecurityhubStandardsSubscriptionSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ManagerScheduleRequestSpec) DeepCopy() *ManagerScheduleRequestSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ManagerScheduleRequestSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (k *kubeScheduler) Schedule(pod api.Pod, unused algorithm.MinionLister) (string, error) {\n\tlog.Infof(\"Try to schedule pod %v\\n\", pod.Name)\n\tctx := api.WithNamespace(api.NewDefaultContext(), pod.Namespace)\n\n\t// default upstream scheduler passes pod.Name as binding.PodID\n\tpodKey, err := makePodKey(ctx, pod.Name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tk.api.Lock()\n\tdefer k.api.Unlock()\n\n\tif taskID, ok := k.api.taskForPod(podKey); !ok {\n\t\t// There's a bit of a potential race here, a pod could have been yielded() but\n\t\t// and then before we get *here* it could be deleted. We use meta to index the pod\n\t\t// in the store since that's what k8s client/cache/reflector does.\n\t\tmeta, err := meta.Accessor(&pod)\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"aborting Schedule, unable to understand pod object %+v\", &pod)\n\t\t\treturn \"\", noSuchPodErr\n\t\t}\n\t\tif deleted := k.podStore.Poll(meta.Name(), queue.DELETE_EVENT); deleted {\n\t\t\t// avoid scheduling a pod that's been deleted between yieldPod() and Schedule()\n\t\t\tlog.Infof(\"aborting Schedule, pod has been deleted %+v\", &pod)\n\t\t\treturn \"\", noSuchPodErr\n\t\t}\n\t\treturn k.doSchedule(k.api.registerPodTask(k.api.createPodTask(ctx, &pod)))\n\t} else {\n\t\tswitch task, state := k.api.getTask(taskID); state {\n\t\tcase statePending:\n\t\t\tif task.launched {\n\t\t\t\treturn \"\", fmt.Errorf(\"task %s has already been launched, aborting schedule\", taskID)\n\t\t\t} else {\n\t\t\t\treturn k.doSchedule(task, nil)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn \"\", fmt.Errorf(\"task %s is not pending, nothing to schedule\", taskID)\n\t\t}\n\t}\n}", "func (in *ScalableTargetSpec) DeepCopy() *ScalableTargetSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalableTargetSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PodSpecWorkload) DeepCopy() *PodSpecWorkload {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PodSpecWorkload)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *FlexibleServers_FirewallRule_Spec) DeepCopy() *FlexibleServers_FirewallRule_Spec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(FlexibleServers_FirewallRule_Spec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o AutoscalingPolicyOutput) ScalingSchedules() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v AutoscalingPolicy) map[string]string { return v.ScalingSchedules }).(pulumi.StringMapOutput)\n}", "func (in *PrometheusSpec) DeepCopy() *PrometheusSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PrometheusSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PrometheusSpec) DeepCopy() *PrometheusSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PrometheusSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PrometheusSpec) DeepCopy() *PrometheusSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PrometheusSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DopplerSecretSpec) DeepCopy() *DopplerSecretSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DopplerSecretSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PodSpecWorkloadStatus) DeepCopy() *PodSpecWorkloadStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PodSpecWorkloadStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o FioSpecPodConfigOutput) PodScheduling() FioSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v FioSpecPodConfig) *FioSpecPodConfigPodScheduling { return v.PodScheduling }).(FioSpecPodConfigPodSchedulingPtrOutput)\n}", "func (in *ServingRuntimeSpec) DeepCopy() *ServingRuntimeSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServingRuntimeSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o IopingSpecPodConfigPtrOutput) PodScheduling() IopingSpecPodConfigPodSchedulingPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecPodConfig) *IopingSpecPodConfigPodScheduling {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PodScheduling\n\t}).(IopingSpecPodConfigPodSchedulingPtrOutput)\n}", "func (in *MetricsSpec) DeepCopy() *MetricsSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MetricsSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *CPUProfileSpec) DeepCopy() *CPUProfileSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CPUProfileSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AzurePipelinesPoolSpec) DeepCopy() *AzurePipelinesPoolSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AzurePipelinesPoolSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o ResourcePolicySnapshotSchedulePolicyOutput) Schedule() ResourcePolicySnapshotSchedulePolicySchedulePtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicySnapshotSchedulePolicy) *ResourcePolicySnapshotSchedulePolicySchedule {\n\t\treturn v.Schedule\n\t}).(ResourcePolicySnapshotSchedulePolicySchedulePtrOutput)\n}", "func (in *SubscriberSpec) DeepCopy() *SubscriberSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubscriberSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o AutoscalingPolicyResponseOutput) ScalingSchedules() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v AutoscalingPolicyResponse) map[string]string { return v.ScalingSchedules }).(pulumi.StringMapOutput)\n}", "func (in *RemoteShuffleServiceSpec) DeepCopy() *RemoteShuffleServiceSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RemoteShuffleServiceSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}" ]
[ "0.7813591", "0.68805146", "0.65664226", "0.64651406", "0.61906093", "0.6134313", "0.6045399", "0.5950982", "0.57670134", "0.5747594", "0.57069665", "0.547154", "0.5444904", "0.536201", "0.53037184", "0.528185", "0.52285314", "0.52279866", "0.52279866", "0.50915116", "0.50893927", "0.5083176", "0.5042375", "0.50009793", "0.49230897", "0.49193713", "0.49036387", "0.48767197", "0.4836483", "0.47927105", "0.47747782", "0.47546914", "0.47518107", "0.47511575", "0.4744606", "0.47390416", "0.4737895", "0.4716947", "0.4716947", "0.47105598", "0.46998715", "0.46946222", "0.46918687", "0.4674303", "0.46735692", "0.46669596", "0.4665408", "0.46595794", "0.4642597", "0.4635391", "0.4635391", "0.4635391", "0.46325213", "0.46320015", "0.46108812", "0.46054903", "0.4599369", "0.45927545", "0.45758507", "0.45611116", "0.4556743", "0.45525926", "0.45413584", "0.45225728", "0.4514213", "0.45079017", "0.45074233", "0.45068926", "0.45011032", "0.4499871", "0.44963202", "0.44915897", "0.4490127", "0.4489496", "0.44810995", "0.44760257", "0.4471643", "0.44549206", "0.4441746", "0.44345486", "0.4432497", "0.44321835", "0.4431931", "0.4421804", "0.4421588", "0.44171828", "0.44171828", "0.44171828", "0.44154954", "0.44125763", "0.44051722", "0.4401778", "0.43971583", "0.43962488", "0.4395811", "0.4386472", "0.43847167", "0.43827298", "0.4382326", "0.43816206" ]
0.8583529
0
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be nonnil.
func (in *ScheduledPodScalerStatus) DeepCopyInto(out *ScheduledPodScalerStatus) { *out = *in }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *RunInfo) DeepCopyInto(out *RunInfo) {\n\t*out = *r\n}", "func (in *Base) DeepCopyInto(out *Base) {\n\t*out = *in\n\treturn\n}", "func (in *ForkObject) DeepCopyInto(out *ForkObject) {\n\t*out = *in\n}", "func (in *TargetObjectInfo) DeepCopyInto(out *TargetObjectInfo) {\n\t*out = *in\n}", "func (in *DebugObjectInfo) DeepCopyInto(out *DebugObjectInfo) {\n\t*out = *in\n}", "func (in *Input) DeepCopyInto(out *Input) {\n\t*out = *in\n}", "func (u *SSN) DeepCopyInto(out *SSN) {\n\t*out = *u\n}", "func (in *ExistPvc) DeepCopyInto(out *ExistPvc) {\n\t*out = *in\n}", "func (in *DockerStep) DeepCopyInto(out *DockerStep) {\n\t*out = *in\n\tif in.Inline != nil {\n\t\tin, out := &in.Inline, &out.Inline\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tout.Auth = in.Auth\n\treturn\n}", "func (in *Container) DeepCopyInto(out *Container) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.Command != nil {\n\t\tin, out := &in.Command, &out.Command\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.LifeCycleScript != nil {\n\t\tin, out := &in.LifeCycleScript, &out.LifeCycleScript\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *RuntimeRef) DeepCopyInto(out *RuntimeRef) {\n\t*out = *in\n}", "func (in *Ibft2) DeepCopyInto(out *Ibft2) {\n\t*out = *in\n\treturn\n}", "func (in *TestResult) DeepCopyInto(out *TestResult) {\n\t*out = *in\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectRef) DeepCopyInto(out *ObjectRef) {\n\t*out = *in\n\treturn\n}", "func (in *Haproxy) DeepCopyInto(out *Haproxy) {\n\t*out = *in\n\treturn\n}", "func (in *SSH) DeepCopyInto(out *SSH) {\n\t*out = *in\n\treturn\n}", "func (in *Runtime) DeepCopyInto(out *Runtime) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n}", "func (b *Base64) DeepCopyInto(out *Base64) {\n\t*out = *b\n}", "func (in *EventDependencyTransformer) DeepCopyInto(out *EventDependencyTransformer) {\n\t*out = *in\n\treturn\n}", "func (in *StageOutput) DeepCopyInto(out *StageOutput) {\n\t*out = *in\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *ObjectReference) DeepCopyInto(out *ObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Dependent) DeepCopyInto(out *Dependent) {\n\t*out = *in\n\treturn\n}", "func (in *GitFileGeneratorItem) DeepCopyInto(out *GitFileGeneratorItem) {\n\t*out = *in\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *CrossVersionObjectReference) DeepCopyInto(out *CrossVersionObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *AnsibleStep) DeepCopyInto(out *AnsibleStep) {\n\t*out = *in\n\treturn\n}", "func (in *Forks) DeepCopyInto(out *Forks) {\n\t*out = *in\n\tif in.DAO != nil {\n\t\tin, out := &in.DAO, &out.DAO\n\t\t*out = new(uint)\n\t\t**out = **in\n\t}\n}", "func (in *ContainerPort) DeepCopyInto(out *ContainerPort) {\n\t*out = *in\n}", "func (in *General) DeepCopyInto(out *General) {\n\t*out = *in\n\treturn\n}", "func (in *IsoContainer) DeepCopyInto(out *IsoContainer) {\n\t*out = *in\n}", "func (in *Git) DeepCopyInto(out *Git) {\n\t*out = *in\n\treturn\n}", "func (in *ConfigFile) DeepCopyInto(out *ConfigFile) {\n\t*out = *in\n}", "func (in *BackupProgress) DeepCopyInto(out *BackupProgress) {\n\t*out = *in\n}", "func (in *DataDisk) DeepCopyInto(out *DataDisk) {\n\t*out = *in\n}", "func (in *PhaseStep) DeepCopyInto(out *PhaseStep) {\n\t*out = *in\n}", "func (u *MAC) DeepCopyInto(out *MAC) {\n\t*out = *u\n}", "func (in *Variable) DeepCopyInto(out *Variable) {\n\t*out = *in\n}", "func (in *RestoreProgress) DeepCopyInto(out *RestoreProgress) {\n\t*out = *in\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *DataExportObjectReference) DeepCopyInto(out *DataExportObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *NamespacedObjectReference) DeepCopyInto(out *NamespacedObjectReference) {\n\t*out = *in\n\treturn\n}", "func (in *Path) DeepCopyInto(out *Path) {\n\t*out = *in\n\treturn\n}", "func (in *GitDirectoryGeneratorItem) DeepCopyInto(out *GitDirectoryGeneratorItem) {\n\t*out = *in\n}", "func (in *NamePath) DeepCopyInto(out *NamePath) {\n\t*out = *in\n\treturn\n}", "func (in *ConsoleCreateObj) DeepCopyInto(out *ConsoleCreateObj) {\n\t*out = *in\n}", "func (in *UsedPipelineRun) DeepCopyInto(out *UsedPipelineRun) {\n\t*out = *in\n}", "func (in *BuildTemplate) DeepCopyInto(out *BuildTemplate) {\n\t*out = *in\n\tif in.Cmd != nil {\n\t\tin, out := &in.Cmd, &out.Cmd\n\t\t*out = make([]BuildTemplateStep, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n}", "func (in *ObjectInfo) DeepCopyInto(out *ObjectInfo) {\n\t*out = *in\n\tout.GroupVersionKind = in.GroupVersionKind\n\treturn\n}", "func (in *Files) DeepCopyInto(out *Files) {\n\t*out = *in\n}", "func (in *Source) DeepCopyInto(out *Source) {\n\t*out = *in\n\tif in.Dependencies != nil {\n\t\tin, out := &in.Dependencies, &out.Dependencies\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MavenRepositories != nil {\n\t\tin, out := &in.MavenRepositories, &out.MavenRepositories\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\treturn\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *Port) DeepCopyInto(out *Port) {\n\t*out = *in\n}", "func (in *StackBuild) DeepCopyInto(out *StackBuild) {\n\t*out = *in\n\treturn\n}", "func (in *BuildTaskRef) DeepCopyInto(out *BuildTaskRef) {\n\t*out = *in\n\treturn\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *Disk) DeepCopyInto(out *Disk) {\n\t*out = *in\n}", "func (in *PathInfo) DeepCopyInto(out *PathInfo) {\n\t*out = *in\n}", "func (in *PoA) DeepCopyInto(out *PoA) {\n\t*out = *in\n}", "func (in *Section) DeepCopyInto(out *Section) {\n\t*out = *in\n\tif in.SecretRefs != nil {\n\t\tin, out := &in.SecretRefs, &out.SecretRefs\n\t\t*out = make([]SecretReference, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Files != nil {\n\t\tin, out := &in.Files, &out.Files\n\t\t*out = make([]FileMount, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n}", "func (in *DNSSelection) DeepCopyInto(out *DNSSelection) {\n\t*out = *in\n\tif in.Include != nil {\n\t\tin, out := &in.Include, &out.Include\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Exclude != nil {\n\t\tin, out := &in.Exclude, &out.Exclude\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ReleaseVersion) DeepCopyInto(out *ReleaseVersion) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Image) DeepCopyInto(out *Image) {\n\t*out = *in\n\treturn\n}", "func (in *Command) DeepCopyInto(out *Command) {\n\t*out = *in\n\tif in.Flags != nil {\n\t\tin, out := &in.Flags, &out.Flags\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.Value != nil {\n\t\tin, out := &in.Value, &out.Value\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *PathRule) DeepCopyInto(out *PathRule) {\n\t*out = *in\n\treturn\n}", "func (in *DockerLifecycleData) DeepCopyInto(out *DockerLifecycleData) {\n\t*out = *in\n}", "func (in *RunScriptStepConfig) DeepCopyInto(out *RunScriptStepConfig) {\n\t*out = *in\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *Checksum) DeepCopyInto(out *Checksum) {\n\t*out = *in\n}", "func (in *DomainNameOutput) DeepCopyInto(out *DomainNameOutput) {\n\t*out = *in\n}", "func (in *InterfaceStruct) DeepCopyInto(out *InterfaceStruct) {\n\t*out = *in\n\tif in.val != nil {\n\t\tin, out := &in.val, &out.val\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n}", "func (in *Ref) DeepCopyInto(out *Ref) {\n\t*out = *in\n}", "func (in *MemorySpec) DeepCopyInto(out *MemorySpec) {\n\t*out = *in\n}", "func (in *BuildJenkinsInfo) DeepCopyInto(out *BuildJenkinsInfo) {\n\t*out = *in\n\treturn\n}", "func (in *VirtualDatabaseBuildObject) DeepCopyInto(out *VirtualDatabaseBuildObject) {\n\t*out = *in\n\tif in.Incremental != nil {\n\t\tin, out := &in.Incremental, &out.Incremental\n\t\t*out = new(bool)\n\t\t**out = **in\n\t}\n\tif in.Env != nil {\n\t\tin, out := &in.Env, &out.Env\n\t\t*out = make([]v1.EnvVar, len(*in))\n\t\tfor i := range *in {\n\t\t\t(*in)[i].DeepCopyInto(&(*out)[i])\n\t\t}\n\t}\n\tout.Git = in.Git\n\tin.Source.DeepCopyInto(&out.Source)\n\tif in.Webhooks != nil {\n\t\tin, out := &in.Webhooks, &out.Webhooks\n\t\t*out = make([]WebhookSecret, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *MaintenanceInfo) DeepCopyInto(out *MaintenanceInfo) {\n\t*out = *in\n\treturn\n}", "func (in *KopsNode) DeepCopyInto(out *KopsNode) {\n\t*out = *in\n\treturn\n}", "func (in *FalconAPI) DeepCopyInto(out *FalconAPI) {\n\t*out = *in\n}", "func (in *EBS) DeepCopyInto(out *EBS) {\n\t*out = *in\n}", "func (in *Target) DeepCopyInto(out *Target) {\n\t*out = *in\n\treturn\n}", "func (in *Empty) DeepCopyInto(out *Empty) {\n\t*out = *in\n\tout.XXX_NoUnkeyedLiteral = in.XXX_NoUnkeyedLiteral\n\tif in.XXX_unrecognized != nil {\n\t\tin, out := &in.XXX_unrecognized, &out.XXX_unrecognized\n\t\t*out = make([]byte, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\treturn\n}", "func (in *ComponentDistGit) DeepCopyInto(out *ComponentDistGit) {\n\t*out = *in\n\treturn\n}", "func (in *Memory) DeepCopyInto(out *Memory) {\n\t*out = *in\n\tout.Required = in.Required.DeepCopy()\n}", "func (in *Persistence) DeepCopyInto(out *Persistence) {\n\t*out = *in\n\tout.Size = in.Size.DeepCopy()\n\treturn\n}", "func (in *ManagedDisk) DeepCopyInto(out *ManagedDisk) {\n\t*out = *in\n}", "func (e *Email) DeepCopyInto(out *Email) {\n\t*out = *e\n}", "func (in *ImageInfo) DeepCopyInto(out *ImageInfo) {\n\t*out = *in\n}", "func (in *ShootRef) DeepCopyInto(out *ShootRef) {\n\t*out = *in\n}", "func (in *N3000Fpga) DeepCopyInto(out *N3000Fpga) {\n\t*out = *in\n}", "func (in *NetflowType) DeepCopyInto(out *NetflowType) {\n\t*out = *in\n\treturn\n}", "func (in *BuiltInAdapter) DeepCopyInto(out *BuiltInAdapter) {\n\t*out = *in\n}", "func (in *Node) DeepCopyInto(out *Node) {\n\t*out = *in\n\tif in.FailStatus != nil {\n\t\tin, out := &in.FailStatus, &out.FailStatus\n\t\t*out = make([]string, len(*in))\n\t\tcopy(*out, *in)\n\t}\n\tif in.MigratingSlots != nil {\n\t\tin, out := &in.MigratingSlots, &out.MigratingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n\tif in.ImportingSlots != nil {\n\t\tin, out := &in.ImportingSlots, &out.ImportingSlots\n\t\t*out = make(map[string]string, len(*in))\n\t\tfor key, val := range *in {\n\t\t\t(*out)[key] = val\n\t\t}\n\t}\n}", "func (in *CPUSpec) DeepCopyInto(out *CPUSpec) {\n\t*out = *in\n}", "func (in *LoopState) DeepCopyInto(out *LoopState) {\n\t*out = *in\n}" ]
[ "0.8215289", "0.81280124", "0.81039286", "0.80862963", "0.8083811", "0.80673146", "0.8064545", "0.8026454", "0.8012046", "0.7996313", "0.799204", "0.79887754", "0.7987097", "0.7986994", "0.7986994", "0.79854053", "0.7975989", "0.7972486", "0.79695636", "0.79695636", "0.79695636", "0.7967528", "0.79624444", "0.7961954", "0.7945754", "0.7945754", "0.7944541", "0.79428566", "0.7942668", "0.7942668", "0.7940451", "0.793851", "0.7936731", "0.79294837", "0.79252166", "0.7915377", "0.7911627", "0.7911138", "0.7909384", "0.790913", "0.7908773", "0.7905649", "0.79050326", "0.7904594", "0.7904594", "0.7904235", "0.79036915", "0.79020816", "0.78988886", "0.78977424", "0.7891376", "0.7891024", "0.7889831", "0.78890276", "0.7887135", "0.788637", "0.7885264", "0.7885264", "0.7884786", "0.7880785", "0.78745943", "0.78745943", "0.78745407", "0.78734446", "0.78724426", "0.78713626", "0.78713554", "0.78652424", "0.7863321", "0.7863321", "0.7863321", "0.7863293", "0.7862628", "0.7860664", "0.7858556", "0.785785", "0.78571486", "0.7851332", "0.78453225", "0.78448987", "0.78415996", "0.7837483", "0.7837037", "0.7836443", "0.78351796", "0.78329664", "0.7831094", "0.7829445", "0.7826582", "0.7824499", "0.78242797", "0.78227437", "0.78192484", "0.7818843", "0.78128535", "0.7812535", "0.78111476", "0.78111106", "0.781107", "0.78093034", "0.7808775" ]
0.0
-1
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ScheduledPodScalerStatus.
func (in *ScheduledPodScalerStatus) DeepCopy() *ScheduledPodScalerStatus { if in == nil { return nil } out := new(ScheduledPodScalerStatus) in.DeepCopyInto(out) return out }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (in *SchedulingScalerStatus) DeepCopy() *SchedulingScalerStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScaler) DeepCopy() *ScheduledPodScaler {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScaler)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingPolicyStatus) DeepCopy() *SchedulingPolicyStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingPolicyStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScalingPolicyStatus) DeepCopy() *ScalingPolicyStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalingPolicyStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerList) DeepCopy() *ScheduledPodScalerList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScalerList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulerEnhancerStatus) DeepCopy() *SchedulerEnhancerStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulerEnhancerStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledSparkApplicationStatus) DeepCopy() *ScheduledSparkApplicationStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledSparkApplicationStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WatermarkHorizontalPodAutoscalerStatus) DeepCopy() *WatermarkHorizontalPodAutoscalerStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WatermarkHorizontalPodAutoscalerStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduledPodScalerSpec) DeepCopy() *ScheduledPodScalerSpec {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduledPodScalerSpec)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScheduleStatus) DeepCopy() *ScheduleStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScheduleStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *TaskScheduleStatus) DeepCopy() *TaskScheduleStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TaskScheduleStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RegistrationServiceResourcesStatus) DeepCopy() *RegistrationServiceResourcesStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RegistrationServiceResourcesStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AutoscalingRuleStatus) DeepCopy() *AutoscalingRuleStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AutoscalingRuleStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PagerdutyRulesetStatus) DeepCopy() *PagerdutyRulesetStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PagerdutyRulesetStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SimpleRolloutTraitStatus) DeepCopy() *SimpleRolloutTraitStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SimpleRolloutTraitStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AgentSchedInfoStatus) DeepCopy() *AgentSchedInfoStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AgentSchedInfoStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ReaperStatus) DeepCopy() *ReaperStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ReaperStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SequenceSubscriptionStatus) DeepCopy() *SequenceSubscriptionStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SequenceSubscriptionStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ChaosPodStatus) DeepCopy() *ChaosPodStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ChaosPodStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScaleStatus) DeepCopy() *ScaleStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScaleStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *TaskLoopRunStatus) DeepCopy() *TaskLoopRunStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TaskLoopRunStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *NamespacedControllerResourceStatus) DeepCopy() *NamespacedControllerResourceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(NamespacedControllerResourceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PagerdutyServiceStatus) DeepCopy() *PagerdutyServiceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PagerdutyServiceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ScalableTargetStatus) DeepCopy() *ScalableTargetStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ScalableTargetStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RegistrationServiceDeploymentStatus) DeepCopy() *RegistrationServiceDeploymentStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RegistrationServiceDeploymentStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ManagerScheduleRequestStatus) DeepCopy() *ManagerScheduleRequestStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ManagerScheduleRequestStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScaler) DeepCopy() *SchedulingScaler {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScaler)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *TaskLoopTaskRunStatus) DeepCopy() *TaskLoopTaskRunStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TaskLoopTaskRunStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PodStatus) DeepCopy() *PodStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PodStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PipelineRunStatus) DeepCopy() *PipelineRunStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PipelineRunStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SesActiveReceiptRuleSetStatus) DeepCopy() *SesActiveReceiptRuleSetStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SesActiveReceiptRuleSetStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SecurityhubStandardsSubscriptionStatus) DeepCopy() *SecurityhubStandardsSubscriptionStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SecurityhubStandardsSubscriptionStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SidekickStatus) DeepCopy() *SidekickStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SidekickStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *MobileSecurityServiceStatus) DeepCopy() *MobileSecurityServiceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MobileSecurityServiceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func podScheduledState() *corev1.Pod {\n\treturn mustLoadPodRecording(podStatePath(\"scheduled\"))\n}", "func (in *RemoteShuffleServiceStatus) DeepCopy() *RemoteShuffleServiceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RemoteShuffleServiceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RolloutAnalysisRunStatus) DeepCopy() *RolloutAnalysisRunStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RolloutAnalysisRunStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RolloutStatus) DeepCopy() *RolloutStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RolloutStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RolloutStatus) DeepCopy() *RolloutStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RolloutStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RpaasPlanStatus) DeepCopy() *RpaasPlanStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RpaasPlanStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *EmsSubscriptionStatus) DeepCopy() *EmsSubscriptionStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(EmsSubscriptionStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *MongoServiceStatus) DeepCopy() *MongoServiceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MongoServiceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DiscoveryServiceCertificateStatus) DeepCopy() *DiscoveryServiceCertificateStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiscoveryServiceCertificateStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *TaskScheduleStatusFields) DeepCopy() *TaskScheduleStatusFields {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TaskScheduleStatusFields)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *BpfdnsStatus) DeepCopy() *BpfdnsStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(BpfdnsStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ShadowPodStatus) DeepCopy() *ShadowPodStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ShadowPodStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *CatalogServiceClaimStatus) DeepCopy() *CatalogServiceClaimStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CatalogServiceClaimStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ResourceSigningProfileStatus) DeepCopy() *ResourceSigningProfileStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ResourceSigningProfileStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DopplerSecretStatus) DeepCopy() *DopplerSecretStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DopplerSecretStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PoolStatus) DeepCopy() *PoolStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PoolStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PoolStatus) DeepCopy() *PoolStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PoolStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PoolStatus) DeepCopy() *PoolStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PoolStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PoolStatus) DeepCopy() *PoolStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PoolStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PodSpecWorkloadStatus) DeepCopy() *PodSpecWorkloadStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PodSpecWorkloadStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *VpDeploymentRunningStatus) DeepCopy() *VpDeploymentRunningStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(VpDeploymentRunningStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ServingRuntimeStatus) DeepCopy() *ServingRuntimeStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ServingRuntimeStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SchedulingScalerList) DeepCopy() *SchedulingScalerList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SchedulingScalerList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DnsresolverSubResource_STATUS) DeepCopy() *DnsresolverSubResource_STATUS {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DnsresolverSubResource_STATUS)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *MobileSecurityServiceDBStatus) DeepCopy() *MobileSecurityServiceDBStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(MobileSecurityServiceDBStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DebugRuleEvaluationStatus) DeepCopy() *DebugRuleEvaluationStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DebugRuleEvaluationStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PolicyStatus) DeepCopy() *PolicyStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PolicyStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PolicyStatus) DeepCopy() *PolicyStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PolicyStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *StreamProcessorStatus) DeepCopy() *StreamProcessorStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(StreamProcessorStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RedpandaStatus) DeepCopy() *RedpandaStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RedpandaStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RedshiftEventSubscriptionStatus) DeepCopy() *RedshiftEventSubscriptionStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RedshiftEventSubscriptionStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *BcsDaemonsetStatus) DeepCopy() *BcsDaemonsetStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(BcsDaemonsetStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (o RegionAutoscalerOutput) ScalingScheduleStatus() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *RegionAutoscaler) pulumi.StringMapOutput { return v.ScalingScheduleStatus }).(pulumi.StringMapOutput)\n}", "func (in *SDStatus) DeepCopy() *SDStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SDStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SSMParameterStatus) DeepCopy() *SSMParameterStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SSMParameterStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SippScenarioRunStatus) DeepCopy() *SippScenarioRunStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SippScenarioRunStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WorkflowRunStatus) DeepCopy() *WorkflowRunStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WorkflowRunStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SensuEventFilterStatus) DeepCopy() *SensuEventFilterStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SensuEventFilterStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *EKSPodIdentityWebhookStatus) DeepCopy() *EKSPodIdentityWebhookStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(EKSPodIdentityWebhookStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DnsresolverSubResource_STATUS_ARM) DeepCopy() *DnsresolverSubResource_STATUS_ARM {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DnsresolverSubResource_STATUS_ARM)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *KMSIssuerStatus) DeepCopy() *KMSIssuerStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(KMSIssuerStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AutoscalingRuleMetricValueStatus) DeepCopy() *AutoscalingRuleMetricValueStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AutoscalingRuleMetricValueStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SubscriptionStatus) DeepCopy() *SubscriptionStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubscriptionStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SubscriptionStatus) DeepCopy() *SubscriptionStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SubscriptionStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ChoiceSubscriptionStatus) DeepCopy() *ChoiceSubscriptionStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ChoiceSubscriptionStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ElasticsearchDataSetStatus) DeepCopy() *ElasticsearchDataSetStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ElasticsearchDataSetStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *WordpressInstanceStatus) DeepCopy() *WordpressInstanceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(WordpressInstanceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AppServiceStatus) DeepCopy() *AppServiceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AppServiceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *UserPoolStatus) DeepCopy() *UserPoolStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(UserPoolStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *StatusClusterScaling) DeepCopy() *StatusClusterScaling {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(StatusClusterScaling)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *TemplatedSecretStatus) DeepCopy() *TemplatedSecretStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(TemplatedSecretStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *FlexibleServers_FirewallRule_STATUS) DeepCopy() *FlexibleServers_FirewallRule_STATUS {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(FlexibleServers_FirewallRule_STATUS)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *AutoscalingGroupStatus) DeepCopy() *AutoscalingGroupStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(AutoscalingGroupStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RunnableStatus) DeepCopy() *RunnableStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RunnableStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DiscoveryServiceStatus) DeepCopy() *DiscoveryServiceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DiscoveryServiceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *StatusPolicy) DeepCopy() *StatusPolicy {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(StatusPolicy)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RPMComposeStatus) DeepCopy() *RPMComposeStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RPMComposeStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RunnerStatus) DeepCopy() *RunnerStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RunnerStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *PodmigrationStatus) DeepCopy() *PodmigrationStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(PodmigrationStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *CiliumLoadBalancerIPPoolStatus) DeepCopy() *CiliumLoadBalancerIPPoolStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(CiliumLoadBalancerIPPoolStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *RpaasInstanceStatus) DeepCopy() *RpaasInstanceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RpaasInstanceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *DnsForwardingRulesetProperties_STATUS_ARM) DeepCopy() *DnsForwardingRulesetProperties_STATUS_ARM {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(DnsForwardingRulesetProperties_STATUS_ARM)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *KubeEventsRuleStatus) DeepCopy() *KubeEventsRuleStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(KubeEventsRuleStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *NetflowPolicyStatus) DeepCopy() *NetflowPolicyStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(NetflowPolicyStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *ArgusWatcherStatus) DeepCopy() *ArgusWatcherStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(ArgusWatcherStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (in *SequenceStatus) DeepCopy() *SequenceStatus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(SequenceStatus)\n\tin.DeepCopyInto(out)\n\treturn out\n}" ]
[ "0.798133", "0.75455487", "0.6869868", "0.6523821", "0.640999", "0.626312", "0.62318623", "0.6178982", "0.61479557", "0.6132582", "0.61129105", "0.5976912", "0.58940923", "0.58825886", "0.5867689", "0.5855375", "0.5833105", "0.5830422", "0.5802052", "0.5787193", "0.57713723", "0.57661945", "0.57516104", "0.57203305", "0.57199156", "0.5719375", "0.5709413", "0.57076895", "0.57043636", "0.5677548", "0.5676527", "0.56715924", "0.5671138", "0.5624802", "0.5621547", "0.5616956", "0.55934185", "0.5555984", "0.5555984", "0.5549341", "0.5521333", "0.5519816", "0.5501809", "0.5501764", "0.54981256", "0.5492807", "0.5486921", "0.54853487", "0.5485128", "0.5484403", "0.5484403", "0.5484403", "0.5484403", "0.548341", "0.54797226", "0.54686815", "0.54602176", "0.54563427", "0.5455439", "0.5453663", "0.54402536", "0.54402536", "0.542887", "0.54206413", "0.5414849", "0.54109246", "0.5395593", "0.53953874", "0.5394521", "0.5369808", "0.53687763", "0.5364794", "0.5354543", "0.5348313", "0.53481996", "0.5347426", "0.5346286", "0.5346286", "0.5335496", "0.53168184", "0.53154", "0.531183", "0.5311293", "0.5310152", "0.5308208", "0.53000903", "0.5296906", "0.5291071", "0.52722603", "0.5269035", "0.5268843", "0.5260799", "0.52577794", "0.5257412", "0.525349", "0.5253439", "0.5243111", "0.5237541", "0.5234834", "0.52298087" ]
0.86013246
0
PodmanImage provides access to an image reference from podman. same as github.com/google/gocontainerregistry/pkg/v1/daemon
func PodmanImage(ref name.Reference, options ...interface{}) (v1.Image, error) { var img v1.Image pr, pw := io.Pipe() go func() { opener := func() (io.ReadCloser, error) { return pr, nil } var err error tag := ref.(name.Digest).Tag() img, err = tarball.Image(opener, &tag) _ = pr.CloseWithError(err) }() // write the image in docker save format first, then load it cmd := exec.Command("sudo", "podman", "image", "save", strings.Split(ref.Name(), "@")[0]) cmd.Stdout = pw err := cmd.Run() if err != nil { return nil, fmt.Errorf("error loading image: %v", err) } return img, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *FakeRunner) podman(args []string, _ bool) (string, error) {\n\tswitch cmd := args[0]; cmd {\n\tcase \"--version\":\n\t\treturn \"podman version 1.6.4\", nil\n\n\tcase \"image\":\n\n\t\tif args[1] == \"inspect\" && args[2] == \"--format\" && args[3] == \"{{.Id}}\" {\n\t\t\tif args[3] == \"missing\" {\n\t\t\t\treturn \"\", &exec.ExitError{Stderr: []byte(\"Error: error getting image \\\"missing\\\": unable to find a name and tag match for missing in repotags: no such image\")}\n\t\t\t}\n\t\t\treturn \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\", nil\n\t\t}\n\n\t}\n\treturn \"\", nil\n}", "func PodmanWrite(ref name.Reference, img v1.Image, opts ...tarball.WriteOption) (string, error) {\n\tpr, pw := io.Pipe()\n\tgo func() {\n\t\t_ = pw.CloseWithError(tarball.Write(ref, img, pw, opts...))\n\t}()\n\n\t// write the image in docker save format first, then load it\n\tcmd := exec.Command(\"sudo\", \"podman\", \"image\", \"load\")\n\tcmd.Stdin = pr\n\toutput, err := cmd.Output()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error loading image: %v\", err)\n\t}\n\t// pull the image from the registry, to get the digest too\n\t// podman: \"Docker references with both a tag and digest are currently not supported\"\n\tcmd = exec.Command(\"sudo\", \"podman\", \"image\", \"pull\", strings.Split(ref.Name(), \"@\")[0])\n\terr = cmd.Run()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error pulling image: %v\", err)\n\t}\n\treturn string(output), nil\n}", "func PullImage(\n\tctx context.Context,\n\treq docker.PullImage,\n\tp events.Publisher[docker.Event],\n\twg *waitgroupx.Group,\n\tlog *logrus.Entry,\n\tgetPullCommand func(docker.PullImage, string) (string, []string),\n) (err error) {\n\tif err = p.Publish(ctx, docker.NewBeginStatsEvent(docker.ImagePullStatsKind)); err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err = p.Publish(ctx, docker.NewEndStatsEvent(docker.ImagePullStatsKind)); err != nil {\n\t\t\tlog.WithError(err).Warn(\"did not send image pull done stats\")\n\t\t}\n\t}()\n\n\timage := CanonicalizeImage(req.Name)\n\n\turi, err := url.Parse(image)\n\tif err != nil || uri.Scheme == \"\" {\n\t\tif err = p.Publish(ctx, docker.NewLogEvent(\n\t\t\tmodel.LogLevelInfo,\n\t\t\tfmt.Sprintf(\"image %s isn't a pullable URI; skipping pull\", image),\n\t\t)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t// TODO(DET-9078): Support registry auth. Investigate other auth mechanisms\n\t// with singularity & podman.\n\tcommand, args := getPullCommand(req, image)\n\n\tif err = PprintCommand(ctx, command, args, p, log); err != nil {\n\t\treturn err\n\t}\n\n\tcmd := exec.CommandContext(ctx, command, args...) // #nosec G204 'command' is under our control\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating stdout pipe: %w\", err)\n\t}\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating stderr pipe: %w\", err)\n\t}\n\n\t// The return codes from `podman pull` aren't super helpful in determining the error, so we\n\t// wrap the publisher and skim logs to see what happened as we ship them.\n\tignoreErrorsSig := make(chan bool)\n\tcheckIgnoreErrors := events.FuncPublisher[docker.Event](\n\t\tfunc(ctx context.Context, t docker.Event) error {\n\t\t\tif t.Log != nil && strings.Contains(t.Log.Message, \"Image file already exists\") {\n\t\t\t\tignoreErrorsSig <- true\n\t\t\t}\n\t\t\treturn p.Publish(ctx, t)\n\t\t},\n\t)\n\twg.Go(func(ctx context.Context) { ShipContainerCommandLogs(ctx, stdout, stdcopy.Stdout, p) })\n\twg.Go(func(ctx context.Context) {\n\t\tdefer close(ignoreErrorsSig)\n\t\tShipContainerCommandLogs(ctx, stderr, stdcopy.Stderr, checkIgnoreErrors)\n\t})\n\n\tif err = cmd.Start(); err != nil {\n\t\treturn fmt.Errorf(\"starting pull command: %w\", err)\n\t}\n\n\tvar ignoreErrors bool\n\tselect {\n\tcase ignoreErrors = <-ignoreErrorsSig:\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\n\tif err = cmd.Wait(); err != nil && !ignoreErrors {\n\t\treturn fmt.Errorf(\"pulling %s: %w\", image, err)\n\t}\n\treturn nil\n}", "func (daemon *Daemon) ImageService() ImageService {\n\treturn daemon.imageService\n}", "func componentImage(name string, v semver.Version, mirror string) string {\n\treturn fmt.Sprintf(\"%s:v%s\", path.Join(kubernetesRepo(mirror), name), v)\n}", "func formatPodImage(raw string) (result string) {\n\ts := strings.Split(raw, \":\")\n\tif len(s) == 3 {\n\t\tresult = s[2]\n\t}\n\treturn\n}", "func (o ArgoCDSpecDexPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecDex) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func (s *VarlinkInterface) VarlinkGetDescription() string {\n\treturn `# Podman Service Interface and API description. The master version of this document can be found\n# in the [API.md](https://github.com/containers/libpod/blob/master/API.md) file in the upstream libpod repository.\ninterface io.podman\n\ntype Volume (\n name: string,\n labels: [string]string,\n mountPoint: string,\n driver: string,\n options: [string]string,\n scope: string\n)\n\ntype NotImplemented (\n comment: string\n)\n\ntype StringResponse (\n message: string\n)\n\ntype LogLine (\n device: string,\n parseLogType : string,\n time: string,\n msg: string,\n cid: string\n)\n\n# ContainerChanges describes the return struct for ListContainerChanges\ntype ContainerChanges (\n changed: []string,\n added: []string,\n deleted: []string\n)\n\ntype ImageSaveOptions (\n name: string,\n format: string,\n output: string,\n outputType: string,\n moreTags: []string,\n quiet: bool,\n compress: bool\n)\n\ntype VolumeCreateOpts (\n volumeName: string,\n driver: string,\n labels: [string]string,\n options: [string]string\n)\n\ntype VolumeRemoveOpts (\n volumes: []string,\n all: bool,\n force: bool\n)\n\ntype Image (\n id: string,\n digest: string,\n parentId: string,\n repoTags: []string,\n repoDigests: []string,\n created: string, # as RFC3339\n size: int,\n virtualSize: int,\n containers: int,\n labels: [string]string,\n isParent: bool,\n topLayer: string,\n readOnly: bool\n)\n\n# ImageHistory describes the returned structure from ImageHistory.\ntype ImageHistory (\n id: string,\n created: string, # as RFC3339\n createdBy: string,\n tags: []string,\n size: int,\n comment: string\n)\n\n# Represents a single search result from SearchImages\ntype ImageSearchResult (\n description: string,\n is_official: bool,\n is_automated: bool,\n registry: string,\n name: string,\n star_count: int\n)\n\ntype ImageSearchFilter (\n is_official: ?bool,\n is_automated: ?bool,\n star_count: int\n)\n\ntype KubePodService (\n pod: string,\n service: string\n)\n\ntype Container (\n id: string,\n image: string,\n imageid: string,\n command: []string,\n createdat: string, # as RFC3339\n runningfor: string,\n status: string,\n ports: []ContainerPortMappings,\n rootfssize: int,\n rwsize: int,\n names: string,\n labels: [string]string,\n mounts: []ContainerMount,\n containerrunning: bool,\n namespaces: ContainerNameSpace\n)\n\n# ContainerStats is the return struct for the stats of a container\ntype ContainerStats (\n id: string,\n name: string,\n cpu: float,\n cpu_nano: int,\n system_nano: int,\n mem_usage: int,\n mem_limit: int,\n mem_perc: float,\n net_input: int,\n net_output: int,\n block_output: int,\n block_input: int,\n pids: int\n)\n\ntype PsOpts (\n all: bool,\n filters: ?[]string,\n last: ?int,\n latest: ?bool,\n noTrunc: ?bool,\n pod: ?bool,\n quiet: ?bool,\n size: ?bool,\n sort: ?string,\n sync: ?bool\n)\n\ntype PsContainer (\n id: string,\n image: string,\n command: string,\n created: string,\n ports: string,\n names: string,\n isInfra: bool,\n status: string,\n state: string,\n pidNum: int,\n rootFsSize: int,\n rwSize: int,\n pod: string,\n createdAt: string,\n exitedAt: string,\n startedAt: string,\n labels: [string]string,\n nsPid: string,\n cgroup: string,\n ipc: string,\n mnt: string,\n net: string,\n pidNs: string,\n user: string,\n uts: string,\n mounts: string\n)\n\n# ContainerMount describes the struct for mounts in a container\ntype ContainerMount (\n destination: string,\n type: string,\n source: string,\n options: []string\n)\n\n# ContainerPortMappings describes the struct for portmappings in an existing container\ntype ContainerPortMappings (\n host_port: string,\n host_ip: string,\n protocol: string,\n container_port: string\n)\n\n# ContainerNamespace describes the namespace structure for an existing container\ntype ContainerNameSpace (\n user: string,\n uts: string,\n pidns: string,\n pid: string,\n cgroup: string,\n net: string,\n mnt: string,\n ipc: string\n)\n\n# InfoDistribution describes the host's distribution\ntype InfoDistribution (\n distribution: string,\n version: string\n)\n\n# InfoHost describes the host stats portion of PodmanInfo\ntype InfoHost (\n buildah_version: string,\n distribution: InfoDistribution,\n mem_free: int,\n mem_total: int,\n swap_free: int,\n swap_total: int,\n arch: string,\n cpus: int,\n hostname: string,\n kernel: string,\n os: string,\n uptime: string,\n eventlogger: string\n)\n\n# InfoGraphStatus describes the detailed status of the storage driver\ntype InfoGraphStatus (\n backing_filesystem: string,\n native_overlay_diff: string,\n supports_d_type: string\n)\n\n# InfoStore describes the host's storage informatoin\ntype InfoStore (\n containers: int,\n images: int,\n graph_driver_name: string,\n graph_driver_options: string,\n graph_root: string,\n graph_status: InfoGraphStatus,\n run_root: string\n)\n\n# InfoPodman provides details on the podman binary\ntype InfoPodmanBinary (\n compiler: string,\n go_version: string,\n podman_version: string,\n git_commit: string\n)\n\n# PodmanInfo describes the Podman host and build\ntype PodmanInfo (\n host: InfoHost,\n registries: []string,\n insecure_registries: []string,\n store: InfoStore,\n podman: InfoPodmanBinary\n)\n\n# Sockets describes sockets location for a container\ntype Sockets(\n container_id: string,\n io_socket: string,\n control_socket: string\n)\n\n# Create is an input structure for creating containers.\ntype Create (\n args: []string,\n addHost: ?[]string,\n annotation: ?[]string,\n attach: ?[]string,\n blkioWeight: ?string,\n blkioWeightDevice: ?[]string,\n capAdd: ?[]string,\n capDrop: ?[]string,\n cgroupParent: ?string,\n cidFile: ?string,\n conmonPidfile: ?string,\n command: ?[]string,\n cpuPeriod: ?int,\n cpuQuota: ?int,\n cpuRtPeriod: ?int,\n cpuRtRuntime: ?int,\n cpuShares: ?int,\n cpus: ?float,\n cpuSetCpus: ?string,\n cpuSetMems: ?string,\n detach: ?bool,\n detachKeys: ?string,\n device: ?[]string,\n deviceReadBps: ?[]string,\n deviceReadIops: ?[]string,\n deviceWriteBps: ?[]string,\n deviceWriteIops: ?[]string,\n dns: ?[]string,\n dnsOpt: ?[]string,\n dnsSearch: ?[]string,\n dnsServers: ?[]string,\n entrypoint: ?string,\n env: ?[]string,\n envFile: ?[]string,\n expose: ?[]string,\n gidmap: ?[]string,\n groupadd: ?[]string,\n healthcheckCommand: ?string,\n healthcheckInterval: ?string,\n healthcheckRetries: ?int,\n healthcheckStartPeriod: ?string,\n healthcheckTimeout:?string,\n hostname: ?string,\n imageVolume: ?string,\n init: ?bool,\n initPath: ?string,\n interactive: ?bool,\n ip: ?string,\n ipc: ?string,\n kernelMemory: ?string,\n label: ?[]string,\n labelFile: ?[]string,\n logDriver: ?string,\n logOpt: ?[]string,\n macAddress: ?string,\n memory: ?string,\n memoryReservation: ?string,\n memorySwap: ?string,\n memorySwappiness: ?int,\n name: ?string,\n net: ?string,\n network: ?string,\n noHosts: ?bool,\n oomKillDisable: ?bool,\n oomScoreAdj: ?int,\n pid: ?string,\n pidsLimit: ?int,\n pod: ?string,\n privileged: ?bool,\n publish: ?[]string,\n publishAll: ?bool,\n quiet: ?bool,\n readonly: ?bool,\n readonlytmpfs: ?bool,\n restart: ?string,\n rm: ?bool,\n rootfs: ?bool,\n securityOpt: ?[]string,\n shmSize: ?string,\n stopSignal: ?string,\n stopTimeout: ?int,\n storageOpt: ?[]string,\n subuidname: ?string,\n subgidname: ?string,\n sysctl: ?[]string,\n systemd: ?bool,\n tmpfs: ?[]string,\n tty: ?bool,\n uidmap: ?[]string,\n ulimit: ?[]string,\n user: ?string,\n userns: ?string,\n uts: ?string,\n mount: ?[]string,\n volume: ?[]string,\n volumesFrom: ?[]string,\n workDir: ?string\n)\n\n# BuildOptions are are used to describe describe physical attributes of the build\ntype BuildOptions (\n addHosts: []string,\n cgroupParent: string,\n cpuPeriod: int,\n cpuQuota: int,\n cpuShares: int,\n cpusetCpus: string,\n cpusetMems: string,\n memory: int,\n memorySwap: int,\n shmSize: string,\n ulimit: []string,\n volume: []string\n)\n\n# BuildInfo is used to describe user input for building images\ntype BuildInfo (\n additionalTags: []string,\n annotations: []string,\n buildArgs: [string]string,\n buildOptions: BuildOptions,\n cniConfigDir: string,\n cniPluginDir: string,\n compression: string,\n contextDir: string,\n defaultsMountFilePath: string,\n dockerfiles: []string,\n err: string,\n forceRmIntermediateCtrs: bool,\n iidfile: string,\n label: []string,\n layers: bool,\n nocache: bool,\n out: string,\n output: string,\n outputFormat: string,\n pullPolicy: string,\n quiet: bool,\n remoteIntermediateCtrs: bool,\n reportWriter: string,\n runtimeArgs: []string,\n squash: bool\n)\n\n# MoreResponse is a struct for when responses from varlink requires longer output\ntype MoreResponse (\n logs: []string,\n id: string\n)\n\n# ListPodContainerInfo is a returned struct for describing containers\n# in a pod.\ntype ListPodContainerInfo (\n name: string,\n id: string,\n status: string\n)\n\n# PodCreate is an input structure for creating pods.\n# It emulates options to podman pod create. The infraCommand and\n# infraImage options are currently NotSupported.\ntype PodCreate (\n name: string,\n cgroupParent: string,\n labels: [string]string,\n share: []string,\n infra: bool,\n infraCommand: string,\n infraImage: string,\n publish: []string\n)\n\n# ListPodData is the returned struct for an individual pod\ntype ListPodData (\n id: string,\n name: string,\n createdat: string,\n cgroup: string,\n status: string,\n labels: [string]string,\n numberofcontainers: string,\n containersinfo: []ListPodContainerInfo\n)\n\ntype PodContainerErrorData (\n containerid: string,\n reason: string\n)\n\n# Runlabel describes the required input for container runlabel\ntype Runlabel(\n image: string,\n authfile: string,\n display: bool,\n name: string,\n pull: bool,\n label: string,\n extraArgs: []string,\n opts: [string]string\n)\n\n# Event describes a libpod struct\ntype Event(\n # TODO: make status and type a enum at some point?\n # id is the container, volume, pod, image ID\n id: string,\n # image is the image name where applicable\n image: string,\n # name is the name of the pod, container, image\n name: string,\n # status describes the event that happened (i.e. create, remove, ...)\n status: string,\n # time the event happened\n time: string,\n # type describes object the event happened with (image, container...)\n type: string\n)\n\ntype DiffInfo(\n # path that is different\n path: string,\n # Add, Delete, Modify\n changeType: string\n)\n\ntype ExecOpts(\n # container name or id\n name: string,\n # Create pseudo tty\n tty: bool,\n # privileged access in container\n privileged: bool,\n # command to execute in container\n cmd: []string,\n # user to use in container\n user: ?string,\n # workdir to run command in container\n workdir: ?string,\n # slice of keyword=value environment variables\n env: ?[]string,\n # string of detach keys\n detachKeys: ?string\n)\n\n# GetVersion returns version and build information of the podman service\nmethod GetVersion() -> (\n version: string,\n go_version: string,\n git_commit: string,\n built: string, # as RFC3339\n os_arch: string,\n remote_api_version: int\n)\n\n# GetInfo returns a [PodmanInfo](#PodmanInfo) struct that describes podman and its host such as storage stats,\n# build information of Podman, and system-wide registries.\nmethod GetInfo() -> (info: PodmanInfo)\n\n# ListContainers returns information about all containers.\n# See also [GetContainer](#GetContainer).\nmethod ListContainers() -> (containers: []Container)\n\nmethod Ps(opts: PsOpts) -> (containers: []PsContainer)\n\nmethod GetContainersByStatus(status: []string) -> (containerS: []Container)\n\nmethod Top (nameOrID: string, descriptors: []string) -> (top: []string)\n\n# GetContainer returns information about a single container. If a container\n# with the given id doesn't exist, a [ContainerNotFound](#ContainerNotFound)\n# error will be returned. See also [ListContainers](ListContainers) and\n# [InspectContainer](#InspectContainer).\nmethod GetContainer(id: string) -> (container: Container)\n\n# GetContainersByContext allows you to get a list of container ids depending on all, latest, or a list of\n# container names. The definition of latest container means the latest by creation date. In a multi-\n# user environment, results might differ from what you expect.\nmethod GetContainersByContext(all: bool, latest: bool, args: []string) -> (containers: []string)\n\n# CreateContainer creates a new container from an image. It uses a [Create](#Create) type for input.\nmethod CreateContainer(create: Create) -> (container: string)\n\n# InspectContainer data takes a name or ID of a container returns the inspection\n# data in string format. You can then serialize the string into JSON. A [ContainerNotFound](#ContainerNotFound)\n# error will be returned if the container cannot be found. See also [InspectImage](#InspectImage).\nmethod InspectContainer(name: string) -> (container: string)\n\n# ListContainerProcesses takes a name or ID of a container and returns the processes\n# running inside the container as array of strings. It will accept an array of string\n# arguments that represent ps options. If the container cannot be found, a [ContainerNotFound](#ContainerNotFound)\n# error will be returned.\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.ListContainerProcesses '{\"name\": \"135d71b9495f\", \"opts\": []}'\n# {\n# \"container\": [\n# \" UID PID PPID C STIME TTY TIME CMD\",\n# \" 0 21220 21210 0 09:05 pts/0 00:00:00 /bin/sh\",\n# \" 0 21232 21220 0 09:05 pts/0 00:00:00 top\",\n# \" 0 21284 21220 0 09:05 pts/0 00:00:00 vi /etc/hosts\"\n# ]\n# }\n# ~~~\nmethod ListContainerProcesses(name: string, opts: []string) -> (container: []string)\n\n# GetContainerLogs takes a name or ID of a container and returns the logs of that container.\n# If the container cannot be found, a [ContainerNotFound](#ContainerNotFound) error will be returned.\n# The container logs are returned as an array of strings. GetContainerLogs will honor the streaming\n# capability of varlink if the client invokes it.\nmethod GetContainerLogs(name: string) -> (container: []string)\n\nmethod GetContainersLogs(names: []string, follow: bool, latest: bool, since: string, tail: int, timestamps: bool) -> (log: LogLine)\n\n# ListContainerChanges takes a name or ID of a container and returns changes between the container and\n# its base image. It returns a struct of changed, deleted, and added path names.\nmethod ListContainerChanges(name: string) -> (container: ContainerChanges)\n\n# ExportContainer creates an image from a container. It takes the name or ID of a container and a\n# path representing the target tarfile. If the container cannot be found, a [ContainerNotFound](#ContainerNotFound)\n# error will be returned.\n# The return value is the written tarfile.\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.ExportContainer '{\"name\": \"flamboyant_payne\", \"path\": \"/tmp/payne.tar\" }'\n# {\n# \"tarfile\": \"/tmp/payne.tar\"\n# }\n# ~~~\nmethod ExportContainer(name: string, path: string) -> (tarfile: string)\n\n# GetContainerStats takes the name or ID of a container and returns a single ContainerStats structure which\n# contains attributes like memory and cpu usage. If the container cannot be found, a\n# [ContainerNotFound](#ContainerNotFound) error will be returned. If the container is not running, a [NoContainerRunning](#NoContainerRunning)\n# error will be returned\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.GetContainerStats '{\"name\": \"c33e4164f384\"}'\n# {\n# \"container\": {\n# \"block_input\": 0,\n# \"block_output\": 0,\n# \"cpu\": 2.571123918839990154678e-08,\n# \"cpu_nano\": 49037378,\n# \"id\": \"c33e4164f384aa9d979072a63319d66b74fd7a128be71fa68ede24f33ec6cfee\",\n# \"mem_limit\": 33080606720,\n# \"mem_perc\": 2.166828456524753747370e-03,\n# \"mem_usage\": 716800,\n# \"name\": \"competent_wozniak\",\n# \"net_input\": 768,\n# \"net_output\": 5910,\n# \"pids\": 1,\n# \"system_nano\": 10000000\n# }\n# }\n# ~~~\nmethod GetContainerStats(name: string) -> (container: ContainerStats)\n\n# GetContainerStatsWithHistory takes a previous set of container statistics and uses libpod functions\n# to calculate the containers statistics based on current and previous measurements.\nmethod GetContainerStatsWithHistory(previousStats: ContainerStats) -> (container: ContainerStats)\n\n# This method has not be implemented yet.\n# method ResizeContainerTty() -> (notimplemented: NotImplemented)\n\n# StartContainer starts a created or stopped container. It takes the name or ID of container. It returns\n# the container ID once started. If the container cannot be found, a [ContainerNotFound](#ContainerNotFound)\n# error will be returned. See also [CreateContainer](#CreateContainer).\nmethod StartContainer(name: string) -> (container: string)\n\n# StopContainer stops a container given a timeout. It takes the name or ID of a container as well as a\n# timeout value. The timeout value the time before a forcible stop to the container is applied. It\n# returns the container ID once stopped. If the container cannot be found, a [ContainerNotFound](#ContainerNotFound)\n# error will be returned instead. See also [KillContainer](KillContainer).\n# #### Error\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.StopContainer '{\"name\": \"135d71b9495f\", \"timeout\": 5}'\n# {\n# \"container\": \"135d71b9495f7c3967f536edad57750bfdb569336cd107d8aabab45565ffcfb6\"\n# }\n# ~~~\nmethod StopContainer(name: string, timeout: int) -> (container: string)\n\n# InitContainer initializes the given container. It accepts a container name or\n# ID, and will initialize the container matching that ID if possible, and error\n# if not. Containers can only be initialized when they are in the Created or\n# Exited states. Initialization prepares a container to be started, but does not\n# start the container. It is intended to be used to debug a container's state\n# prior to starting it.\nmethod InitContainer(name: string) -> (container: string)\n\n# RestartContainer will restart a running container given a container name or ID and timeout value. The timeout\n# value is the time before a forcible stop is used to stop the container. If the container cannot be found by\n# name or ID, a [ContainerNotFound](#ContainerNotFound) error will be returned; otherwise, the ID of the\n# container will be returned.\nmethod RestartContainer(name: string, timeout: int) -> (container: string)\n\n# KillContainer takes the name or ID of a container as well as a signal to be applied to the container. Once the\n# container has been killed, the container's ID is returned. If the container cannot be found, a\n# [ContainerNotFound](#ContainerNotFound) error is returned. See also [StopContainer](StopContainer).\nmethod KillContainer(name: string, signal: int) -> (container: string)\n\n# This method has not be implemented yet.\n# method UpdateContainer() -> (notimplemented: NotImplemented)\n\n# This method has not be implemented yet.\n# method RenameContainer() -> (notimplemented: NotImplemented)\n\n# PauseContainer takes the name or ID of container and pauses it. If the container cannot be found,\n# a [ContainerNotFound](#ContainerNotFound) error will be returned; otherwise the ID of the container is returned.\n# See also [UnpauseContainer](#UnpauseContainer).\nmethod PauseContainer(name: string) -> (container: string)\n\n# UnpauseContainer takes the name or ID of container and unpauses a paused container. If the container cannot be\n# found, a [ContainerNotFound](#ContainerNotFound) error will be returned; otherwise the ID of the container is returned.\n# See also [PauseContainer](#PauseContainer).\nmethod UnpauseContainer(name: string) -> (container: string)\n\n# Attach takes the name or ID of a container and sets up the ability to remotely attach to its console. The start\n# bool is whether you wish to start the container in question first.\nmethod Attach(name: string, detachKeys: string, start: bool) -> ()\n\nmethod AttachControl(name: string) -> ()\n\n# GetAttachSockets takes the name or ID of an existing container. It returns file paths for two sockets needed\n# to properly communicate with a container. The first is the actual I/O socket that the container uses. The\n# second is a \"control\" socket where things like resizing the TTY events are sent. If the container cannot be\n# found, a [ContainerNotFound](#ContainerNotFound) error will be returned.\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/io.podman/io.podman.GetAttachSockets '{\"name\": \"b7624e775431219161\"}'\n# {\n# \"sockets\": {\n# \"container_id\": \"b7624e7754312191613245ce1a46844abee60025818fe3c3f3203435623a1eca\",\n# \"control_socket\": \"/var/lib/containers/storage/overlay-containers/b7624e7754312191613245ce1a46844abee60025818fe3c3f3203435623a1eca/userdata/ctl\",\n# \"io_socket\": \"/var/run/libpod/socket/b7624e7754312191613245ce1a46844abee60025818fe3c3f3203435623a1eca/attach\"\n# }\n# }\n# ~~~\nmethod GetAttachSockets(name: string) -> (sockets: Sockets)\n\n# WaitContainer takes the name or ID of a container and waits the given interval in milliseconds until the container\n# stops. Upon stopping, the return code of the container is returned. If the container container cannot be found by ID\n# or name, a [ContainerNotFound](#ContainerNotFound) error is returned.\nmethod WaitContainer(name: string, interval: int) -> (exitcode: int)\n\n# RemoveContainer requires the name or ID of container as well a boolean representing whether a running container can be stopped and removed, and a boolean\n# indicating whether to remove builtin volumes. Upon successful removal of the\n# container, its ID is returned. If the\n# container cannot be found by name or ID, a [ContainerNotFound](#ContainerNotFound) error will be returned.\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.RemoveContainer '{\"name\": \"62f4fd98cb57\"}'\n# {\n# \"container\": \"62f4fd98cb57f529831e8f90610e54bba74bd6f02920ffb485e15376ed365c20\"\n# }\n# ~~~\nmethod RemoveContainer(name: string, force: bool, removeVolumes: bool) -> (container: string)\n\n# DeleteStoppedContainers will delete all containers that are not running. It will return a list the deleted\n# container IDs. See also [RemoveContainer](RemoveContainer).\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.DeleteStoppedContainers\n# {\n# \"containers\": [\n# \"451410b931d00def8aa9b4f8084e4d4a39e5e04ea61f358cf53a5cf95afcdcee\",\n# \"8b60f754a3e01389494a9581ade97d35c2765b6e2f19acd2d3040c82a32d1bc0\",\n# \"cf2e99d4d3cad6073df199ed32bbe64b124f3e1aba6d78821aa8460e70d30084\",\n# \"db901a329587312366e5ecff583d08f0875b4b79294322df67d90fc6eed08fc1\"\n# ]\n# }\n# ~~~\nmethod DeleteStoppedContainers() -> (containers: []string)\n\n# ListImages returns information about the images that are currently in storage.\n# See also [InspectImage](#InspectImage).\nmethod ListImages() -> (images: []Image)\n\n# GetImage returns information about a single image in storage.\n# If the image caGetImage returns be found, [ImageNotFound](#ImageNotFound) will be returned.\nmethod GetImage(id: string) -> (image: Image)\n\n# BuildImage takes a [BuildInfo](#BuildInfo) structure and builds an image. At a minimum, you must provide the\n# 'dockerfile' and 'tags' options in the BuildInfo structure. It will return a [MoreResponse](#MoreResponse) structure\n# that contains the build logs and resulting image ID.\nmethod BuildImage(build: BuildInfo) -> (image: MoreResponse)\n\n# This function is not implemented yet.\n# method CreateImage() -> (notimplemented: NotImplemented)\n\n# InspectImage takes the name or ID of an image and returns a string representation of data associated with the\n#image. You must serialize the string into JSON to use it further. An [ImageNotFound](#ImageNotFound) error will\n# be returned if the image cannot be found.\nmethod InspectImage(name: string) -> (image: string)\n\n# HistoryImage takes the name or ID of an image and returns information about its history and layers. The returned\n# history is in the form of an array of ImageHistory structures. If the image cannot be found, an\n# [ImageNotFound](#ImageNotFound) error is returned.\nmethod HistoryImage(name: string) -> (history: []ImageHistory)\n\n# PushImage takes two input arguments: the name or ID of an image, the fully-qualified destination name of the image,\n# It will return an [ImageNotFound](#ImageNotFound) error if\n# the image cannot be found in local storage; otherwise it will return a [MoreResponse](#MoreResponse)\nmethod PushImage(name: string, tag: string, compress: bool, format: string, removeSignatures: bool, signBy: string) -> (reply: MoreResponse)\n\n# TagImage takes the name or ID of an image in local storage as well as the desired tag name. If the image cannot\n# be found, an [ImageNotFound](#ImageNotFound) error will be returned; otherwise, the ID of the image is returned on success.\nmethod TagImage(name: string, tagged: string) -> (image: string)\n\n# RemoveImage takes the name or ID of an image as well as a boolean that determines if containers using that image\n# should be deleted. If the image cannot be found, an [ImageNotFound](#ImageNotFound) error will be returned. The\n# ID of the removed image is returned when complete. See also [DeleteUnusedImages](DeleteUnusedImages).\n# #### Example\n# ~~~\n# varlink call -m unix:/run/podman/io.podman/io.podman.RemoveImage '{\"name\": \"registry.fedoraproject.org/fedora\", \"force\": true}'\n# {\n# \"image\": \"426866d6fa419873f97e5cbd320eeb22778244c1dfffa01c944db3114f55772e\"\n# }\n# ~~~\nmethod RemoveImage(name: string, force: bool) -> (image: string)\n\n# SearchImages searches available registries for images that contain the\n# contents of \"query\" in their name. If \"limit\" is given, limits the amount of\n# search results per registry.\nmethod SearchImages(query: string, limit: ?int, filter: ImageSearchFilter) -> (results: []ImageSearchResult)\n\n# DeleteUnusedImages deletes any images not associated with a container. The IDs of the deleted images are returned\n# in a string array.\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.DeleteUnusedImages\n# {\n# \"images\": [\n# \"166ea6588079559c724c15223f52927f514f73dd5c5cf2ae2d143e3b2e6e9b52\",\n# \"da86e6ba6ca197bf6bc5e9d900febd906b133eaa4750e6bed647b0fbe50ed43e\",\n# \"3ef70f7291f47dfe2b82931a993e16f5a44a0e7a68034c3e0e086d77f5829adc\",\n# \"59788edf1f3e78cd0ebe6ce1446e9d10788225db3dedcfd1a59f764bad2b2690\"\n# ]\n# }\n# ~~~\nmethod DeleteUnusedImages() -> (images: []string)\n\n# Commit, creates an image from an existing container. It requires the name or\n# ID of the container as well as the resulting image name. Optionally, you can define an author and message\n# to be added to the resulting image. You can also define changes to the resulting image for the following\n# attributes: _CMD, ENTRYPOINT, ENV, EXPOSE, LABEL, ONBUILD, STOPSIGNAL, USER, VOLUME, and WORKDIR_. To pause the\n# container while it is being committed, pass a _true_ bool for the pause argument. If the container cannot\n# be found by the ID or name provided, a (ContainerNotFound)[#ContainerNotFound] error will be returned; otherwise,\n# the resulting image's ID will be returned as a string inside a MoreResponse.\nmethod Commit(name: string, image_name: string, changes: []string, author: string, message: string, pause: bool, manifestType: string) -> (reply: MoreResponse)\n\n# ImportImage imports an image from a source (like tarball) into local storage. The image can have additional\n# descriptions added to it using the message and changes options. See also [ExportImage](ExportImage).\nmethod ImportImage(source: string, reference: string, message: string, changes: []string, delete: bool) -> (image: string)\n\n# ExportImage takes the name or ID of an image and exports it to a destination like a tarball. There is also\n# a boolean option to force compression. It also takes in a string array of tags to be able to save multiple\n# tags of the same image to a tarball (each tag should be of the form <image>:<tag>). Upon completion, the ID\n# of the image is returned. If the image cannot be found in local storage, an [ImageNotFound](#ImageNotFound)\n# error will be returned. See also [ImportImage](ImportImage).\nmethod ExportImage(name: string, destination: string, compress: bool, tags: []string) -> (image: string)\n\n# PullImage pulls an image from a repository to local storage. After a successful pull, the image id and logs\n# are returned as a [MoreResponse](#MoreResponse). This connection also will handle a WantsMores request to send\n# status as it occurs.\nmethod PullImage(name: string) -> (reply: MoreResponse)\n\n# CreatePod creates a new empty pod. It uses a [PodCreate](#PodCreate) type for input.\n# On success, the ID of the newly created pod will be returned.\n# #### Example\n# ~~~\n# $ varlink call unix:/run/podman/io.podman/io.podman.CreatePod '{\"create\": {\"name\": \"test\"}}'\n# {\n# \"pod\": \"b05dee7bd4ccfee688099fe1588a7a898d6ddd6897de9251d4671c9b0feacb2a\"\n# }\n#\n# $ varlink call unix:/run/podman/io.podman/io.podman.CreatePod '{\"create\": {\"infra\": true, \"share\": [\"ipc\", \"net\", \"uts\"]}}'\n# {\n# \"pod\": \"d7697449a8035f613c1a8891286502aca68fff7d5d49a85279b3bda229af3b28\"\n# }\n# ~~~\nmethod CreatePod(create: PodCreate) -> (pod: string)\n\n# ListPods returns a list of pods in no particular order. They are\n# returned as an array of ListPodData structs. See also [GetPod](#GetPod).\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.ListPods\n# {\n# \"pods\": [\n# {\n# \"cgroup\": \"machine.slice\",\n# \"containersinfo\": [\n# {\n# \"id\": \"00c130a45de0411f109f1a0cfea2e298df71db20fa939de5cab8b2160a36be45\",\n# \"name\": \"1840835294cf-infra\",\n# \"status\": \"running\"\n# },\n# {\n# \"id\": \"49a5cce72093a5ca47c6de86f10ad7bb36391e2d89cef765f807e460865a0ec6\",\n# \"name\": \"upbeat_murdock\",\n# \"status\": \"running\"\n# }\n# ],\n# \"createdat\": \"2018-12-07 13:10:15.014139258 -0600 CST\",\n# \"id\": \"1840835294cf076a822e4e12ba4152411f131bd869e7f6a4e8b16df9b0ea5c7f\",\n# \"name\": \"foobar\",\n# \"numberofcontainers\": \"2\",\n# \"status\": \"Running\"\n# },\n# {\n# \"cgroup\": \"machine.slice\",\n# \"containersinfo\": [\n# {\n# \"id\": \"1ca4b7bbba14a75ba00072d4b705c77f3df87db0109afaa44d50cb37c04a477e\",\n# \"name\": \"784306f655c6-infra\",\n# \"status\": \"running\"\n# }\n# ],\n# \"createdat\": \"2018-12-07 13:09:57.105112457 -0600 CST\",\n# \"id\": \"784306f655c6200aea321dd430ba685e9b2cc1f7d7528a72f3ff74ffb29485a2\",\n# \"name\": \"nostalgic_pike\",\n# \"numberofcontainers\": \"1\",\n# \"status\": \"Running\"\n# }\n# ]\n# }\n# ~~~\nmethod ListPods() -> (pods: []ListPodData)\n\n# GetPod takes a name or ID of a pod and returns single [ListPodData](#ListPodData)\n# structure. A [PodNotFound](#PodNotFound) error will be returned if the pod cannot be found.\n# See also [ListPods](ListPods).\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.GetPod '{\"name\": \"foobar\"}'\n# {\n# \"pod\": {\n# \"cgroup\": \"machine.slice\",\n# \"containersinfo\": [\n# {\n# \"id\": \"00c130a45de0411f109f1a0cfea2e298df71db20fa939de5cab8b2160a36be45\",\n# \"name\": \"1840835294cf-infra\",\n# \"status\": \"running\"\n# },\n# {\n# \"id\": \"49a5cce72093a5ca47c6de86f10ad7bb36391e2d89cef765f807e460865a0ec6\",\n# \"name\": \"upbeat_murdock\",\n# \"status\": \"running\"\n# }\n# ],\n# \"createdat\": \"2018-12-07 13:10:15.014139258 -0600 CST\",\n# \"id\": \"1840835294cf076a822e4e12ba4152411f131bd869e7f6a4e8b16df9b0ea5c7f\",\n# \"name\": \"foobar\",\n# \"numberofcontainers\": \"2\",\n# \"status\": \"Running\"\n# }\n# }\n# ~~~\nmethod GetPod(name: string) -> (pod: ListPodData)\n\n# InspectPod takes the name or ID of an image and returns a string representation of data associated with the\n# pod. You must serialize the string into JSON to use it further. A [PodNotFound](#PodNotFound) error will\n# be returned if the pod cannot be found.\nmethod InspectPod(name: string) -> (pod: string)\n\n# StartPod starts containers in a pod. It takes the name or ID of pod. If the pod cannot be found, a [PodNotFound](#PodNotFound)\n# error will be returned. Containers in a pod are started independently. If there is an error starting one container, the ID of those containers\n# will be returned in a list, along with the ID of the pod in a [PodContainerError](#PodContainerError).\n# If the pod was started with no errors, the pod ID is returned.\n# See also [CreatePod](#CreatePod).\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.StartPod '{\"name\": \"135d71b9495f\"}'\n# {\n# \"pod\": \"135d71b9495f7c3967f536edad57750bfdb569336cd107d8aabab45565ffcfb6\",\n# }\n# ~~~\nmethod StartPod(name: string) -> (pod: string)\n\n# StopPod stops containers in a pod. It takes the name or ID of a pod and a timeout.\n# If the pod cannot be found, a [PodNotFound](#PodNotFound) error will be returned instead.\n# Containers in a pod are stopped independently. If there is an error stopping one container, the ID of those containers\n# will be returned in a list, along with the ID of the pod in a [PodContainerError](#PodContainerError).\n# If the pod was stopped with no errors, the pod ID is returned.\n# See also [KillPod](KillPod).\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.StopPod '{\"name\": \"135d71b9495f\"}'\n# {\n# \"pod\": \"135d71b9495f7c3967f536edad57750bfdb569336cd107d8aabab45565ffcfb6\"\n# }\n# ~~~\nmethod StopPod(name: string, timeout: int) -> (pod: string)\n\n# RestartPod will restart containers in a pod given a pod name or ID. Containers in\n# the pod that are running will be stopped, then all stopped containers will be run.\n# If the pod cannot be found by name or ID, a [PodNotFound](#PodNotFound) error will be returned.\n# Containers in a pod are restarted independently. If there is an error restarting one container, the ID of those containers\n# will be returned in a list, along with the ID of the pod in a [PodContainerError](#PodContainerError).\n# If the pod was restarted with no errors, the pod ID is returned.\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.RestartPod '{\"name\": \"135d71b9495f\"}'\n# {\n# \"pod\": \"135d71b9495f7c3967f536edad57750bfdb569336cd107d8aabab45565ffcfb6\"\n# }\n# ~~~\nmethod RestartPod(name: string) -> (pod: string)\n\n# KillPod takes the name or ID of a pod as well as a signal to be applied to the pod. If the pod cannot be found, a\n# [PodNotFound](#PodNotFound) error is returned.\n# Containers in a pod are killed independently. If there is an error killing one container, the ID of those containers\n# will be returned in a list, along with the ID of the pod in a [PodContainerError](#PodContainerError).\n# If the pod was killed with no errors, the pod ID is returned.\n# See also [StopPod](StopPod).\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.KillPod '{\"name\": \"foobar\", \"signal\": 15}'\n# {\n# \"pod\": \"1840835294cf076a822e4e12ba4152411f131bd869e7f6a4e8b16df9b0ea5c7f\"\n# }\n# ~~~\nmethod KillPod(name: string, signal: int) -> (pod: string)\n\n# PausePod takes the name or ID of a pod and pauses the running containers associated with it. If the pod cannot be found,\n# a [PodNotFound](#PodNotFound) error will be returned.\n# Containers in a pod are paused independently. If there is an error pausing one container, the ID of those containers\n# will be returned in a list, along with the ID of the pod in a [PodContainerError](#PodContainerError).\n# If the pod was paused with no errors, the pod ID is returned.\n# See also [UnpausePod](#UnpausePod).\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.PausePod '{\"name\": \"foobar\"}'\n# {\n# \"pod\": \"1840835294cf076a822e4e12ba4152411f131bd869e7f6a4e8b16df9b0ea5c7f\"\n# }\n# ~~~\nmethod PausePod(name: string) -> (pod: string)\n\n# UnpausePod takes the name or ID of a pod and unpauses the paused containers associated with it. If the pod cannot be\n# found, a [PodNotFound](#PodNotFound) error will be returned.\n# Containers in a pod are unpaused independently. If there is an error unpausing one container, the ID of those containers\n# will be returned in a list, along with the ID of the pod in a [PodContainerError](#PodContainerError).\n# If the pod was unpaused with no errors, the pod ID is returned.\n# See also [PausePod](#PausePod).\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.UnpausePod '{\"name\": \"foobar\"}'\n# {\n# \"pod\": \"1840835294cf076a822e4e12ba4152411f131bd869e7f6a4e8b16df9b0ea5c7f\"\n# }\n# ~~~\nmethod UnpausePod(name: string) -> (pod: string)\n\n# RemovePod takes the name or ID of a pod as well a boolean representing whether a running\n# container in the pod can be stopped and removed. If a pod has containers associated with it, and force is not true,\n# an error will occur.\n# If the pod cannot be found by name or ID, a [PodNotFound](#PodNotFound) error will be returned.\n# Containers in a pod are removed independently. If there is an error removing any container, the ID of those containers\n# will be returned in a list, along with the ID of the pod in a [PodContainerError](#PodContainerError).\n# If the pod was removed with no errors, the pod ID is returned.\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.RemovePod '{\"name\": \"62f4fd98cb57\", \"force\": \"true\"}'\n# {\n# \"pod\": \"62f4fd98cb57f529831e8f90610e54bba74bd6f02920ffb485e15376ed365c20\"\n# }\n# ~~~\nmethod RemovePod(name: string, force: bool) -> (pod: string)\n\n# This method has not be implemented yet.\n# method WaitPod() -> (notimplemented: NotImplemented)\n\nmethod TopPod(pod: string, latest: bool, descriptors: []string) -> (stats: []string)\n\n# GetPodStats takes the name or ID of a pod and returns a pod name and slice of ContainerStats structure which\n# contains attributes like memory and cpu usage. If the pod cannot be found, a [PodNotFound](#PodNotFound)\n# error will be returned. If the pod has no running containers associated with it, a [NoContainerRunning](#NoContainerRunning)\n# error will be returned.\n# #### Example\n# ~~~\n# $ varlink call unix:/run/podman/io.podman/io.podman.GetPodStats '{\"name\": \"7f62b508b6f12b11d8fe02e\"}'\n# {\n# \"containers\": [\n# {\n# \"block_input\": 0,\n# \"block_output\": 0,\n# \"cpu\": 2.833470544016107524276e-08,\n# \"cpu_nano\": 54363072,\n# \"id\": \"a64b51f805121fe2c5a3dc5112eb61d6ed139e3d1c99110360d08b58d48e4a93\",\n# \"mem_limit\": 12276146176,\n# \"mem_perc\": 7.974359265237864966003e-03,\n# \"mem_usage\": 978944,\n# \"name\": \"quirky_heisenberg\",\n# \"net_input\": 866,\n# \"net_output\": 7388,\n# \"pids\": 1,\n# \"system_nano\": 20000000\n# }\n# ],\n# \"pod\": \"7f62b508b6f12b11d8fe02e0db4de6b9e43a7d7699b33a4fc0d574f6e82b4ebd\"\n# }\n# ~~~\nmethod GetPodStats(name: string) -> (pod: string, containers: []ContainerStats)\n\n# GetPodsByStatus searches for pods whose status is included in statuses\nmethod GetPodsByStatus(statuses: []string) -> (pods: []string)\n\n# ImageExists talks a full or partial image ID or name and returns an int as to whether\n# the image exists in local storage. An int result of 0 means the image does exist in\n# local storage; whereas 1 indicates the image does not exists in local storage.\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.ImageExists '{\"name\": \"imageddoesntexist\"}'\n# {\n# \"exists\": 1\n# }\n# ~~~\nmethod ImageExists(name: string) -> (exists: int)\n\n# ContainerExists takes a full or partial container ID or name and returns an int as to\n# whether the container exists in local storage. A result of 0 means the container does\n# exists; whereas a result of 1 means it could not be found.\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.ContainerExists '{\"name\": \"flamboyant_payne\"}'{\n# \"exists\": 0\n# }\n# ~~~\nmethod ContainerExists(name: string) -> (exists: int)\n\n# ContainerCheckPoint performs a checkpopint on a container by its name or full/partial container\n# ID. On successful checkpoint, the id of the checkpointed container is returned.\nmethod ContainerCheckpoint(name: string, keep: bool, leaveRunning: bool, tcpEstablished: bool) -> (id: string)\n\n# ContainerRestore restores a container that has been checkpointed. The container to be restored can\n# be identified by its name or full/partial container ID. A successful restore will result in the return\n# of the container's ID.\nmethod ContainerRestore(name: string, keep: bool, tcpEstablished: bool) -> (id: string)\n\n# ContainerRunlabel runs executes a command as described by a given container image label.\nmethod ContainerRunlabel(runlabel: Runlabel) -> ()\n\n# ExecContainer executes a command in the given container.\nmethod ExecContainer(opts: ExecOpts) -> ()\n\n# ListContainerMounts gathers all the mounted container mount points and returns them as an array\n# of strings\n# #### Example\n# ~~~\n# $ varlink call unix:/run/podman/io.podman/io.podman.ListContainerMounts\n# {\n# \"mounts\": {\n# \"04e4c255269ed2545e7f8bd1395a75f7949c50c223415c00c1d54bfa20f3b3d9\": \"/var/lib/containers/storage/overlay/a078925828f57e20467ca31cfca8a849210d21ec7e5757332b72b6924f441c17/merged\",\n# \"1d58c319f9e881a644a5122ff84419dccf6d138f744469281446ab243ef38924\": \"/var/lib/containers/storage/overlay/948fcf93f8cb932f0f03fd52e3180a58627d547192ffe3b88e0013b98ddcd0d2/merged\"\n# }\n# }\n# ~~~\nmethod ListContainerMounts() -> (mounts: [string]string)\n\n# MountContainer mounts a container by name or full/partial ID. Upon a successful mount, the destination\n# mount is returned as a string.\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.MountContainer '{\"name\": \"jolly_shannon\"}'{\n# \"path\": \"/var/lib/containers/storage/overlay/419eeb04e783ea159149ced67d9fcfc15211084d65e894792a96bedfae0470ca/merged\"\n# }\n# ~~~\nmethod MountContainer(name: string) -> (path: string)\n\n# UnmountContainer umounts a container by its name or full/partial container ID.\n# #### Example\n# ~~~\n# $ varlink call -m unix:/run/podman/io.podman/io.podman.UnmountContainer '{\"name\": \"jolly_shannon\", \"force\": false}'\n# {}\n# ~~~\nmethod UnmountContainer(name: string, force: bool) -> ()\n\n# ImagesPrune removes all unused images from the local store. Upon successful pruning,\n# the IDs of the removed images are returned.\nmethod ImagesPrune(all: bool) -> (pruned: []string)\n\n# This function is not implemented yet.\n# method ListContainerPorts(name: string) -> (notimplemented: NotImplemented)\n\n# GenerateKube generates a Kubernetes v1 Pod description of a Podman container or pod\n# and its containers. The description is in YAML. See also [ReplayKube](ReplayKube).\nmethod GenerateKube(name: string, service: bool) -> (pod: KubePodService)\n\n# ReplayKube recreates a pod and its containers based on a Kubernetes v1 Pod description (in YAML)\n# like that created by GenerateKube. See also [GenerateKube](GenerateKube).\n# method ReplayKube() -> (notimplemented: NotImplemented)\n\n# ContainerConfig returns a container's config in string form. This call is for\n# development of Podman only and generally should not be used.\nmethod ContainerConfig(name: string) -> (config: string)\n\n# ContainerArtifacts returns a container's artifacts in string form. This call is for\n# development of Podman only and generally should not be used.\nmethod ContainerArtifacts(name: string, artifactName: string) -> (config: string)\n\n# ContainerInspectData returns a container's inspect data in string form. This call is for\n# development of Podman only and generally should not be used.\nmethod ContainerInspectData(name: string, size: bool) -> (config: string)\n\n# ContainerStateData returns a container's state config in string form. This call is for\n# development of Podman only and generally should not be used.\nmethod ContainerStateData(name: string) -> (config: string)\n\n# PodStateData returns inspectr level information of a given pod in string form. This call is for\n# development of Podman only and generally should not be used.\nmethod PodStateData(name: string) -> (config: string)\n\n# This call is for the development of Podman only and should not be used.\nmethod CreateFromCC(in: []string) -> (id: string)\n\n# Spec returns the oci spec for a container. This call is for development of Podman only and generally should not be used.\nmethod Spec(name: string) -> (config: string)\n\n# Sendfile allows a remote client to send a file to the host\nmethod SendFile(type: string, length: int) -> (file_handle: string)\n\n# ReceiveFile allows the host to send a remote client a file\nmethod ReceiveFile(path: string, delete: bool) -> (len: int)\n\n# VolumeCreate creates a volume on a remote host\nmethod VolumeCreate(options: VolumeCreateOpts) -> (volumeName: string)\n\n# VolumeRemove removes a volume on a remote host\nmethod VolumeRemove(options: VolumeRemoveOpts) -> (volumeNames: []string)\n\n# GetVolumes gets slice of the volumes on a remote host\nmethod GetVolumes(args: []string, all: bool) -> (volumes: []Volume)\n\n# VolumesPrune removes unused volumes on the host\nmethod VolumesPrune() -> (prunedNames: []string, prunedErrors: []string)\n\n# ImageSave allows you to save an image from the local image storage to a tarball\nmethod ImageSave(options: ImageSaveOptions) -> (reply: MoreResponse)\n\n# GetPodsByContext allows you to get a list pod ids depending on all, latest, or a list of\n# pod names. The definition of latest pod means the latest by creation date. In a multi-\n# user environment, results might differ from what you expect.\nmethod GetPodsByContext(all: bool, latest: bool, args: []string) -> (pods: []string)\n\n# LoadImage allows you to load an image into local storage from a tarball.\nmethod LoadImage(name: string, inputFile: string, quiet: bool, deleteFile: bool) -> (reply: MoreResponse)\n\n# GetEvents returns known libpod events filtered by the options provided.\nmethod GetEvents(filter: []string, since: string, until: string) -> (events: Event)\n\n# Diff returns a diff between libpod objects\nmethod Diff(name: string) -> (diffs: []DiffInfo)\n\n# GetLayersMapWithImageInfo is for the development of Podman and should not be used.\nmethod GetLayersMapWithImageInfo() -> (layerMap: string)\n\n# BuildImageHierarchyMap is for the development of Podman and should not be used.\nmethod BuildImageHierarchyMap(name: string) -> (imageInfo: string)\n\nmethod GenerateSystemd(name: string, restart: string, timeout: int, useName: bool) -> (unit: string)\n\n# ImageNotFound means the image could not be found by the provided name or ID in local storage.\nerror ImageNotFound (id: string, reason: string)\n\n# ContainerNotFound means the container could not be found by the provided name or ID in local storage.\nerror ContainerNotFound (id: string, reason: string)\n\n# NoContainerRunning means none of the containers requested are running in a command that requires a running container.\nerror NoContainerRunning ()\n\n# PodNotFound means the pod could not be found by the provided name or ID in local storage.\nerror PodNotFound (name: string, reason: string)\n\n# VolumeNotFound means the volume could not be found by the name or ID in local storage.\nerror VolumeNotFound (id: string, reason: string)\n\n# PodContainerError means a container associated with a pod failed to perform an operation. It contains\n# a container ID of the container that failed.\nerror PodContainerError (podname: string, errors: []PodContainerErrorData)\n\n# NoContainersInPod means a pod has no containers on which to perform the operation. It contains\n# the pod ID.\nerror NoContainersInPod (name: string)\n\n# InvalidState indicates that a container or pod was in an improper state for the requested operation\nerror InvalidState (id: string, reason: string)\n\n# ErrorOccurred is a generic error for an error that occurs during the execution. The actual error message\n# is includes as part of the error's text.\nerror ErrorOccurred (reason: string)\n\n# RuntimeErrors generally means a runtime could not be found or gotten.\nerror RuntimeError (reason: string)\n\n# The Podman endpoint requires that you use a streaming connection.\nerror WantsMoreRequired (reason: string)\n\n# Container is already stopped\nerror ErrCtrStopped (id: string)\n\n# This function requires CGroupsV2 to run in rootless mode.\nerror ErrRequiresCgroupsV2ForRootless(reason: string)\n`\n}", "func GetImage(runtime connector.ModuleRuntime, kubeConf *common.KubeConf, name string) Image {\n\tvar image Image\n\tpauseTag, corednsTag := \"3.2\", \"1.6.9\"\n\n\tif versionutil.MustParseSemantic(kubeConf.Cluster.Kubernetes.Version).LessThan(versionutil.MustParseSemantic(\"v1.21.0\")) {\n\t\tpauseTag = \"3.2\"\n\t\tcorednsTag = \"1.6.9\"\n\t}\n\tif versionutil.MustParseSemantic(kubeConf.Cluster.Kubernetes.Version).AtLeast(versionutil.MustParseSemantic(\"v1.21.0\")) ||\n\t\t(kubeConf.Cluster.Kubernetes.ContainerManager != \"\" && kubeConf.Cluster.Kubernetes.ContainerManager != \"docker\") {\n\t\tpauseTag = \"3.4.1\"\n\t\tcorednsTag = \"1.8.0\"\n\t}\n\tif versionutil.MustParseSemantic(kubeConf.Cluster.Kubernetes.Version).AtLeast(versionutil.MustParseSemantic(\"v1.22.0\")) {\n\t\tpauseTag = \"3.5\"\n\t\tcorednsTag = \"1.8.0\"\n\t}\n\tif versionutil.MustParseSemantic(kubeConf.Cluster.Kubernetes.Version).AtLeast(versionutil.MustParseSemantic(\"v1.23.0\")) {\n\t\tpauseTag = \"3.6\"\n\t\tcorednsTag = \"1.8.6\"\n\t}\n\tif versionutil.MustParseSemantic(kubeConf.Cluster.Kubernetes.Version).AtLeast(versionutil.MustParseSemantic(\"v1.24.0\")) {\n\t\tpauseTag = \"3.7\"\n\t\tcorednsTag = \"1.8.6\"\n\t}\n\tif versionutil.MustParseSemantic(kubeConf.Cluster.Kubernetes.Version).AtLeast(versionutil.MustParseSemantic(\"v1.25.0\")) {\n\t\tpauseTag = \"3.8\"\n\t\tcorednsTag = \"1.9.3\"\n\t}\n\n\tlogger.Log.Debugf(\"pauseTag: %s, corednsTag: %s\", pauseTag, corednsTag)\n\n\tImageList := map[string]Image{\n\t\t\"pause\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: kubekeyv1alpha2.DefaultKubeImageNamespace, Repo: \"pause\", Tag: pauseTag, Group: kubekeyv1alpha2.K8s, Enable: true},\n\t\t\"etcd\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: kubekeyv1alpha2.DefaultKubeImageNamespace, Repo: \"etcd\", Tag: kubekeyv1alpha2.DefaultEtcdVersion, Group: kubekeyv1alpha2.Master, Enable: strings.EqualFold(kubeConf.Cluster.Etcd.Type, kubekeyv1alpha2.Kubeadm)},\n\t\t\"kube-apiserver\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: kubekeyv1alpha2.DefaultKubeImageNamespace, Repo: \"kube-apiserver\", Tag: kubeConf.Cluster.Kubernetes.Version, Group: kubekeyv1alpha2.Master, Enable: true},\n\t\t\"kube-controller-manager\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: kubekeyv1alpha2.DefaultKubeImageNamespace, Repo: \"kube-controller-manager\", Tag: kubeConf.Cluster.Kubernetes.Version, Group: kubekeyv1alpha2.Master, Enable: true},\n\t\t\"kube-scheduler\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: kubekeyv1alpha2.DefaultKubeImageNamespace, Repo: \"kube-scheduler\", Tag: kubeConf.Cluster.Kubernetes.Version, Group: kubekeyv1alpha2.Master, Enable: true},\n\t\t\"kube-proxy\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: kubekeyv1alpha2.DefaultKubeImageNamespace, Repo: \"kube-proxy\", Tag: kubeConf.Cluster.Kubernetes.Version, Group: kubekeyv1alpha2.K8s, Enable: !kubeConf.Cluster.Kubernetes.DisableKubeProxy},\n\n\t\t// network\n\t\t\"coredns\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"coredns\", Repo: \"coredns\", Tag: corednsTag, Group: kubekeyv1alpha2.K8s, Enable: true},\n\t\t\"k8s-dns-node-cache\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: kubekeyv1alpha2.DefaultKubeImageNamespace, Repo: \"k8s-dns-node-cache\", Tag: \"1.15.12\", Group: kubekeyv1alpha2.K8s, Enable: kubeConf.Cluster.Kubernetes.EnableNodelocaldns()},\n\t\t\"calico-kube-controllers\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"calico\", Repo: \"kube-controllers\", Tag: kubekeyv1alpha2.DefaultCalicoVersion, Group: kubekeyv1alpha2.K8s, Enable: strings.EqualFold(kubeConf.Cluster.Network.Plugin, \"calico\")},\n\t\t\"calico-cni\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"calico\", Repo: \"cni\", Tag: kubekeyv1alpha2.DefaultCalicoVersion, Group: kubekeyv1alpha2.K8s, Enable: strings.EqualFold(kubeConf.Cluster.Network.Plugin, \"calico\")},\n\t\t\"calico-node\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"calico\", Repo: \"node\", Tag: kubekeyv1alpha2.DefaultCalicoVersion, Group: kubekeyv1alpha2.K8s, Enable: strings.EqualFold(kubeConf.Cluster.Network.Plugin, \"calico\")},\n\t\t\"calico-flexvol\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"calico\", Repo: \"pod2daemon-flexvol\", Tag: kubekeyv1alpha2.DefaultCalicoVersion, Group: kubekeyv1alpha2.K8s, Enable: strings.EqualFold(kubeConf.Cluster.Network.Plugin, \"calico\")},\n\t\t\"calico-typha\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"calico\", Repo: \"typha\", Tag: kubekeyv1alpha2.DefaultCalicoVersion, Group: kubekeyv1alpha2.K8s, Enable: strings.EqualFold(kubeConf.Cluster.Network.Plugin, \"calico\") && len(runtime.GetHostsByRole(common.K8s)) > 50},\n\t\t\"flannel\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"flannel\", Repo: \"flannel\", Tag: kubekeyv1alpha2.DefaultFlannelVersion, Group: kubekeyv1alpha2.K8s, Enable: strings.EqualFold(kubeConf.Cluster.Network.Plugin, \"flannel\")},\n\t\t\"flannel-cni-plugin\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"flannel\", Repo: \"flannel-cni-plugin\", Tag: kubekeyv1alpha2.DefaultFlannelCniPluginVersion, Group: kubekeyv1alpha2.K8s, Enable: strings.EqualFold(kubeConf.Cluster.Network.Plugin, \"flannel\")},\n\t\t\"cilium\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"cilium\", Repo: \"cilium\", Tag: kubekeyv1alpha2.DefaultCiliumVersion, Group: kubekeyv1alpha2.K8s, Enable: strings.EqualFold(kubeConf.Cluster.Network.Plugin, \"cilium\")},\n\t\t\"cilium-operator-generic\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"cilium\", Repo: \"operator-generic\", Tag: kubekeyv1alpha2.DefaultCiliumVersion, Group: kubekeyv1alpha2.K8s, Enable: strings.EqualFold(kubeConf.Cluster.Network.Plugin, \"cilium\")},\n\t\t\"kubeovn\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"kubeovn\", Repo: \"kube-ovn\", Tag: kubekeyv1alpha2.DefaultKubeovnVersion, Group: kubekeyv1alpha2.K8s, Enable: strings.EqualFold(kubeConf.Cluster.Network.Plugin, \"kubeovn\")},\n\t\t\"multus\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: kubekeyv1alpha2.DefaultKubeImageNamespace, Repo: \"multus-cni\", Tag: kubekeyv1alpha2.DefalutMultusVersion, Group: kubekeyv1alpha2.K8s, Enable: strings.Contains(kubeConf.Cluster.Network.Plugin, \"multus\")},\n\t\t// storage\n\t\t\"provisioner-localpv\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"openebs\", Repo: \"provisioner-localpv\", Tag: \"3.3.0\", Group: kubekeyv1alpha2.Worker, Enable: false},\n\t\t\"linux-utils\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"openebs\", Repo: \"linux-utils\", Tag: \"3.3.0\", Group: kubekeyv1alpha2.Worker, Enable: false},\n\t\t// load balancer\n\t\t\"haproxy\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"library\", Repo: \"haproxy\", Tag: \"2.3\", Group: kubekeyv1alpha2.Worker, Enable: kubeConf.Cluster.ControlPlaneEndpoint.IsInternalLBEnabled()},\n\t\t\"kubevip\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: \"plndr\", Repo: \"kube-vip\", Tag: \"v0.5.0\", Group: kubekeyv1alpha2.Master, Enable: kubeConf.Cluster.ControlPlaneEndpoint.IsInternalLBEnabledVip()},\n\t\t// kata-deploy\n\t\t\"kata-deploy\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: kubekeyv1alpha2.DefaultKubeImageNamespace, Repo: \"kata-deploy\", Tag: \"stable\", Group: kubekeyv1alpha2.Worker, Enable: kubeConf.Cluster.Kubernetes.EnableKataDeploy()},\n\t\t// node-feature-discovery\n\t\t\"node-feature-discovery\": {RepoAddr: kubeConf.Cluster.Registry.PrivateRegistry, Namespace: kubekeyv1alpha2.DefaultKubeImageNamespace, Repo: \"node-feature-discovery\", Tag: \"v0.10.0\", Group: kubekeyv1alpha2.K8s, Enable: kubeConf.Cluster.Kubernetes.EnableNodeFeatureDiscovery()},\n\t}\n\n\timage = ImageList[name]\n\tif kubeConf.Cluster.Registry.NamespaceOverride != \"\" {\n\t\timage.NamespaceOverride = kubeConf.Cluster.Registry.NamespaceOverride\n\t}\n\treturn image\n}", "func (i *LibpodAPI) InspectImage(call ioprojectatomicpodman.VarlinkCall, name string) error {\n\truntime, err := libpodruntime.GetRuntime(i.Cli)\n\tif err != nil {\n\t\treturn call.ReplyRuntimeError(err.Error())\n\t}\n\tnewImage, err := runtime.ImageRuntime().NewFromLocal(name)\n\tif err != nil {\n\t\treturn call.ReplyImageNotFound(name)\n\t}\n\tinspectInfo, err := newImage.Inspect(getContext())\n\tb, err := json.Marshal(inspectInfo)\n\tif err != nil {\n\t\treturn call.ReplyErrorOccurred(fmt.Sprintf(\"unable to serialize\"))\n\t}\n\treturn call.ReplyInspectImage(string(b))\n}", "func (d *Descriptor) Image() (v1.Image, error) {\n\tswitch d.MediaType {\n\tcase types.DockerManifestSchema1, types.DockerManifestSchema1Signed:\n\t\t// We don't care to support schema 1 images:\n\t\t// https://github.com/google/go-containerregistry/issues/377\n\t\treturn nil, newErrSchema1(d.MediaType)\n\tcase types.OCIImageIndex, types.DockerManifestList:\n\t\t// We want an image but the registry has an index, resolve it to an image.\n\t\treturn d.remoteIndex().imageByPlatform(d.platform)\n\tcase types.OCIManifestSchema1, types.DockerManifestSchema2:\n\t\t// These are expected. Enumerated here to allow a default case.\n\tdefault:\n\t\t// We could just return an error here, but some registries (e.g. static\n\t\t// registries) don't set the Content-Type headers correctly, so instead...\n\t\tlogs.Warn.Printf(\"Unexpected media type for Image(): %s\", d.MediaType)\n\t}\n\n\t// Wrap the v1.Layers returned by this v1.Image in a hint for downstream\n\t// remote.Write calls to facilitate cross-repo \"mounting\".\n\timgCore, err := partial.CompressedToImage(d.remoteImage())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &mountableImage{\n\t\tImage: imgCore,\n\t\tReference: d.ref,\n\t}, nil\n}", "func (s *VarlinkInterface) GetImage(ctx context.Context, c VarlinkCall, id_ string) error {\n\treturn c.ReplyMethodNotImplemented(ctx, \"io.podman.GetImage\")\n}", "func getPodVersions(podList []string, cobraCmd *cobra.Command) map[string]*versionInfo {\n\toutMap := make(map[string]*versionInfo)\n\tcmd := exec.Command(\"kubectl\", \"get\", \"pods\", \"--all-namespaces\", \"-o\", \"jsonpath={range .items[*]}{\\\"{\\\\\\\"name\\\\\\\":\\\\\\\"\\\"}{.status.containerStatuses[].name}{\\\"\\\\\\\",\\\"}{\\\"\\\\\\\"version\\\\\\\":\\\\\\\"\\\"}{.status.containerStatuses[].image}{\\\"\\\\\\\",\\\"}{\\\"\\\\\\\"id\\\\\\\":\\\\\\\"\\\"}{.status.containerStatuses[].imageID}{\\\"\\\\\\\"}\\\\n\\\"}\")\n\toutput, err := utils.ExecuteCmd(cmd, cobraCmd)\n\tif err != nil {\n\t\tfmt.Println(\"Error getting pods version\\n\", err)\n\t} else {\n\t\tpods := strings.Split(output, \"\\n\")\n\t\tfor i := range pods {\n\n\t\t\tvi := new(versionInfo)\n\t\t\terr := json.Unmarshal([]byte(pods[i]), &vi)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsvcName := getSvcName(vi.Name)\n\t\t\tif svcName != \"\" && contains(podList, svcName) {\n\t\t\t\toutMap[svcName] = vi\n\n\t\t\t\t// Build ID (custom docker image label)\n\t\t\t\tcmd := exec.Command(\"docker\", \"image\", \"inspect\", \"--format\", \"{{ index .Config.Labels \\\"MeepVersion\\\"}}\", vi.Version)\n\t\t\t\tvi.BuildID, _ = utils.ExecuteCmd(cmd, cobraCmd)\n\t\t\t\tvi.BuildID = strings.TrimSuffix(vi.BuildID, \"\\n\")\n\n\t\t\t\t// // Image name\n\t\t\t\t// tv := strings.Split(vi.Version, \":\")\n\t\t\t\t// vi.Version = tv[len(tv)-1]\n\n\t\t\t\t// Image ID\n\t\t\t\ttid := strings.Split(vi.VersionID, \":\")\n\t\t\t\tvi.VersionID = tid[len(tid)-1]\n\t\t\t}\n\t\t}\n\t}\n\treturn outMap\n}", "func RunPod(ctx context.Context, pod corev1.Pod,\n\tts oauth2.TokenSource, watcherImage, project, zone, machineType string) error {\n\n\tsvc, err := compute.NewService(ctx, option.WithTokenSource(ts))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb, err := yaml.Marshal(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpodstr := string(b)\n\tlog.Println(\"POD MANIFEST:\\n\", podstr) // TODO remove\n\n\tregion := zone[:strings.LastIndex(zone, \"-\")]\n\n\twatcherPod := fmt.Sprintf(watcherPodFmt, watcherImage)\n\n\tname := \"instance-\" + uuid.New().String()[:4]\n\tlog.Printf(\"creating %q...\", name)\n\top, err := svc.Instances.Insert(project, zone, &compute.Instance{\n\t\tName: name,\n\t\tZone: zone,\n\t\tMachineType: fmt.Sprintf(\"projects/%s/zones/%s/machineTypes/%s\", project, zone, machineType),\n\t\tDisks: []*compute.AttachedDisk{{\n\t\t\tInitializeParams: &compute.AttachedDiskInitializeParams{\n\t\t\t\tSourceImage: \"projects/cos-cloud/global/images/family/cos-stable\",\n\t\t\t},\n\t\t\tBoot: true,\n\t\t}},\n\t\tNetworkInterfaces: []*compute.NetworkInterface{{\n\t\t\tSubnetwork: fmt.Sprintf(\"projects/%s/regions/%s/subnetworks/default\", project, region),\n\t\t\tAccessConfigs: []*compute.AccessConfig{{\n\t\t\t\tName: \"External NAT\",\n\t\t\t\tType: \"ONE_TO_ONE_NAT\",\n\t\t\t\tNetworkTier: \"PREMIUM\",\n\t\t\t}},\n\t\t}},\n\t\tServiceAccounts: []*compute.ServiceAccount{{\n\t\t\tEmail: \"178371766757-compute@developer.gserviceaccount.com\",\n\t\t\tScopes: []string{\n\t\t\t\t// Permiission to pull private images (watcher)\n\t\t\t\t\"https://www.googleapis.com/auth/devstorage.read_only\",\n\n\t\t\t\t// Permission to write logs and metrics (google-fluentd)\n\t\t\t\t\"https://www.googleapis.com/auth/logging.write\",\n\t\t\t\t\"https://www.googleapis.com/auth/monitoring.write\",\n\t\t\t},\n\t\t}},\n\t\tMetadata: &compute.Metadata{\n\t\t\tItems: []*compute.MetadataItems{{\n\t\t\t\tKey: \"user-data\",\n\t\t\t\tValue: &cloudConfig,\n\t\t\t}, {\n\t\t\t\tKey: \"watcher\",\n\t\t\t\tValue: &watcherPod,\n\t\t\t}, {\n\t\t\t\tKey: \"pod\",\n\t\t\t\tValue: &podstr,\n\t\t\t}, {\n\t\t\t\tKey: \"ca-cert\",\n\t\t\t\tValue: &caCert,\n\t\t\t}, {\n\t\t\t\tKey: \"ca-cert-key\",\n\t\t\t\tValue: &caCertKey,\n\t\t\t}, {\n\t\t\t\tKey: \"cos-metrics-enabled\",\n\t\t\t\tValue: &trueString,\n\t\t\t}},\n\t\t},\n\t\tTags: &compute.Tags{Items: []string{\"https-server\"}},\n\t\tShieldedInstanceConfig: &compute.ShieldedInstanceConfig{\n\t\t\tEnableSecureBoot: true,\n\t\t},\n\t}).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstart := time.Now()\n\tfor ; ; time.Sleep(time.Second) {\n\t\top, err = svc.ZoneOperations.Get(project, zone, op.Name).Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Printf(\"operation is %q...\", op.Status)\n\t\tif op.Status == \"DONE\" {\n\t\t\tbreak\n\t\t}\n\t}\n\tlog.Println(\"startup took\", time.Since(start))\n\treturn nil\n}", "func (o IopingSpecVolumeVolumeSourceRbdPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceRbd) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func podInfo(pod v1.Pod) (result string) {\n\tpodname := pod.Name\n\tpodstatus := strings.ToLower(string(pod.Status.Phase))\n\timages := \"\"\n\tfor _, container := range pod.Spec.Containers {\n\t\timages += fmt.Sprintf(\"%v \", container.Image)\n\t}\n\tresult += fmt.Sprintf(\"pod [%v] is %v and uses image(s) %v\\n\", podname, podstatus, images)\n\treturn result\n}", "func (o BuildSpecBuilderPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildSpecBuilder) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func (s *VarlinkInterface) InspectImage(ctx context.Context, c VarlinkCall, name_ string) error {\n\treturn c.ReplyMethodNotImplemented(ctx, \"io.podman.InspectImage\")\n}", "func (o ArgoCDSpecGrafanaPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecGrafana) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func uxImage(cmd cli.Command) cli.Command {\n\tcmd.Flags = append(cmd.Flags, cli.StringFlag{\n\t\tName: \"image\",\n\t\tUsage: \"OCI image URI of the form 'path[:tag]'\",\n\t})\n\n\toldBefore := cmd.Before\n\tcmd.Before = func(ctx *cli.Context) error {\n\t\t// Verify and parse --image.\n\t\tif ctx.IsSet(\"image\") {\n\t\t\timage := ctx.String(\"image\")\n\n\t\t\tvar dir, tag string\n\t\t\tsep := strings.Index(image, \":\")\n\t\t\tif sep == -1 {\n\t\t\t\tdir = image\n\t\t\t\ttag = \"latest\"\n\t\t\t} else {\n\t\t\t\tdir = image[:sep]\n\t\t\t\ttag = image[sep+1:]\n\t\t\t}\n\n\t\t\t// Verify directory value.\n\t\t\tif dir == \"\" {\n\t\t\t\treturn errors.Wrap(fmt.Errorf(\"path is empty\"), \"invalid --image\")\n\t\t\t}\n\n\t\t\t// Verify tag value.\n\t\t\tif !casext.IsValidReferenceName(tag) {\n\t\t\t\treturn errors.Wrap(fmt.Errorf(\"tag contains invalid characters: '%s'\", tag), \"invalid --image\")\n\t\t\t}\n\t\t\tif tag == \"\" {\n\t\t\t\treturn errors.Wrap(fmt.Errorf(\"tag is empty\"), \"invalid --image\")\n\t\t\t}\n\n\t\t\tctx.App.Metadata[\"--image-path\"] = dir\n\t\t\tctx.App.Metadata[\"--image-tag\"] = tag\n\t\t}\n\n\t\tif oldBefore != nil {\n\t\t\treturn oldBefore(ctx)\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn cmd\n}", "func (o ArgoCDSpecDexOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecDex) *string { return v.Image }).(pulumi.StringPtrOutput)\n}", "func (o FioSpecVolumeVolumeSourceRbdPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceRbd) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func newImageDestination(ctx context.Context, sys *types.SystemContext, ref daemonReference) (private.ImageDestination, error) {\n\tif ref.ref == nil {\n\t\treturn nil, fmt.Errorf(\"Invalid destination docker-daemon:%s: a destination must be a name:tag\", ref.StringWithinTransport())\n\t}\n\tnamedTaggedRef, ok := ref.ref.(reference.NamedTagged)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Invalid destination docker-daemon:%s: a destination must be a name:tag\", ref.StringWithinTransport())\n\t}\n\n\tvar mustMatchRuntimeOS = true\n\tif sys != nil && sys.DockerDaemonHost != client.DefaultDockerHost {\n\t\tmustMatchRuntimeOS = false\n\t}\n\n\tc, err := newDockerClient(sys)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initializing docker engine client: %w\", err)\n\t}\n\n\treader, writer := io.Pipe()\n\tarchive := tarfile.NewWriter(writer)\n\t// Commit() may never be called, so we may never read from this channel; so, make this buffered to allow imageLoadGoroutine to write status and terminate even if we never read it.\n\tstatusChannel := make(chan error, 1)\n\n\tgoroutineContext, goroutineCancel := context.WithCancel(ctx)\n\tgo imageLoadGoroutine(goroutineContext, c, reader, statusChannel)\n\n\treturn &daemonImageDestination{\n\t\tref: ref,\n\t\tmustMatchRuntimeOS: mustMatchRuntimeOS,\n\t\tDestination: tarfile.NewDestination(sys, archive, ref.Transport().Name(), namedTaggedRef),\n\t\tarchive: archive,\n\t\tgoroutineCancel: goroutineCancel,\n\t\tstatusChannel: statusChannel,\n\t\twriter: writer,\n\t\tcommitted: false,\n\t}, nil\n}", "func natsPodReloaderContainer(image, tag, pullPolicy, authFilePath string) v1.Container {\n\tcontainer := v1.Container{\n\t\tName: \"reloader\",\n\t\tImage: fmt.Sprintf(\"%s:%s\", image, tag),\n\t\tImagePullPolicy: v1.PullPolicy(pullPolicy),\n\t\tCommand: []string{\n\t\t\t\"nats-server-config-reloader\",\n\t\t\t\"-config\",\n\t\t\tconstants.ConfigFilePath,\n\t\t\t\"-pid\",\n\t\t\tconstants.PidFilePath,\n\t\t},\n\t}\n\tif authFilePath != \"\" {\n\t\t// The volume is mounted as a subdirectory under the NATS config.\n\t\taf := filepath.Join(constants.ConfigMapMountPath, authFilePath)\n\t\tcontainer.Command = append(container.Command, \"-config\", af)\n\t}\n\treturn container\n}", "func (o BuildSpecRuntimeBasePtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildSpecRuntimeBase) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ArgoCDSpecRedisPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecRedis) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func (o BuildRunStatusBuildSpecBuilderPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildRunStatusBuildSpecBuilder) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func (this *Task) image(zkc zk.ZK) (string, string, string, error) {\n\tif this.ImagePath == \"\" {\n\n\t\tdefaultReleaseWatchPath, _, err := RegistryKeyValue(KReleaseWatch, map[string]interface{}{\n\t\t\t\"Domain\": this.domain,\n\t\t\t\"Service\": this.service,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", \"\", err\n\t\t}\n\n\t\treleaseNode, err := zkc.Get(defaultReleaseWatchPath)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", \"\", err\n\t\t}\n\n\t\tthis.ImagePath = releaseNode.GetValueString()\n\t\tglog.Infoln(\"ImagePath defaults to\", this.ImagePath, \"for job\", *this)\n\t}\n\n\tglog.Infoln(\"Container image from image path\", this.ImagePath)\n\tdocker_info, err := zkc.Get(this.ImagePath)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\timage := docker_info.GetValueString()\n\tversion := image[strings.LastIndex(image, \":\")+1:]\n\treturn fmt.Sprintf(\"/%s/%s/%s\", this.domain, this.service, version), version, image, nil\n}", "func (o ArgoCDExportSpecPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDExportSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ArgoCDSpecPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func (o BuildSpecOutputPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildSpecOutput) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func (mConfig *MonitoringConfig) GetImage() string {\n\tif mConfig.JmxImage != \"\" {\n\t\treturn mConfig.JmxImage\n\t}\n\treturn \"banzaicloud/jmx-javaagent:0.12.0\"\n}", "func (mConfig *MonitoringConfig) GetImage() string {\n\tif mConfig.JmxImage != \"\" {\n\t\treturn mConfig.JmxImage\n\t}\n\treturn \"banzaicloud/jmx-javaagent:0.12.0\"\n}", "func Builder(ctx context.Context, c client.Client) (*client.Result, error) {\n\tst := llb.Image(\"ubuntu:18.04\")\n\n\tdef, err := st.Marshal(llb.LinuxAmd64)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"marshaling state\")\n\t}\n\n\treq := client.SolveRequest{\n\t\tDefinition: def.ToPB(),\n\t}\n\tres, err := c.Solve(ctx, req)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"resolving dockerfile\")\n\t}\n\n\timg := specs.Image{\n\t\tArchitecture: \"amd64\",\n\t\tOS: \"linux\",\n\t}\n\timg.RootFS.Type = \"layers\"\n\timg.Config.WorkingDir = \"/\"\n\timg.Config.Env = []string{\"PATH=\" + system.DefaultPathEnv}\n\timg.Config.Cmd = []string{\"ls\"}\n\n\tcfg, err := json.Marshal(img)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"marshaling image definition\")\n\t}\n\tlog.Println(cfg)\n\n\tplat := []string{\n\t\texptypes.ExporterImageConfigKey,\n\t\tplatforms.Format(platforms.DefaultSpec()),\n\t}\n\tres.AddMeta(strings.Join(plat, \"/\"), cfg)\n\n\t// ref, err := res.SingleRef()\n\t// if err != nil {\n\t// \treturn nil, err\n\t// }\n\t// res.SetRef(ref)\n\n\treturn res, nil\n}", "func PodImages(pod v1.Pod) []string {\n\timages := []string{}\n\tfor _, ic := range pod.Spec.InitContainers {\n\t\timages = append(images, ic.Image)\n\t}\n\tfor _, c := range pod.Spec.Containers {\n\t\timages = append(images, c.Image)\n\t}\n\treturn images\n}", "func (*ImagePullReply) Descriptor() ([]byte, []int) {\n\treturn file_proto_images_alive_proto_rawDescGZIP(), []int{1}\n}", "func PullImage(image, cacheDir string) (v1.Image, error) {\n var options []crane.Option\n\n // options = append(options, crane.Insecure)\n\n // Use current built OS and architecture\n options = append(options, crane.WithPlatform(&v1.Platform{\n OS: runtime.GOOS,\n Architecture: runtime.GOARCH,\n }))\n\n // Grab the remote manifest\n manifest, err := crane.Manifest(image, options...)\n if err != nil {\n return nil, fmt.Errorf(\"failed fetching manifest for %s: %v\", image, err)\n }\n\n if !gjson.Valid(string(manifest)) {\n return nil, fmt.Errorf(\"Cannot parse manifest: %s\", string(manifest))\n }\n\n value := gjson.Get(string(manifest), \"config.digest\").Value().(string)\n if value == \"\" {\n return nil, fmt.Errorf(\"Malformed manifest: %s\", string(manifest))\n }\n \n digest := strings.Split(value, \":\")[1]\n tarball := fmt.Sprintf(\"%s/%s.tar.gz\", cacheDir, digest)\n\n // Download the tarball of the image if not available in the cache\n if _, err := os.Stat(tarball); os.IsNotExist(err) {\n // Create the cacheDir if it does not already exist\n if cacheDir != \"\" {\n if _, err := os.Stat(cacheDir); os.IsNotExist(err) {\n os.MkdirAll(cacheDir, os.ModePerm)\n }\n }\n \n // Pull the image\n img, err := crane.Pull(image, options...)\n if err != nil {\n return nil, fmt.Errorf(\"Could not pull image: %s\", err)\n }\n \n f, err := os.Create(tarball)\n if err != nil {\n return nil, fmt.Errorf(\"Failed to open %s: %v\", tarball, err)\n }\n \n defer f.Close()\n \n err = crane.Save(img, image, tarball)\n if err != nil {\n return nil, fmt.Errorf(\"Could not save image: %s\", err)\n }\n }\n\n img, err := crane.Load(tarball)\n if err != nil {\n return nil, fmt.Errorf(\"Could not load image: %s\", err)\n }\n\n return img, nil\n}", "func GetImage(imageSpec *commonv1.AgentImageConfig, registry *string) string {\n\tif defaulting.IsImageNameContainsTag(imageSpec.Name) {\n\t\treturn imageSpec.Name\n\t}\n\n\timg := defaulting.NewImage(imageSpec.Name, imageSpec.Tag, imageSpec.JMXEnabled)\n\n\tif registry != nil && *registry != \"\" {\n\t\tdefaulting.WithRegistry(defaulting.ContainerRegistry(*registry))(img)\n\t}\n\n\treturn img.String()\n}", "func dirImageMock(t *testing.T, dir, dockerReference string) private.UnparsedImage {\n\tref, err := reference.ParseNormalizedNamed(dockerReference)\n\trequire.NoError(t, err)\n\treturn dirImageMockWithRef(t, dir, refImageReferenceMock{ref: ref})\n}", "func (o BuildRunStatusBuildSpecOutputPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildRunStatusBuildSpecOutput) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func (o BuildRunSpecOutputPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildRunSpecOutput) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func (i *LibpodAPI) PullImage(call ioprojectatomicpodman.VarlinkCall, name string) error {\n\truntime, err := libpodruntime.GetRuntime(i.Cli)\n\tif err != nil {\n\t\treturn call.ReplyRuntimeError(err.Error())\n\t}\n\tnewImage, err := runtime.ImageRuntime().New(getContext(), name, \"\", \"\", nil, &image.DockerRegistryOptions{}, image.SigningOptions{}, true, false)\n\tif err != nil {\n\t\treturn call.ReplyErrorOccurred(fmt.Sprintf(\"unable to pull %s: %s\", name, err.Error()))\n\t}\n\treturn call.ReplyPullImage(newImage.ID())\n}", "func (o IopingSpecVolumeVolumeSourceRbdOutput) Image() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceRbd) string { return v.Image }).(pulumi.StringOutput)\n}", "func (adpt *DockerRunAdapter) Image() string {\n\tspec := (*yaml.Option)(adpt)\n\n\treturn fmt.Sprintf(\"%s:${%s_VERSION:-\\\"%s\\\"}\", spec.Image, strings.ToUpper(spec.Path.Base()), spec.Tag)\n}", "func (s *VarlinkInterface) PullImage(ctx context.Context, c VarlinkCall, name_ string) error {\n\treturn c.ReplyMethodNotImplemented(ctx, \"io.podman.PullImage\")\n}", "func (m *kubeGenericRuntimeManager) GetDesiredImagePuller(pod *v1.Pod) (images.ImageManager, error) {\n\n\timageBackOff := flowcontrol.NewBackOff(10*time.Second, 300*time.Second)\n\n\t// TODO: get the hardcoded parameters to the ImageManager constructor from config\n\treturn images.NewImageManager(\n\t\tkubecontainer.FilterEventRecorder(m.recorder),\n\t\tm,\n\t\timageBackOff,\n\t\ttrue,\n\t\t0.0,\n\t\t100), nil\n\n}", "func (o BuildRunStatusBuildSpecRuntimeBasePtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BuildRunStatusBuildSpecRuntimeBase) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func PGAdminContainerImage(cluster *v1beta1.PostgresCluster) string {\n\tvar image string\n\tif cluster.Spec.UserInterface != nil &&\n\t\tcluster.Spec.UserInterface.PGAdmin != nil {\n\t\timage = cluster.Spec.UserInterface.PGAdmin.Image\n\t}\n\n\treturn defaultFromEnv(image, \"RELATED_IMAGE_PGADMIN\")\n}", "func (o StorageClusterSpecPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *StorageClusterSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ArgoCDSpecRedisOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecRedis) *string { return v.Image }).(pulumi.StringPtrOutput)\n}", "func (o ArgoCDSpecGrafanaOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecGrafana) *string { return v.Image }).(pulumi.StringPtrOutput)\n}", "func (o FioSpecVolumeVolumeSourceRbdOutput) Image() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceRbd) string { return v.Image }).(pulumi.StringOutput)\n}", "func (i *ImageInspectCommand) example() string {\n\treturn `$ pouch image inspect docker.io/library/busybox\n{\n \"CreatedAt\": \"2017-12-21 04:30:57\",\n \"Digest\": \"sha256:bbc3a03235220b170ba48a157dd097dd1379299370e1ed99ce976df0355d24f0\",\n \"ID\": \"bbc3a0323522\",\n \"Name\": \"docker.io/library/busybox:latest\",\n \"Size\": 720019,\n \"Tag\": \"latest\"\n}`\n}", "func ReferencedImages(deployment *deployapi.Deployment) map[string]string {\n\tresult := make(map[string]string)\n\n\tif deployment == nil {\n\t\treturn result\n\t}\n\n\tfor _, container := range deployment.ControllerTemplate.Template.Spec.Containers {\n\t\tname, version := ParseContainerImage(container.Image)\n\t\tresult[name] = version\n\t}\n\n\treturn result\n}", "func StartWithOptions(options *Options) (*Registry, error) {\n\tif options == nil {\n\t\toptions = &Options{}\n\t}\n\n\tvar args []string\n\tif options.Image != \"\" {\n\t\targs = append(args, \"-i\", options.Image)\n\t}\n\targs = append(args, \"start\")\n\n\tpodmanCmd := []string{\"podman\"}\n\tif options.PodmanPath != \"\" {\n\t\tpodmanCmd[0] = options.PodmanPath\n\t}\n\tif len(options.PodmanArgs) != 0 {\n\t\tpodmanCmd = append(podmanCmd, options.PodmanArgs...)\n\t}\n\n\t// Start a registry.\n\tos.Setenv(\"PODMAN\", strings.Join(podmanCmd, \" \"))\n\tout, err := utils.ExecCmd(binary, args...)\n\tos.Unsetenv(\"PODMAN\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"running %q: %s: %w\", binary, out, err)\n\t}\n\n\t// Parse the output.\n\tregistry := Registry{}\n\tfor _, s := range strings.Split(out, \"\\n\") {\n\t\tif s == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tspl := strings.Split(s, \"=\")\n\t\tif len(spl) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"unexpected output format %q: want 'PODMAN_...=...'\", s)\n\t\t}\n\t\tkey := spl[0]\n\t\tval := strings.TrimSuffix(strings.TrimPrefix(spl[1], \"\\\"\"), \"\\\"\")\n\t\tswitch key {\n\t\tcase ImageKey:\n\t\t\tregistry.Image = val\n\t\tcase UserKey:\n\t\t\tregistry.User = val\n\t\tcase PassKey:\n\t\t\tregistry.Password = val\n\t\tcase PortKey:\n\t\t\tregistry.Port = val\n\t\tdefault:\n\t\t\tlogrus.Errorf(\"Unexpected podman-registry output: %q\", s)\n\t\t}\n\t}\n\n\t// Extra sanity check.\n\tif registry.Image == \"\" {\n\t\treturn nil, fmt.Errorf(\"unexpected output %q: %q missing\", out, ImageKey)\n\t}\n\tif registry.User == \"\" {\n\t\treturn nil, fmt.Errorf(\"unexpected output %q: %q missing\", out, UserKey)\n\t}\n\tif registry.Password == \"\" {\n\t\treturn nil, fmt.Errorf(\"unexpected output %q: %q missing\", out, PassKey)\n\t}\n\tif registry.Port == \"\" {\n\t\treturn nil, fmt.Errorf(\"unexpected output %q: %q missing\", out, PortKey)\n\t}\n\n\tregistry.running = true\n\n\treturn &registry, nil\n}", "func (p *P) Image() string {\n\treturn fmt.Sprintf(\"docker.io/influxdb:%s\", p.Version)\n}", "func (d Docker) LookupImage(name string) (*image.Image, error) {\n\treturn d.Daemon.GetImage(name)\n}", "func (mgr *deploymentManager) imageName() string {\n\treturn fmt.Sprintf(\"%s:%s\", mgr.serverImageName, mgr.serverVersion)\n}", "func (o ArgoCDExportSpecOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDExportSpec) *string { return v.Image }).(pulumi.StringPtrOutput)\n}", "func (i *LibpodAPI) SearchImage(call ioprojectatomicpodman.VarlinkCall, name string, limit int64) error {\n\tsc := image.GetSystemContext(\"\", \"\", false)\n\tregistries, err := sysreg.GetRegistries()\n\tif err != nil {\n\t\treturn call.ReplyErrorOccurred(fmt.Sprintf(\"unable to get system registries: %q\", err))\n\t}\n\tvar imageResults []ioprojectatomicpodman.ImageSearch\n\tfor _, reg := range registries {\n\t\tresults, err := docker.SearchRegistry(getContext(), sc, reg, name, int(limit))\n\t\tif err != nil {\n\t\t\treturn call.ReplyErrorOccurred(err.Error())\n\t\t}\n\t\tfor _, result := range results {\n\t\t\ti := ioprojectatomicpodman.ImageSearch{\n\t\t\t\tDescription: result.Description,\n\t\t\t\tIs_official: result.IsOfficial,\n\t\t\t\tIs_automated: result.IsAutomated,\n\t\t\t\tName: result.Name,\n\t\t\t\tStar_count: int64(result.StarCount),\n\t\t\t}\n\t\t\timageResults = append(imageResults, i)\n\t\t}\n\t}\n\treturn call.ReplySearchImage(imageResults)\n}", "func (o StorageClusterSpecOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageClusterSpec) *string { return v.Image }).(pulumi.StringPtrOutput)\n}", "func (r *Registry) ImageManifest(image Image, token string) (*ImageManifest, error) {\n\turl := r.GetDigestUrl(image)\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Accept\", schema2.MediaTypeManifest)\n\tif token != \"\" {\n\t\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token))\n\t}\n\n\tresp, err := r.Client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\trespBody, _ := GetRespBody(resp)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tif resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusUnauthorized {\n\t\t\tklog.Error(statusUnauthorized)\n\t\t\treturn nil, restful.NewError(resp.StatusCode, statusUnauthorized)\n\t\t}\n\t\tklog.Errorf(\"got response: statusCode is '%d', body is '%s'\\n\", resp.StatusCode, respBody)\n\t\treturn nil, restful.NewError(resp.StatusCode, \"got image manifest failed\")\n\t}\n\n\timageManifest := &ImageManifest{}\n\terr = json.Unmarshal(respBody, imageManifest)\n\n\treturn imageManifest, err\n}", "func (cli *DockerCli) ImageLoadFromDaemon(ctx context.Context, name string, quiet bool) (*types.ImageLoadResponse, error) {\n\tif !quiet {\n\t\tfmt.Fprintln(cli.out, \"Loading image from local docker daemon...\")\n\t}\n\n\ttr, err := cli.client.ImageSaveTarFromDaemon(ctx, []string{name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer tr.Close()\n\n\treturn cli.ImageLoadFromTar(ctx, tr, quiet)\n}", "func RunInsideImageFS(podmanEngine cli.PodmanEngine, image string, containerFn ContainerFn) (bool, error) {\n\treport, err := podmanEngine.MountImage(image)\n\tif err != nil {\n\t\tlog.Error(\"stdout: \", report.Stdout)\n\t\tlog.Error(\"stderr: \", report.Stderr)\n\t\tlog.Error(\"could not mount filesystem\", err)\n\t\treturn false, err\n\t}\n\n\tdefer func() {\n\t\treport, err := podmanEngine.UnmountImage(image)\n\t\tif err != nil {\n\t\t\tlog.Warn(\"stdout: \", report.Stdout)\n\t\t\tlog.Warn(\"stderr: \", report.Stderr)\n\t\t}\n\t}()\n\n\treturn containerFn(migration.ImageToImageReference(strings.TrimSpace(report.MountDir)))\n}", "func (b *EtcdManagerBuilder) buildPod(etcdCluster kops.EtcdClusterSpec, instanceGroupName string) (*v1.Pod, error) {\n\tvar pod *v1.Pod\n\tvar container *v1.Container\n\n\tvar manifest []byte\n\n\t// TODO: pull from bundle\n\tbundle := \"(embedded etcd manifest)\"\n\tmanifest = []byte(defaultManifest)\n\n\t{\n\t\tobjects, err := model.ParseManifest(manifest)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(objects) != 1 {\n\t\t\treturn nil, fmt.Errorf(\"expected exactly one object in manifest %s, found %d\", bundle, len(objects))\n\t\t}\n\t\tif podObject, ok := objects[0].(*v1.Pod); !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected v1.Pod object in manifest %s, found %T\", bundle, objects[0])\n\t\t} else {\n\t\t\tpod = podObject\n\t\t}\n\t}\n\n\t{\n\t\tutilMounts := []v1.VolumeMount{\n\t\t\t{\n\t\t\t\tMountPath: \"/opt\",\n\t\t\t\tName: \"opt\",\n\t\t\t},\n\t\t}\n\t\t{\n\t\t\tinitContainer := v1.Container{\n\t\t\t\tName: \"kops-utils-cp\",\n\t\t\t\tImage: kopsUtilsImage,\n\t\t\t\tCommand: []string{\"/ko-app/kops-utils-cp\"},\n\t\t\t\tArgs: []string{\n\t\t\t\t\t\"--target-dir=/opt/kops-utils/\",\n\t\t\t\t\t\"--src=/ko-app/kops-utils-cp\",\n\t\t\t\t},\n\t\t\t\tVolumeMounts: utilMounts,\n\t\t\t}\n\t\t\tpod.Spec.InitContainers = append(pod.Spec.InitContainers, initContainer)\n\t\t}\n\n\t\tsymlinkToVersions := sets.NewString()\n\t\tfor _, etcdVersion := range etcdSupportedVersions() {\n\t\t\tif etcdVersion.SymlinkToVersion != \"\" {\n\t\t\t\tsymlinkToVersions.Insert(etcdVersion.SymlinkToVersion)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tinitContainer := v1.Container{\n\t\t\t\tName: \"init-etcd-\" + strings.ReplaceAll(etcdVersion.Version, \".\", \"-\"),\n\t\t\t\tImage: etcdVersion.Image,\n\t\t\t\tCommand: []string{\"/opt/kops-utils/kops-utils-cp\"},\n\t\t\t\tVolumeMounts: utilMounts,\n\t\t\t}\n\n\t\t\tinitContainer.Args = []string{\n\t\t\t\t\"--target-dir=/opt/etcd-v\" + etcdVersion.Version,\n\t\t\t\t\"--src=/usr/local/bin/etcd\",\n\t\t\t\t\"--src=/usr/local/bin/etcdctl\",\n\t\t\t}\n\n\t\t\tpod.Spec.InitContainers = append(pod.Spec.InitContainers, initContainer)\n\t\t}\n\n\t\tfor _, symlinkToVersion := range symlinkToVersions.List() {\n\t\t\ttargetVersions := sets.NewString()\n\n\t\t\tfor _, etcdVersion := range etcdSupportedVersions() {\n\t\t\t\tif etcdVersion.SymlinkToVersion == symlinkToVersion {\n\t\t\t\t\ttargetVersions.Insert(etcdVersion.Version)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinitContainer := v1.Container{\n\t\t\t\tName: \"init-etcd-symlinks-\" + strings.ReplaceAll(symlinkToVersion, \".\", \"-\"),\n\t\t\t\tImage: kopsUtilsImage,\n\t\t\t\tCommand: []string{\"/opt/kops-utils/kops-utils-cp\"},\n\t\t\t\tVolumeMounts: utilMounts,\n\t\t\t}\n\n\t\t\tinitContainer.Args = []string{\n\t\t\t\t\"--symlink\",\n\t\t\t}\n\t\t\tfor _, targetVersion := range targetVersions.List() {\n\t\t\t\tinitContainer.Args = append(initContainer.Args, \"--target-dir=/opt/etcd-v\"+targetVersion)\n\t\t\t}\n\t\t\t// NOTE: Flags must come before positional arguments\n\t\t\tinitContainer.Args = append(initContainer.Args,\n\t\t\t\t\"--src=/opt/etcd-v\"+symlinkToVersion+\"/etcd\",\n\t\t\t\t\"--src=/opt/etcd-v\"+symlinkToVersion+\"/etcdctl\",\n\t\t\t)\n\n\t\t\tpod.Spec.InitContainers = append(pod.Spec.InitContainers, initContainer)\n\t\t}\n\n\t\t// Remap image via AssetBuilder\n\t\tfor i := range pod.Spec.InitContainers {\n\t\t\tinitContainer := &pod.Spec.InitContainers[i]\n\t\t\tremapped, err := b.AssetBuilder.RemapImage(initContainer.Image)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to remap init container image %q: %w\", container.Image, err)\n\t\t\t}\n\t\t\tinitContainer.Image = remapped\n\t\t}\n\t}\n\n\t{\n\t\tif len(pod.Spec.Containers) != 1 {\n\t\t\treturn nil, fmt.Errorf(\"expected exactly one container in etcd-manager Pod, found %d\", len(pod.Spec.Containers))\n\t\t}\n\t\tcontainer = &pod.Spec.Containers[0]\n\n\t\tif etcdCluster.Manager != nil && etcdCluster.Manager.Image != \"\" {\n\t\t\tklog.Warningf(\"overloading image in manifest %s with images %s\", bundle, etcdCluster.Manager.Image)\n\t\t\tcontainer.Image = etcdCluster.Manager.Image\n\t\t}\n\n\t\t// Remap image via AssetBuilder\n\t\tremapped, err := b.AssetBuilder.RemapImage(container.Image)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to remap container image %q: %w\", container.Image, err)\n\t\t}\n\t\tcontainer.Image = remapped\n\t}\n\n\tvar clientHost string\n\n\tif featureflag.APIServerNodes.Enabled() {\n\t\tclientHost = etcdCluster.Name + \".etcd.internal.\" + b.ClusterName()\n\t} else {\n\t\tclientHost = \"__name__\"\n\t}\n\n\tclusterName := \"etcd-\" + etcdCluster.Name\n\tbackupStore := \"\"\n\tif etcdCluster.Backups != nil {\n\t\tbackupStore = etcdCluster.Backups.BackupStore\n\t}\n\n\tpod.Name = \"etcd-manager-\" + etcdCluster.Name\n\n\tif pod.Annotations == nil {\n\t\tpod.Annotations = make(map[string]string)\n\t}\n\n\tif featureflag.APIServerNodes.Enabled() {\n\t\tpod.Annotations[\"dns.alpha.kubernetes.io/internal\"] = clientHost\n\t}\n\n\tif pod.Labels == nil {\n\t\tpod.Labels = make(map[string]string)\n\t}\n\tfor k, v := range SelectorForCluster(etcdCluster) {\n\t\tpod.Labels[k] = v\n\t}\n\n\t// The dns suffix logic mirrors the existing logic, so we should be compatible with existing clusters\n\t// (etcd makes it difficult to change peer urls, treating it as a cluster event, for reasons unknown)\n\tdnsInternalSuffix := \".internal.\" + b.Cluster.Name\n\n\tports, err := PortsForCluster(etcdCluster)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch etcdCluster.Name {\n\tcase \"main\":\n\t\tclusterName = \"etcd\"\n\n\tcase \"events\":\n\t\t// ok\n\n\tcase \"cilium\":\n\t\tif !featureflag.APIServerNodes.Enabled() {\n\t\t\tclientHost = b.Cluster.APIInternalName()\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown etcd cluster key %q\", etcdCluster.Name)\n\t}\n\n\tif backupStore == \"\" {\n\t\treturn nil, fmt.Errorf(\"backupStore must be set for use with etcd-manager\")\n\t}\n\n\tname := clusterName\n\tif !strings.HasPrefix(name, \"etcd\") {\n\t\t// For sanity, and to avoid collisions in directories / dns\n\t\treturn nil, fmt.Errorf(\"unexpected name for etcd cluster (must start with etcd): %q\", name)\n\t}\n\tlogFile := \"/var/log/\" + name + \".log\"\n\n\tconfig := &config{\n\t\tContainerized: true,\n\t\tClusterName: clusterName,\n\t\tBackupStore: backupStore,\n\t\tGrpcPort: ports.GRPCPort,\n\t\tDNSSuffix: dnsInternalSuffix,\n\t}\n\n\tconfig.LogLevel = 6\n\n\tif etcdCluster.Manager != nil && etcdCluster.Manager.LogLevel != nil {\n\t\tklog.Warningf(\"overriding log level in manifest %s, new level is %d\", bundle, int(*etcdCluster.Manager.LogLevel))\n\t\tconfig.LogLevel = int(*etcdCluster.Manager.LogLevel)\n\t}\n\n\tif etcdCluster.Manager != nil && etcdCluster.Manager.BackupInterval != nil {\n\t\tconfig.BackupInterval = fi.PtrTo(etcdCluster.Manager.BackupInterval.Duration.String())\n\t}\n\n\tif etcdCluster.Manager != nil && etcdCluster.Manager.DiscoveryPollInterval != nil {\n\t\tconfig.DiscoveryPollInterval = fi.PtrTo(etcdCluster.Manager.DiscoveryPollInterval.Duration.String())\n\t}\n\n\t{\n\t\tscheme := \"https\"\n\n\t\tconfig.PeerUrls = fmt.Sprintf(\"%s://__name__:%d\", scheme, ports.PeerPort)\n\t\tconfig.ClientUrls = fmt.Sprintf(\"%s://%s:%d\", scheme, clientHost, ports.ClientPort)\n\t\tconfig.QuarantineClientUrls = fmt.Sprintf(\"%s://__name__:%d\", scheme, ports.QuarantinedGRPCPort)\n\n\t\t// TODO: We need to wire these into the etcd-manager spec\n\t\t// // add timeout/heartbeat settings\n\t\tif etcdCluster.LeaderElectionTimeout != nil {\n\t\t\t// envs = append(envs, v1.EnvVar{Name: \"ETCD_ELECTION_TIMEOUT\", Value: convEtcdSettingsToMs(etcdClusterSpec.LeaderElectionTimeout)})\n\t\t\treturn nil, fmt.Errorf(\"LeaderElectionTimeout not supported by etcd-manager\")\n\t\t}\n\t\tif etcdCluster.HeartbeatInterval != nil {\n\t\t\t// envs = append(envs, v1.EnvVar{Name: \"ETCD_HEARTBEAT_INTERVAL\", Value: convEtcdSettingsToMs(etcdClusterSpec.HeartbeatInterval)})\n\t\t\treturn nil, fmt.Errorf(\"HeartbeatInterval not supported by etcd-manager\")\n\t\t}\n\t}\n\n\t{\n\t\tswitch b.Cluster.Spec.GetCloudProvider() {\n\t\tcase kops.CloudProviderAWS:\n\t\t\tconfig.VolumeProvider = \"aws\"\n\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\tfmt.Sprintf(\"kubernetes.io/cluster/%s=owned\", b.Cluster.Name),\n\t\t\t\tawsup.TagNameEtcdClusterPrefix + etcdCluster.Name,\n\t\t\t\tawsup.TagNameRolePrefix + \"control-plane=1\",\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = awsup.TagNameEtcdClusterPrefix + etcdCluster.Name\n\n\t\tcase kops.CloudProviderAzure:\n\t\t\tconfig.VolumeProvider = \"azure\"\n\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\t// Use dash (_) as a splitter. Other CSPs use slash (/), but slash is not\n\t\t\t\t// allowed as a tag key in Azure.\n\t\t\t\tfmt.Sprintf(\"kubernetes.io_cluster_%s=owned\", b.Cluster.Name),\n\t\t\t\tazure.TagNameEtcdClusterPrefix + etcdCluster.Name,\n\t\t\t\tazure.TagNameRolePrefix + \"control_plane=1\",\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = azure.TagNameEtcdClusterPrefix + etcdCluster.Name\n\n\t\tcase kops.CloudProviderGCE:\n\t\t\tconfig.VolumeProvider = \"gce\"\n\n\t\t\tclusterLabel := gce.LabelForCluster(b.Cluster.Name)\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\tclusterLabel.Key + \"=\" + clusterLabel.Value,\n\t\t\t\tgce.GceLabelNameEtcdClusterPrefix + etcdCluster.Name,\n\t\t\t\tgce.GceLabelNameRolePrefix + \"master=master\",\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = gce.GceLabelNameEtcdClusterPrefix + etcdCluster.Name\n\n\t\tcase kops.CloudProviderDO:\n\t\t\tconfig.VolumeProvider = \"do\"\n\n\t\t\t// DO does not support . in tags / names\n\t\t\tsafeClusterName := do.SafeClusterName(b.Cluster.Name)\n\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\tfmt.Sprintf(\"%s=%s\", do.TagKubernetesClusterNamePrefix, safeClusterName),\n\t\t\t\tdo.TagKubernetesClusterIndex,\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = do.TagNameEtcdClusterPrefix + etcdCluster.Name\n\n\t\tcase kops.CloudProviderHetzner:\n\t\t\tconfig.VolumeProvider = \"hetzner\"\n\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\tfmt.Sprintf(\"%s=%s\", hetzner.TagKubernetesClusterName, b.Cluster.Name),\n\t\t\t\tfmt.Sprintf(\"%s=%s\", hetzner.TagKubernetesVolumeRole, etcdCluster.Name),\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = fmt.Sprintf(\"%s=%s\", hetzner.TagKubernetesInstanceGroup, instanceGroupName)\n\n\t\tcase kops.CloudProviderOpenstack:\n\t\t\tconfig.VolumeProvider = \"openstack\"\n\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\topenstack.TagNameEtcdClusterPrefix + etcdCluster.Name,\n\t\t\t\topenstack.TagNameRolePrefix + \"control-plane=1\",\n\t\t\t\tfmt.Sprintf(\"%s=%s\", openstack.TagClusterName, b.Cluster.Name),\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = openstack.TagNameEtcdClusterPrefix + etcdCluster.Name\n\t\t\tconfig.NetworkCIDR = fi.PtrTo(b.Cluster.Spec.Networking.NetworkCIDR)\n\n\t\tcase kops.CloudProviderScaleway:\n\t\t\tconfig.VolumeProvider = \"scaleway\"\n\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\tfmt.Sprintf(\"%s=%s\", scaleway.TagClusterName, b.Cluster.Name),\n\t\t\t\tfmt.Sprintf(\"%s=%s\", scaleway.TagNameEtcdClusterPrefix, etcdCluster.Name),\n\t\t\t\tfmt.Sprintf(\"%s=%s\", scaleway.TagNameRolePrefix, scaleway.TagRoleControlPlane),\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = fmt.Sprintf(\"%s=%s\", scaleway.TagInstanceGroup, instanceGroupName)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"CloudProvider %q not supported with etcd-manager\", b.Cluster.Spec.GetCloudProvider())\n\t\t}\n\t}\n\n\targs, err := flagbuilder.BuildFlagsList(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t{\n\t\tcontainer.Command = exec.WithTee(\"/etcd-manager\", args, \"/var/log/etcd.log\")\n\n\t\tcpuRequest := resource.MustParse(\"200m\")\n\t\tif etcdCluster.CPURequest != nil {\n\t\t\tcpuRequest = *etcdCluster.CPURequest\n\t\t}\n\t\tmemoryRequest := resource.MustParse(\"100Mi\")\n\t\tif etcdCluster.MemoryRequest != nil {\n\t\t\tmemoryRequest = *etcdCluster.MemoryRequest\n\t\t}\n\n\t\tcontainer.Resources = v1.ResourceRequirements{\n\t\t\tRequests: v1.ResourceList{\n\t\t\t\tv1.ResourceCPU: cpuRequest,\n\t\t\t\tv1.ResourceMemory: memoryRequest,\n\t\t\t},\n\t\t}\n\n\t\tkubemanifest.AddHostPathMapping(pod, container, \"varlogetcd\", \"/var/log/etcd.log\",\n\t\t\tkubemanifest.WithReadWrite(),\n\t\t\tkubemanifest.WithType(v1.HostPathFileOrCreate),\n\t\t\tkubemanifest.WithHostPath(logFile))\n\n\t\tif fi.ValueOf(b.Cluster.Spec.UseHostCertificates) {\n\t\t\tkubemanifest.AddHostPathMapping(pod, container, \"etc-ssl-certs\", \"/etc/ssl/certs\", kubemanifest.WithType(v1.HostPathDirectoryOrCreate))\n\t\t}\n\t}\n\n\tenvMap := env.BuildSystemComponentEnvVars(&b.Cluster.Spec)\n\n\tcontainer.Env = envMap.ToEnvVars()\n\n\tif etcdCluster.Manager != nil {\n\t\tif etcdCluster.Manager.BackupRetentionDays != nil {\n\t\t\tenvVar := v1.EnvVar{\n\t\t\t\tName: \"ETCD_MANAGER_DAILY_BACKUPS_RETENTION\",\n\t\t\t\tValue: strconv.FormatUint(uint64(fi.ValueOf(etcdCluster.Manager.BackupRetentionDays)), 10) + \"d\",\n\t\t\t}\n\n\t\t\tcontainer.Env = append(container.Env, envVar)\n\t\t}\n\n\t\tif len(etcdCluster.Manager.ListenMetricsURLs) > 0 {\n\t\t\tenvVar := v1.EnvVar{\n\t\t\t\tName: \"ETCD_LISTEN_METRICS_URLS\",\n\t\t\t\tValue: strings.Join(etcdCluster.Manager.ListenMetricsURLs, \",\"),\n\t\t\t}\n\n\t\t\tcontainer.Env = append(container.Env, envVar)\n\t\t}\n\n\t\tfor _, envVar := range etcdCluster.Manager.Env {\n\t\t\tklog.V(2).Infof(\"overloading ENV var in manifest %s with %s=%s\", bundle, envVar.Name, envVar.Value)\n\t\t\tconfigOverwrite := v1.EnvVar{\n\t\t\t\tName: envVar.Name,\n\t\t\t\tValue: envVar.Value,\n\t\t\t}\n\n\t\t\tcontainer.Env = append(container.Env, configOverwrite)\n\t\t}\n\t}\n\n\t{\n\t\tfoundPKI := false\n\t\tfor i := range pod.Spec.Volumes {\n\t\t\tv := &pod.Spec.Volumes[i]\n\t\t\tif v.Name == \"pki\" {\n\t\t\t\tif v.HostPath == nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"found PKI volume, but HostPath was nil\")\n\t\t\t\t}\n\t\t\t\tdirname := \"etcd-manager-\" + etcdCluster.Name\n\t\t\t\tv.HostPath.Path = \"/etc/kubernetes/pki/\" + dirname\n\t\t\t\tfoundPKI = true\n\t\t\t}\n\t\t}\n\t\tif !foundPKI {\n\t\t\treturn nil, fmt.Errorf(\"did not find PKI volume\")\n\t\t}\n\t}\n\n\tkubemanifest.MarkPodAsCritical(pod)\n\tkubemanifest.MarkPodAsClusterCritical(pod)\n\n\treturn pod, nil\n}", "func Build(k kubectl.CLI, pod string, d docker.CLI, options *Options, image string, context string, out *output.Interface) error {\n\treturn pkgerror(out.Do(\"Building image\", func(op output.Operation) error {\n\t\top.Progress(\"determining build node\")\n\t\tvar node string\n\t\tfor {\n\t\t\tvar err error\n\t\t\tnode, err = k.String(\"get\", \"pod\", pod, \"--output\", `go-template={{.spec.nodeName}}`)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t} else if node != \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t}\n\n\t\top.Progress(\"determining build pod\")\n\t\tnodePods, err := server.NodePods(k, out)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif nodePods[node] == \"\" {\n\t\t\treturn fmt.Errorf(\"cannot build on node %s\", node)\n\t\t}\n\n\t\top.Progress(\"connecting to docker daemon\")\n\t\tdockerPort, stop, err := portforward.StartOne(k, \"kube-system\", nodePods[node], \"2375\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer stop()\n\n\t\tbuildArgs := []string{\"--host\", \"localhost:\" + dockerPort, \"build\"}\n\t\tif options.File != \"\" {\n\t\t\tbuildArgs = append(buildArgs, \"--file\", options.File)\n\t\t}\n\t\tfor _, arg := range options.Args {\n\t\t\tbuildArgs = append(buildArgs, \"--build-arg\", arg)\n\t\t}\n\t\tif options.Target != \"\" {\n\t\t\tbuildArgs = append(buildArgs, \"--target\", options.Target)\n\t\t}\n\t\tbuildArgs = append(buildArgs, \"--tag\", image, context)\n\n\t\top.Progress(\"running\")\n\t\treturn d.EachLine(buildArgs, func(line string) {\n\t\t\tif out.Level < output.LevelVerbose && (strings.HasPrefix(line, \"Sending build context \") || strings.HasPrefix(line, \"Step \")) {\n\t\t\t\top.Progress(\"s\" + line[1:])\n\t\t\t} else {\n\t\t\t\tout.Verbose(\"[docker] %s\", line)\n\t\t\t}\n\t\t})\n\t}))\n}", "func (o ArgoCDSpecOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpec) *string { return v.Image }).(pulumi.StringPtrOutput)\n}", "func buildPrePullDaemonSet(component, image string) *apps.DaemonSet {\n\tvar gracePeriodSecs int64\n\treturn &apps.DaemonSet{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: addPrepullPrefix(component),\n\t\t\tNamespace: metav1.NamespaceSystem,\n\t\t},\n\t\tSpec: apps.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"k8s-app\": addPrepullPrefix(component),\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: v1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"k8s-app\": addPrepullPrefix(component),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: component,\n\t\t\t\t\t\t\tImage: image,\n\t\t\t\t\t\t\tCommand: []string{\"/bin/sleep\", \"3600\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tNodeSelector: map[string]string{\n\t\t\t\t\t\tconstants.LabelNodeRoleMaster: \"\",\n\t\t\t\t\t},\n\t\t\t\t\tTolerations: []v1.Toleration{constants.MasterToleration},\n\t\t\t\t\tTerminationGracePeriodSeconds: &gracePeriodSecs,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (i *LibpodAPI) PushImage(call ioprojectatomicpodman.VarlinkCall, name, tag string, tlsVerify bool) error {\n\truntime, err := libpodruntime.GetRuntime(i.Cli)\n\tif err != nil {\n\t\treturn call.ReplyRuntimeError(err.Error())\n\t}\n\tnewImage, err := runtime.ImageRuntime().NewFromLocal(name)\n\tif err != nil {\n\t\treturn call.ReplyImageNotFound(err.Error())\n\t}\n\tdestname := name\n\tif tag != \"\" {\n\t\tdestname = tag\n\t}\n\n\tdockerRegistryOptions := image.DockerRegistryOptions{\n\t\tDockerInsecureSkipTLSVerify: !tlsVerify,\n\t}\n\n\tso := image.SigningOptions{}\n\n\tif err := newImage.PushImage(getContext(), destname, \"\", \"\", \"\", nil, false, so, &dockerRegistryOptions, false); err != nil {\n\t\treturn call.ReplyErrorOccurred(err.Error())\n\t}\n\treturn call.ReplyPushImage(newImage.ID())\n}", "func getContainerImageManifest(ctr *container.Container) (ocispec.Descriptor, error) {\n\tif ctr.ImageManifest == nil {\n\t\treturn ocispec.Descriptor{}, errdefs.InvalidParameter(errors.New(\"container is missing ImageManifest (probably created on old version), please recreate it\"))\n\t}\n\n\treturn *ctr.ImageManifest, nil\n}", "func (o AtlasMapStatusPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AtlasMapStatus) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func (i *ImageManifest) RefName() string {\n\treturn i.Annotations[\"org.opencontainers.image.ref.name\"]\n}", "func (reg *registry) GetImage(img Repository, tag string) (_ flux.Image, err error) {\n\trem, err := reg.newRemote(img)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn rem.Manifest(img, tag)\n}", "func resolveImagePullSpec(imageClient imagetypedclient.ImageV1Interface, source, name, defaultNamespace string) (string, error) {\n\t// for Docker source, just passtrough the image name\n\tif isDockerImageSource(source) {\n\t\treturn name, nil\n\t}\n\t// parse the namespace from the provided image\n\tnamespace, image := splitNamespaceAndImage(name)\n\tif len(namespace) == 0 {\n\t\tnamespace = defaultNamespace\n\t}\n\n\tdockerImageReference := \"\"\n\n\tif isImageStreamTag(source) {\n\t\tif resolved, err := imageClient.ImageStreamTags(namespace).Get(context.TODO(), image, metav1.GetOptions{}); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to get image stream tag %q: %v\", image, err)\n\t\t} else {\n\t\t\tdockerImageReference = resolved.Image.DockerImageReference\n\t\t}\n\t}\n\n\tif isImageStreamImage(source) {\n\t\tif resolved, err := imageClient.ImageStreamImages(namespace).Get(context.TODO(), image, metav1.GetOptions{}); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to get image stream image %q: %v\", image, err)\n\t\t} else {\n\t\t\tdockerImageReference = resolved.Image.DockerImageReference\n\t\t}\n\t}\n\n\tif len(dockerImageReference) == 0 {\n\t\treturn \"\", fmt.Errorf(\"unable to resolve %s %q\", source, name)\n\t}\n\n\treturn clientcmd.ParseDockerImageReferenceToStringFunc(dockerImageReference)\n}", "func Pod(namespace, name string, phase kapi.PodPhase, containerImages ...string) kapi.Pod {\n\treturn AgedPod(namespace, name, phase, -1, containerImages...)\n}", "func (cli Client) ImagePull(options v1alpha1.OCIPullOptions) (v1alpha1.OCIPullResponse, error) {\n\n\tpullFlags := []command.Flag{\n\t\t// Buildah registry auth in format username[:password]\n\t\t{Name: \"creds\", Value: options.RegistryAuth, Short: false, OmitEmpty: true},\n\t}\n\n\tcmd := command.Builder(\"buildah\").Command(\"pull\").Flags(pullFlags...).Args(options.Ref).Build()\n\tcli.Logger.WithField(\"cmd\", cmd).Debugln(\"executing pull with command\")\n\n\tstdout, stderr, err := execute(&cmd)\n\tif err != nil {\n\t\tcli.Logger.WithError(err).Errorln(\"error building image...\")\n\t\treturn v1alpha1.OCIPullResponse{}, err\n\t}\n\treturn v1alpha1.OCIPullResponse{\n\t\tBody: stdout,\n\t\tExec: &cmd,\n\t\tStderr: stderr,\n\t}, nil\n}", "func genpod(namespace, name, image string) *corev1.Pod {\n\tvar userID int64 = 65534\n\n\treturn &corev1.Pod{\n\t\tMetadata: &metav1.ObjectMeta{\n\t\t\tName: k8s.String(name),\n\t\t\tNamespace: k8s.String(namespace),\n\t\t\tLabels: map[string]string{\"generator\": \"kboom\"},\n\t\t},\n\t\tSpec: &corev1.PodSpec{\n\t\t\tContainers: []*corev1.Container{\n\t\t\t\t&corev1.Container{\n\t\t\t\t\tName: k8s.String(\"main\"),\n\t\t\t\t\tImage: k8s.String(image),\n\t\t\t\t\tCommand: []string{\"/bin/sh\", \"-ec\", \"sleep 3600\"},\n\t\t\t\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\t\t\t\tRunAsUser: &userID,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (d *Docker) CreateImage(parentRef string) {}", "func (a *AgentServer) PullImage(req PullImageRequest, image *string) error {\n\n\tlogger := plog.WithFields(logrus.Fields{\n\t\t\"image\": req.Image,\n\t\t\"registry\": req.Registry})\n\n\t// set up the connections\n\tdocker, err := docker.NewDockerClient()\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"Could not connect to docker client\")\n\t\treturn err\n\t}\n\tconn, err := zzk.GetLocalConnection(\"/\")\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"Could not acquire coordinator connection\")\n\t\treturn err\n\t}\n\n\t// pull the image from the registry\n\treg := registry.NewRegistryListener(docker, req.Registry, \"\")\n\treg.SetConnection(conn)\n\ttimer := time.NewTimer(req.Timeout)\n\tdefer timer.Stop()\n\tif err := reg.PullImage(timer.C, req.Image); err != nil {\n\t\tlogger.WithError(err).Error(\"Could not pull image from registry\")\n\t\treturn err\n\t}\n\n\t// get the tag of the image pulled\n\t*image, err = reg.ImagePath(req.Image)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"Could not get image id for image from registry\")\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (i *LibpodAPI) ImportImage(call ioprojectatomicpodman.VarlinkCall, source, reference, message string, changes []string) error {\n\truntime, err := libpodruntime.GetRuntime(i.Cli)\n\tif err != nil {\n\t\treturn call.ReplyRuntimeError(err.Error())\n\t}\n\tconfigChanges, err := util.GetImageConfig(changes)\n\tif err != nil {\n\t\treturn call.ReplyErrorOccurred(err.Error())\n\t}\n\thistory := []v1.History{\n\t\t{Comment: message},\n\t}\n\tconfig := v1.Image{\n\t\tConfig: configChanges,\n\t\tHistory: history,\n\t}\n\tnewImage, err := runtime.ImageRuntime().Import(getContext(), source, reference, nil, image.SigningOptions{}, config)\n\tif err != nil {\n\t\treturn call.ReplyErrorOccurred(err.Error())\n\t}\n\treturn call.ReplyImportImage(newImage.ID())\n}", "func (*UpdateImageMetadata) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_compute_v1_image_service_proto_rawDescGZIP(), []int{7}\n}", "func (c *container) Image() (string, error) {\n\timageSpec := c.config.Image\n\tif imageSpec == nil {\n\t\treturn \"\", errors.New(\"CreateContainerRequest.ContainerConfig.Image is nil\")\n\t}\n\n\timage := imageSpec.Image\n\tif image == \"\" {\n\t\treturn \"\", errors.New(\"CreateContainerRequest.ContainerConfig.Image.Image is empty\")\n\t}\n\treturn image, nil\n}", "func MakeDockerImageReference(ns, isName, imageID string) string {\n\treturn fmt.Sprintf(\"%s/%s/%s@%s\", InternalRegistryURL, ns, isName, imageID)\n}", "func PMMContainer(spec api.PMMSpec, secrets string) corev1.Container {\n\treturn corev1.Container{\n\t\tName: \"pmm-client\",\n\t\tImage: spec.Image,\n\t\tImagePullPolicy: corev1.PullAlways,\n\t\tEnv: []corev1.EnvVar{\n\t\t\t{\n\t\t\t\tName: \"PMM_SERVER\",\n\t\t\t\tValue: spec.ServerHost,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"DB_TYPE\",\n\t\t\t\tValue: \"mongodb\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"MONGODB_USER\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tSecretKeyRef: &corev1.SecretKeySelector{\n\t\t\t\t\t\tKey: \"MONGODB_CLUSTER_MONITOR_USER\",\n\t\t\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\t\t\tName: secrets,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"MONGODB_PASSWORD\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tSecretKeyRef: &corev1.SecretKeySelector{\n\t\t\t\t\t\tKey: \"MONGODB_CLUSTER_MONITOR_PASSWORD\",\n\t\t\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\t\t\tName: secrets,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"PMM_USER\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tSecretKeyRef: &corev1.SecretKeySelector{\n\t\t\t\t\t\tKey: \"PMM_SERVER_PASSWORD\",\n\t\t\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\t\t\tName: secrets,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"PMM_PASSWORD\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tSecretKeyRef: &corev1.SecretKeySelector{\n\t\t\t\t\t\tKey: \"PMM_SERVER_PASSWORD\",\n\t\t\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\t\t\tName: secrets,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"DB_ARGS\",\n\t\t\t\tValue: \"--uri=mongodb://$(MONGODB_USER):$(MONGODB_PASSWORD)@127.0.0.1:27017/\",\n\t\t\t},\n\t\t},\n\t}\n}", "func NewLibpodImageRuntime(flags *pflag.FlagSet, opts *entities.PodmanConfig) (entities.ImageEngine, error) {\n\tr, err := GetRuntime(context.Background(), flags, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &abi.ImageEngine{Libpod: r}, nil\n}", "func PGBouncerContainerImage(cluster *v1beta1.PostgresCluster) string {\n\tvar image string\n\tif cluster.Spec.Proxy != nil &&\n\t\tcluster.Spec.Proxy.PGBouncer != nil {\n\t\timage = cluster.Spec.Proxy.PGBouncer.Image\n\t}\n\n\treturn defaultFromEnv(image, \"RELATED_IMAGE_PGBOUNCER\")\n}", "func (d *DigitalOcean) Image(slug_or_name_or_id string) (digitalocean.Image, error) {\n\treturn d.Client.Image(slug_or_name_or_id)\n}", "func (o StorageClusterSpecAutopilotPtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *StorageClusterSpecAutopilot) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func imageConfig(diffIDs []digest.Digest) ocispec.Image {\n\timg := ocispec.Image{\n\t\tArchitecture: runtime.GOARCH,\n\t\tOS: runtime.GOOS,\n\t}\n\timg.RootFS.Type = \"layers\"\n\timg.RootFS.DiffIDs = diffIDs\n\timg.Config.WorkingDir = \"/\"\n\timg.Config.Env = []string{\"PATH=\" + system.DefaultPathEnv}\n\treturn img\n}", "func Exec(ctx context.Context, cfg *config.Config, pipeline *pipelines.Pipeline, name names.Name) (ImageRefs, error) {\n\tmanifest := pipeline.Deploy.Container.ParsedManifest\n\tif manifest == nil {\n\t\treturn nil, nil\n\t}\n\n\tdockerPath, err := cfg.ToolPath(config.Docker)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdk := docker{\n\t\tpath: dockerPath,\n\t}\n\n\trefs := make(map[string]string, len(manifest))\n\tvar mut sync.Mutex\n\tg, gctx := errgroup.WithContext(ctx)\n\tfor k, v := range manifest {\n\t\tk, v := k, v\n\t\tg.Go(func() error {\n\t\t\tref := v.Ref\n\t\t\tif ref == \"\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif len(pipeline.Deploy.Container.Label) > 0 {\n\t\t\t\texpandedLabels := make(map[string]string, len(pipeline.Deploy.Container.Label))\n\t\t\t\tfor _, lbl := range pipeline.Deploy.Container.Label {\n\t\t\t\t\tparts := strings.SplitN(lbl, \"=\", 2)\n\t\t\t\t\tif len(parts) != 2 {\n\t\t\t\t\t\treturn fmt.Errorf(\"unexpected label spec '%s'\", lbl)\n\t\t\t\t\t}\n\t\t\t\t\texpandedLabels[parts[0]] = os.ExpandEnv(parts[1])\n\t\t\t\t}\n\t\t\t\tnextRef, err := dk.build(gctx, cfg, ref, expandedLabels)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif pipeline.Deploy.Container.Push == \"\" {\n\t\t\t\t\tparts := strings.SplitN(ref, \":\", 2)\n\t\t\t\t\tref = parts[0] + \":\" + strings.Replace(nextRef, \"sha256:\", \"\", 1)\n\t\t\t\t\tif err := dk.tag(gctx, cfg, nextRef, ref); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif err := dk.push(gctx, cfg, ref); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif pipeline.Deploy.Container.Push != \"\" {\n\t\t\t\tparts := strings.SplitN(ref, \"/\", 2)\n\t\t\t\tregistry := os.ExpandEnv(pipeline.Deploy.Container.Push)\n\t\t\t\tvar nextRef string\n\t\t\t\tif len(parts) == 2 {\n\t\t\t\t\tnextRef = registry + \"/\" + parts[1]\n\t\t\t\t} else {\n\t\t\t\t\tnextRef = registry + \"/\" + ref\n\t\t\t\t}\n\t\t\t\tif err := dk.tag(gctx, cfg, ref, nextRef); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := dk.push(gctx, cfg, nextRef); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tref = nextRef\n\t\t\t}\n\t\t\tmut.Lock()\n\t\t\trefs[k] = ref\n\t\t\tmut.Unlock()\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tif err := g.Wait(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn refs, nil\n}", "func PatchServiceImage(t *testing.T, clients *Clients, svc *v1alpha1.Service, imagePath string) (*v1alpha1.Service, error) {\n\tnewSvc := svc.DeepCopy()\n\tif svc.Spec.DeprecatedRunLatest != nil {\n\t\tnewSvc.Spec.DeprecatedRunLatest.Configuration.GetTemplate().Spec.GetContainer().Image = imagePath\n\t} else if svc.Spec.DeprecatedRelease != nil {\n\t\tnewSvc.Spec.DeprecatedRelease.Configuration.GetTemplate().Spec.GetContainer().Image = imagePath\n\t} else if svc.Spec.DeprecatedPinned != nil {\n\t\tnewSvc.Spec.DeprecatedPinned.Configuration.GetTemplate().Spec.GetContainer().Image = imagePath\n\t} else {\n\t\tnewSvc.Spec.ConfigurationSpec.GetTemplate().Spec.GetContainer().Image = imagePath\n\t}\n\tLogResourceObject(t, ResourceObjects{Service: newSvc})\n\tpatchBytes, err := createPatch(svc, newSvc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clients.ServingClient.Services.Patch(svc.ObjectMeta.Name, types.JSONPatchType, patchBytes, \"\")\n}", "func Image(id, ref string) imageapi.Image {\n\treturn AgedImage(id, ref, 120)\n}", "func (o StorageClusterSpecAutopilotOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageClusterSpecAutopilot) *string { return v.Image }).(pulumi.StringPtrOutput)\n}", "func (p *BlackduckPatcher) patchImages() error {\n\tif p.blackDuckCr.Spec.RegistryConfiguration != nil && (len(p.blackDuckCr.Spec.RegistryConfiguration.Registry) > 0 || len(p.blackDuckCr.Spec.ImageRegistries) > 0) {\n\t\tfor _, v := range p.mapOfUniqueIdToBaseRuntimeObject {\n\t\t\tswitch v.(type) {\n\t\t\tcase *corev1.ReplicationController:\n\t\t\t\tfor i := range v.(*corev1.ReplicationController).Spec.Template.Spec.Containers {\n\t\t\t\t\tv.(*corev1.ReplicationController).Spec.Template.Spec.Containers[i].Image = controllers_utils.GenerateImageTag(v.(*corev1.ReplicationController).Spec.Template.Spec.Containers[i].Image, p.blackDuckCr.Spec.ImageRegistries, *p.blackDuckCr.Spec.RegistryConfiguration)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (o StorageClusterSpecUserInterfacePtrOutput) Image() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *StorageClusterSpecUserInterface) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Image\n\t}).(pulumi.StringPtrOutput)\n}", "func inspectImage(appCfg config.App) {\n\timage, err := serviceRuntime.InspectImage(appCfg.Version())\n\tif err != nil {\n\t\tlog.Println(\"error inspecting image\", appCfg.Version())\n\t\treturn\n\t}\n\n\tif utils.StripSHA(image.ID) != appCfg.VersionID() {\n\t\tlog.Printf(\"warning: %s image ID does not match config\", appCfg.Name())\n\t}\n}", "func inspectImage(appCfg config.App) {\n\timage, err := serviceRuntime.InspectImage(appCfg.Version())\n\tif err != nil {\n\t\tlog.Println(\"error inspecting image\", appCfg.Version())\n\t\treturn\n\t}\n\n\tif utils.StripSHA(image.ID) != appCfg.VersionID() {\n\t\tlog.Printf(\"warning: %s image ID does not match config\", appCfg.Name())\n\t}\n}", "func natsPodMetricsContainer(image, tag, pullPolicy string) v1.Container {\n\treturn v1.Container{\n\t\tName: \"metrics\",\n\t\tImage: fmt.Sprintf(\"%s:%s\", image, tag),\n\t\tImagePullPolicy: v1.PullPolicy(pullPolicy),\n\t\tCommand: []string{},\n\t\tPorts: []v1.ContainerPort{\n\t\t\t{\n\t\t\t\tName: \"metrics\",\n\t\t\t\tContainerPort: int32(constants.MetricsPort),\n\t\t\t\tProtocol: v1.ProtocolTCP,\n\t\t\t},\n\t\t},\n\t\tArgs: []string{\n\t\t\t\"-connz\",\n\t\t\t\"-routez\",\n\t\t\t\"-subz\",\n\t\t\t\"-varz\",\n\t\t\t\"-channelz\",\n\t\t\t\"-serverz\",\n\t\t\tfmt.Sprintf(\"http://localhost:%d\", constants.MonitoringPort)},\n\t}\n}", "func getImage() string {\n\tif config.ImageBuild == \"\" && config.ImageBuildFolder == \"\" {\n\t\treturn config.GetImageName()\n\t}\n\n\tif config.ImageBuildFolder == \"\" {\n\t\tconfig.ImageBuildFolder = \".\"\n\t}\n\n\tvar dockerFile string\n\tif config.ImageBuild != \"\" {\n\t\tout := Must(ioutil.TempFile(config.ImageBuildFolder, \"DockerFile\")).(*os.File)\n\t\tMust(fmt.Fprintf(out, \"FROM %s \\n%s\", config.GetImageName(), config.ImageBuild))\n\t\tMust(out.Close())\n\t\tdefer os.Remove(out.Name())\n\t\tdockerFile = out.Name()\n\t}\n\n\targs := []string{\"build\", config.ImageBuildFolder, \"--quiet\", \"--force-rm\"}\n\tif refresh {\n\t\targs = append(args, \"--pull\")\n\t}\n\tif dockerFile != \"\" {\n\t\targs = append(args, \"--file\")\n\t\targs = append(args, dockerFile)\n\t}\n\tbuildCmd := exec.Command(\"docker\", args...)\n\n\tif debug {\n\t\tprintfDebug(os.Stderr, \"%s\\n\", strings.Join(buildCmd.Args, \" \"))\n\t}\n\tbuildCmd.Stderr = os.Stderr\n\tbuildCmd.Dir = config.ImageBuildFolder\n\n\treturn strings.TrimSpace(string(Must(buildCmd.Output()).([]byte)))\n}", "func DockerImage() error {\n\tdockerImageTag := viper.GetString(\"docker-image-tag\")\n\tif dockerImageTag == \"\" {\n\t\treturn errors.Errorf(\"environment variable DOCKER_IMAGE_TAG not set\")\n\t}\n\n\terr := config.SetupOperatorDockerImage(\n\t\tviper.GetString(\"docker-image-org\"),\n\t\tviper.GetString(\"docker-image-repository\"),\n\t\tdockerImageTag,\n\t)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Couldn't parse docker image reference.\")\n\t}\n\n\terr = config.SetupOperatorImagePullPolicy(viper.GetString(\"docker-image-pull-policy\"))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Couldn't parse docker image pull policy.\")\n\t}\n\n\treturn nil\n}" ]
[ "0.6808878", "0.66259", "0.6014489", "0.57632554", "0.57444906", "0.5724609", "0.56687987", "0.56613916", "0.56557065", "0.56465936", "0.56103295", "0.55788076", "0.555107", "0.55340725", "0.5532543", "0.5526531", "0.5525078", "0.5503822", "0.54514915", "0.5446481", "0.54401803", "0.54377615", "0.54349774", "0.5427915", "0.5427051", "0.54209405", "0.54143363", "0.54114985", "0.5388323", "0.53836256", "0.53757846", "0.53660274", "0.53660274", "0.5356337", "0.53444546", "0.53367954", "0.5330831", "0.5307669", "0.52876836", "0.52833825", "0.52819234", "0.52704316", "0.5254273", "0.5252955", "0.52384", "0.52363664", "0.52288944", "0.52252084", "0.52169776", "0.5213934", "0.519879", "0.5196575", "0.5193668", "0.5192754", "0.51810235", "0.51743734", "0.5166104", "0.5153114", "0.5149685", "0.5140091", "0.5137877", "0.5135206", "0.5135186", "0.5121253", "0.51002467", "0.50867003", "0.5074095", "0.5072981", "0.50704", "0.506833", "0.50539154", "0.5046726", "0.5042682", "0.5042123", "0.5042013", "0.5041854", "0.5038132", "0.503533", "0.5030957", "0.5029689", "0.5024299", "0.50188285", "0.50167495", "0.50100315", "0.5007228", "0.5000372", "0.49950963", "0.4993613", "0.49921948", "0.49916318", "0.49910197", "0.49889326", "0.498674", "0.49826303", "0.49802205", "0.4977711", "0.4977711", "0.49698913", "0.49683094", "0.49668476" ]
0.8102636
0
PodmanWrite saves the image into podman as the given tag. same as github.com/google/gocontainerregistry/pkg/v1/daemon
func PodmanWrite(ref name.Reference, img v1.Image, opts ...tarball.WriteOption) (string, error) { pr, pw := io.Pipe() go func() { _ = pw.CloseWithError(tarball.Write(ref, img, pw, opts...)) }() // write the image in docker save format first, then load it cmd := exec.Command("sudo", "podman", "image", "load") cmd.Stdin = pr output, err := cmd.Output() if err != nil { return "", fmt.Errorf("error loading image: %v", err) } // pull the image from the registry, to get the digest too // podman: "Docker references with both a tag and digest are currently not supported" cmd = exec.Command("sudo", "podman", "image", "pull", strings.Split(ref.Name(), "@")[0]) err = cmd.Run() if err != nil { return "", fmt.Errorf("error pulling image: %v", err) } return string(output), nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func PodmanImage(ref name.Reference, options ...interface{}) (v1.Image, error) {\n\tvar img v1.Image\n\tpr, pw := io.Pipe()\n\tgo func() {\n\t\topener := func() (io.ReadCloser, error) {\n\t\t\treturn pr, nil\n\t\t}\n\t\tvar err error\n\t\ttag := ref.(name.Digest).Tag()\n\t\timg, err = tarball.Image(opener, &tag)\n\t\t_ = pr.CloseWithError(err)\n\t}()\n\n\t// write the image in docker save format first, then load it\n\tcmd := exec.Command(\"sudo\", \"podman\", \"image\", \"save\", strings.Split(ref.Name(), \"@\")[0])\n\tcmd.Stdout = pw\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error loading image: %v\", err)\n\t}\n\treturn img, nil\n}", "func RunPod(ctx context.Context, pod corev1.Pod,\n\tts oauth2.TokenSource, watcherImage, project, zone, machineType string) error {\n\n\tsvc, err := compute.NewService(ctx, option.WithTokenSource(ts))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb, err := yaml.Marshal(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpodstr := string(b)\n\tlog.Println(\"POD MANIFEST:\\n\", podstr) // TODO remove\n\n\tregion := zone[:strings.LastIndex(zone, \"-\")]\n\n\twatcherPod := fmt.Sprintf(watcherPodFmt, watcherImage)\n\n\tname := \"instance-\" + uuid.New().String()[:4]\n\tlog.Printf(\"creating %q...\", name)\n\top, err := svc.Instances.Insert(project, zone, &compute.Instance{\n\t\tName: name,\n\t\tZone: zone,\n\t\tMachineType: fmt.Sprintf(\"projects/%s/zones/%s/machineTypes/%s\", project, zone, machineType),\n\t\tDisks: []*compute.AttachedDisk{{\n\t\t\tInitializeParams: &compute.AttachedDiskInitializeParams{\n\t\t\t\tSourceImage: \"projects/cos-cloud/global/images/family/cos-stable\",\n\t\t\t},\n\t\t\tBoot: true,\n\t\t}},\n\t\tNetworkInterfaces: []*compute.NetworkInterface{{\n\t\t\tSubnetwork: fmt.Sprintf(\"projects/%s/regions/%s/subnetworks/default\", project, region),\n\t\t\tAccessConfigs: []*compute.AccessConfig{{\n\t\t\t\tName: \"External NAT\",\n\t\t\t\tType: \"ONE_TO_ONE_NAT\",\n\t\t\t\tNetworkTier: \"PREMIUM\",\n\t\t\t}},\n\t\t}},\n\t\tServiceAccounts: []*compute.ServiceAccount{{\n\t\t\tEmail: \"178371766757-compute@developer.gserviceaccount.com\",\n\t\t\tScopes: []string{\n\t\t\t\t// Permiission to pull private images (watcher)\n\t\t\t\t\"https://www.googleapis.com/auth/devstorage.read_only\",\n\n\t\t\t\t// Permission to write logs and metrics (google-fluentd)\n\t\t\t\t\"https://www.googleapis.com/auth/logging.write\",\n\t\t\t\t\"https://www.googleapis.com/auth/monitoring.write\",\n\t\t\t},\n\t\t}},\n\t\tMetadata: &compute.Metadata{\n\t\t\tItems: []*compute.MetadataItems{{\n\t\t\t\tKey: \"user-data\",\n\t\t\t\tValue: &cloudConfig,\n\t\t\t}, {\n\t\t\t\tKey: \"watcher\",\n\t\t\t\tValue: &watcherPod,\n\t\t\t}, {\n\t\t\t\tKey: \"pod\",\n\t\t\t\tValue: &podstr,\n\t\t\t}, {\n\t\t\t\tKey: \"ca-cert\",\n\t\t\t\tValue: &caCert,\n\t\t\t}, {\n\t\t\t\tKey: \"ca-cert-key\",\n\t\t\t\tValue: &caCertKey,\n\t\t\t}, {\n\t\t\t\tKey: \"cos-metrics-enabled\",\n\t\t\t\tValue: &trueString,\n\t\t\t}},\n\t\t},\n\t\tTags: &compute.Tags{Items: []string{\"https-server\"}},\n\t\tShieldedInstanceConfig: &compute.ShieldedInstanceConfig{\n\t\t\tEnableSecureBoot: true,\n\t\t},\n\t}).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstart := time.Now()\n\tfor ; ; time.Sleep(time.Second) {\n\t\top, err = svc.ZoneOperations.Get(project, zone, op.Name).Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Printf(\"operation is %q...\", op.Status)\n\t\tif op.Status == \"DONE\" {\n\t\t\tbreak\n\t\t}\n\t}\n\tlog.Println(\"startup took\", time.Since(start))\n\treturn nil\n}", "func Write(tag name.Tag, img v1.Image, options ...Option) (string, error) {\n\to, err := makeOptions(options...)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpr, pw := io.Pipe()\n\tgo func() {\n\t\tpw.CloseWithError(tarball.Write(tag, img, pw))\n\t}()\n\n\t// write the image in docker save format first, then load it\n\tresp, err := o.client.ImageLoad(o.ctx, pr, false)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error loading image: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\tb, err := io.ReadAll(resp.Body)\n\tresponse := string(b)\n\tif err != nil {\n\t\treturn response, fmt.Errorf(\"error reading load response body: %w\", err)\n\t}\n\treturn response, nil\n}", "func (i *LibpodAPI) PushImage(call ioprojectatomicpodman.VarlinkCall, name, tag string, tlsVerify bool) error {\n\truntime, err := libpodruntime.GetRuntime(i.Cli)\n\tif err != nil {\n\t\treturn call.ReplyRuntimeError(err.Error())\n\t}\n\tnewImage, err := runtime.ImageRuntime().NewFromLocal(name)\n\tif err != nil {\n\t\treturn call.ReplyImageNotFound(err.Error())\n\t}\n\tdestname := name\n\tif tag != \"\" {\n\t\tdestname = tag\n\t}\n\n\tdockerRegistryOptions := image.DockerRegistryOptions{\n\t\tDockerInsecureSkipTLSVerify: !tlsVerify,\n\t}\n\n\tso := image.SigningOptions{}\n\n\tif err := newImage.PushImage(getContext(), destname, \"\", \"\", \"\", nil, false, so, &dockerRegistryOptions, false); err != nil {\n\t\treturn call.ReplyErrorOccurred(err.Error())\n\t}\n\treturn call.ReplyPushImage(newImage.ID())\n}", "func (f *FakeRunner) podman(args []string, _ bool) (string, error) {\n\tswitch cmd := args[0]; cmd {\n\tcase \"--version\":\n\t\treturn \"podman version 1.6.4\", nil\n\n\tcase \"image\":\n\n\t\tif args[1] == \"inspect\" && args[2] == \"--format\" && args[3] == \"{{.Id}}\" {\n\t\t\tif args[3] == \"missing\" {\n\t\t\t\treturn \"\", &exec.ExitError{Stderr: []byte(\"Error: error getting image \\\"missing\\\": unable to find a name and tag match for missing in repotags: no such image\")}\n\t\t\t}\n\t\t\treturn \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\", nil\n\t\t}\n\n\t}\n\treturn \"\", nil\n}", "func generatePod(c *client.Client, podName string, nsName string, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tp := pod.Instance{\n\t\tName: podName,\n\t\tNamespace: nsName,\n\t\tImage: imageSource,\n\t\tLabelKey: \"app\",\n\t\tImagePullPolicy: \"ifnotpresent\",\n\t\tLabelValue: \"podTest\",\n\t}\n\n\ttimeNow := time.Now()\n\tfmt.Printf(\"creating pod %s in namespace %s\\n\", podName, nsName)\n\terr := pod.CreateWaitRunningState(c, &p)\n\t//if err != nil {\n\t//\tfmt.Printf(\"%s\\n\", err)\n\t//\tos.Exit(1)\n\t//}\n\n\tlastTime, err := pod.GetLastTimeConditionHappened(c,\n\t\t\"Ready\",\n\t\tpodName,\n\t\tnsName)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\thour := lastTime.Sub(timeNow).Hours()\n\thour, mf := math.Modf(hour)\n\ttotalHour = totalHour + hour\n\n\tminutes := mf * 60\n\tminutes, sf := math.Modf(minutes)\n\ttotalMinutes = totalMinutes + minutes\n\n\tseconds := sf * 60\n\ttotalSec = totalSec + seconds\n\n\tfmt.Printf(\"\\n- %s is created and responsive in namespace %s ✅\\n\", p.Name, p.Namespace)\n\tfmt.Printf(\"- image used: %s\\n\", imageSource)\n\n\tfmt.Println(\" took:\", hour, \"hours\",\n\t\tminutes, \"minutes\",\n\t\tseconds, \"seconds\")\n\tsumSec = append(sumSec, totalSec)\n\tsumMin = append(sumMin, totalMinutes)\n\tsumHour = append(sumHour, totalHour)\n\ttotalPodsRunning = totalPodsRunning + 1\n\tfmt.Printf(\"TOTAL NUMBER OF PODS RUNNING: %v\\n\", totalPodsRunning)\n\tfmt.Printf(\"TIME NOW: %v\\n\", time.Now().Format(\"2006-01-02 3:4:5 PM\"))\n\n\ttotalHour = 0\n\ttotalMinutes = 0\n\ttotalSec = 0\n}", "func writePodInformation(pod corev1.Pod) string {\n\tvar buffer strings.Builder\n\tvar containers, readyContainers, restarts int\n\tfor _, conStatus := range pod.Status.ContainerStatuses {\n\t\tcontainers++\n\t\tif conStatus.Ready {\n\t\t\treadyContainers++\n\t\t}\n\n\t\trestarts += int(conStatus.RestartCount)\n\t}\n\n\tbuffer.WriteString(pod.GetName())\n\tbuffer.WriteString(\"\\t\")\n\tbuffer.WriteString(strconv.Itoa(readyContainers))\n\tbuffer.WriteString(\"/\")\n\tbuffer.WriteString(strconv.Itoa(containers))\n\tbuffer.WriteString(\"\\t\")\n\tbuffer.WriteString(string(pod.Status.Phase))\n\n\tif pod.Status.Phase == corev1.PodPending {\n\t\tfor _, condition := range pod.Status.Conditions {\n\t\t\t// Only check the PodScheduled condition.\n\t\t\tif condition.Type != corev1.PodScheduled {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// If the Pod is scheduled we can ignore this condition.\n\t\t\tif condition.Status == corev1.ConditionTrue {\n\t\t\t\tbuffer.WriteString(\"\\t-\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Printout the message, why the Pod is not scheduling.\n\t\t\tbuffer.WriteString(\"\\t\")\n\t\t\tif condition.Message != \"\" {\n\t\t\t\tbuffer.WriteString(condition.Message)\n\t\t\t} else {\n\t\t\t\tbuffer.WriteString(\"-\")\n\t\t\t}\n\t\t}\n\t} else {\n\t\tbuffer.WriteString(\"\\t-\")\n\t}\n\n\tbuffer.WriteString(\"\\t\")\n\tbuffer.WriteString(strconv.Itoa(restarts))\n\n\tif _, ok := pod.Labels[fdbv1beta2.FDBProcessGroupIDLabel]; ok {\n\t\tvar mainTag, sidecarTag string\n\t\tfor _, container := range pod.Spec.Containers {\n\t\t\tif container.Name == fdbv1beta2.MainContainerName {\n\t\t\t\tmainTag = strings.Split(container.Image, \":\")[1]\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif container.Name == fdbv1beta2.SidecarContainerName {\n\t\t\t\tsidecarTag = strings.Split(container.Image, \":\")[1]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tbuffer.WriteString(\"\\t\")\n\t\tbuffer.WriteString(mainTag)\n\t\tbuffer.WriteString(\"\\t\")\n\t\tbuffer.WriteString(sidecarTag)\n\t} else {\n\t\tbuffer.WriteString(\"\\t-\\t-\")\n\t}\n\n\tbuffer.WriteString(\"\\t\")\n\tendIdx := len(pod.Status.PodIPs) - 1\n\tfor idx, ip := range pod.Status.PodIPs {\n\t\tbuffer.WriteString(ip.IP)\n\t\tif endIdx > idx {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t}\n\n\tbuffer.WriteString(\"\\t\")\n\tbuffer.WriteString(pod.Spec.NodeName)\n\tbuffer.WriteString(\"\\t\")\n\tbuffer.WriteString(duration.HumanDuration(time.Since(pod.CreationTimestamp.Time)))\n\n\treturn buffer.String()\n}", "func genpod(namespace, name, image string) *corev1.Pod {\n\tvar userID int64 = 65534\n\n\treturn &corev1.Pod{\n\t\tMetadata: &metav1.ObjectMeta{\n\t\t\tName: k8s.String(name),\n\t\t\tNamespace: k8s.String(namespace),\n\t\t\tLabels: map[string]string{\"generator\": \"kboom\"},\n\t\t},\n\t\tSpec: &corev1.PodSpec{\n\t\t\tContainers: []*corev1.Container{\n\t\t\t\t&corev1.Container{\n\t\t\t\t\tName: k8s.String(\"main\"),\n\t\t\t\t\tImage: k8s.String(image),\n\t\t\t\t\tCommand: []string{\"/bin/sh\", \"-ec\", \"sleep 3600\"},\n\t\t\t\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\t\t\t\tRunAsUser: &userID,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (s *VarlinkInterface) PushImage(ctx context.Context, c VarlinkCall, name_ string, tag_ string, compress_ bool, format_ string, removeSignatures_ bool, signBy_ string) error {\n\treturn c.ReplyMethodNotImplemented(ctx, \"io.podman.PushImage\")\n}", "func pushTagImage(idx tagindex, from *os.File, token string) error {\n\t// XXX implement ssl please\n\tconn, err := grpc.Dial(idx.server, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)\n\tdefer cancel()\n\n\tclient := pb.NewTagIOServiceClient(conn)\n\tstream, err := client.Push(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// we first send over a communication to indicate we are\n\t// willing to send an image. That will bail out if the\n\t// provided info is wrong.\n\tireq := &pb.PushRequest{\n\t\tTestOneof: &pb.PushRequest_Request{\n\t\t\tRequest: &pb.Request{\n\t\t\t\tName: idx.name,\n\t\t\t\tNamespace: idx.namespace,\n\t\t\t\tToken: token,\n\t\t\t},\n\t\t},\n\t}\n\tif err := stream.Send(ireq); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = pb.SendFileClient(from, stream)\n\treturn err\n}", "func (r *Replication) tagImage(repo string, tag string) error {\n\t//example => localhost:5000/busybox\n\tnewRepo := r.registryURL + \"/\" + repo\n\terr := dockerClient.TagImage(repo+\":\"+tag, docker.TagImageOptions{\n\t\tRepo: newRepo,\n\t\tTag: tag,\n\t\tForce: true,\n\t})\n\tif err != nil {\n\t\tfmt.Printf(\"tag %s:%s, FAIL: %v\\n\", newRepo, tag, err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func formatPodImage(raw string) (result string) {\n\ts := strings.Split(raw, \":\")\n\tif len(s) == 3 {\n\t\tresult = s[2]\n\t}\n\treturn\n}", "func (c *Client) Push(ctx context.Context, image string) error {\n\t// Parse the image name and tag.\n\tnamed, err := reference.ParseNormalizedNamed(image)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing image name %q failed: %v\", image, err)\n\t}\n\t// Add the latest lag if they did not provide one.\n\tnamed = reference.TagNameOnly(named)\n\timage = named.String()\n\n\t// Create the worker opts.\n\topt, err := c.createWorkerOpt()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating worker opt failed: %v\", err)\n\t}\n\n\t// Create the image writer.\n\tiw, err := containerimage.NewImageWriter(containerimage.WriterOpt{\n\t\tSnapshotter: opt.Snapshotter,\n\t\tContentStore: opt.ContentStore,\n\t\tDiffer: opt.Differ,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating new container image writer failed: %v\", err)\n\t}\n\n\t// Create the image pusher.\n\timagePusher, err := imagepush.New(imagepush.Opt{\n\t\tImages: opt.ImageStore,\n\t\tImageWriter: iw,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating new image pusher failed: %v\", err)\n\t}\n\n\t// Resolve (ie. push) the image.\n\tip, err := imagePusher.Resolve(ctx, map[string]string{\n\t\t\"name\": image,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"resolving image %s failed: %v\", image, err)\n\t}\n\n\t// Snapshot the image.\n\tif _, err := ip.Export(ctx, nil, nil); err != nil {\n\t\treturn fmt.Errorf(\"exporting the image %s failed: %v\", image, err)\n\t}\n\n\treturn nil\n}", "func createPod(clientset kubernetes.Interface, namespace string, image string, name string,\n\tlabels map[string]string, command []string, args []string) (*v1.Pod, error) {\n\tenv := []v1.EnvVar{\n\t\t{\n\t\t\tName: \"NAMESPACE\",\n\t\t\tValueFrom: &v1.EnvVarSource{\n\t\t\t\tFieldRef: &v1.ObjectFieldSelector{\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\tFieldPath: \"metadata.namespace\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tspec := v1.PodSpec{\n\t\tContainers: []v1.Container{\n\t\t\t{\n\t\t\t\tEnv: env,\n\t\t\t\tName: fmt.Sprintf(\"%v-pod-container\", name),\n\t\t\t\tImage: image,\n\t\t\t},\n\t\t},\n\t}\n\n\tif len(command) > 0 {\n\t\tspec.Containers[0].Command = command\n\t\tif len(args) > 0 {\n\t\t\tspec.Containers[0].Args = args\n\t\t}\n\t}\n\n\tpod := &v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tLabels: labels,\n\t\t\tName: name,\n\t\t},\n\t\tSpec: spec,\n\t}\n\n\tif _, err := clientset.CoreV1().Pods(namespace).Create(pod); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn clientset.CoreV1().Pods(namespace).Get(name, metav1.GetOptions{})\n}", "func setTag(ctx context.Context, kubeClient kube.CLIClient, tagName, revision, istioNS string, generate bool, w, stderr io.Writer) error {\n\topts := &GenerateOptions{\n\t\tTag: tagName,\n\t\tRevision: revision,\n\t\tWebhookName: webhookName,\n\t\tManifestsPath: manifestsPath,\n\t\tGenerate: generate,\n\t\tOverwrite: overwrite,\n\t\tAutoInjectNamespaces: autoInjectNamespaces,\n\t}\n\ttagWhYAML, err := Generate(ctx, kubeClient, opts, istioNS)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Check the newly generated webhook does not conflict with existing ones.\n\tresName := webhookName\n\tif resName == \"\" {\n\t\tresName = fmt.Sprintf(\"%s-%s\", \"istio-revision-tag\", tagName)\n\t}\n\tif err := analyzeWebhook(resName, istioNS, tagWhYAML, revision, kubeClient.RESTConfig()); err != nil {\n\t\t// if we have a conflict, we will fail. If --skip-confirmation is set, we will continue with a\n\t\t// warning; when actually applying we will also confirm to ensure the user does not see the\n\t\t// warning *after* it has applied\n\t\tif !skipConfirmation {\n\t\t\t_, _ = stderr.Write([]byte(err.Error()))\n\t\t\tif !generate {\n\t\t\t\tif !util.Confirm(\"Apply anyways? [y/N]\", w) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif generate {\n\t\t_, err := w.Write([]byte(tagWhYAML))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := Create(kubeClient, tagWhYAML, istioNS); err != nil {\n\t\treturn fmt.Errorf(\"failed to apply tag webhook MutatingWebhookConfiguration to cluster: %v\", err)\n\t}\n\tfmt.Fprintf(w, tagCreatedStr, tagName, revision, tagName)\n\treturn nil\n}", "func writeDataInPod(app *v1.Pod, f *framework.Framework) error {\n\tapp.Labels = map[string]string{\"app\": \"write-data-in-pod\"}\n\tapp.Namespace = f.UniqueName\n\n\terr := createApp(f.ClientSet, app, deployTimeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\topt := metav1.ListOptions{\n\t\tLabelSelector: \"app=write-data-in-pod\",\n\t}\n\t// write data to PVC. The idea here is to fill some content in the file\n\t// instead of filling and reverifying the md5sum/data integrity\n\tfilePath := app.Spec.Containers[0].VolumeMounts[0].MountPath + \"/test\"\n\t// While writing more data we are encountering issues in E2E timeout, so keeping it low for now\n\t_, writeErr := execCommandInPod(f, fmt.Sprintf(\"dd if=/dev/zero of=%s bs=1M count=10 status=none\", filePath), app.Namespace, &opt)\n\tExpect(writeErr).Should(BeEmpty())\n\treturn nil\n}", "func setImage(dep *appsv1.Deployment, ctn string, image string) {\n\tfor index, value := range dep.Spec.Template.Spec.Containers {\n\t\tif value.Name == ctn {\n\t\t\tnewImage := \"\"\n\t\t\toriImage := dep.Spec.Template.Spec.Containers[index].Image\n\t\t\timageStrutct := strings.Split(oriImage, \":\")\n\t\t\tif len(imageStrutct) != 0 {\n\t\t\t\tnewImage = fmt.Sprintf(\"%s:%s\", image, imageStrutct[len(imageStrutct)-1])\n\t\t\t\tdep.Spec.Template.Spec.Containers[index].Image = newImage\n\t\t\t}\n\t\t}\n\t}\n}", "func createPatch(pod *corev1.Pod, inj *config.InjectionConfig, annotations map[string]string) ([]byte, error) {\n\tvar patch []patchOperation\n\n\t// make sure any injected containers in our config get the EnvVars and VolumeMounts injected\n\t// this mutates inj.Containers with our environment vars\n\tmutatedInjectedContainers := mergeEnvVars(inj.Environment, inj.Containers)\n\tmutatedInjectedContainers = mergeVolumeMounts(inj.VolumeMounts, mutatedInjectedContainers)\n\n\t// make sure any injected init containers in our config get the EnvVars and VolumeMounts injected\n\t// this mutates inj.InitContainers with our environment vars\n\tmutatedInjectedInitContainers := mergeEnvVars(inj.Environment, inj.InitContainers)\n\tmutatedInjectedInitContainers = mergeVolumeMounts(inj.VolumeMounts, mutatedInjectedInitContainers)\n\n\t// patch all existing containers with the env vars and volume mounts\n\tpatch = append(patch, setVolumeMounts(pod.Spec.Containers, inj.VolumeMounts, \"/spec/containers\")...)\n\t// TODO: fix set env\n\t// setEnvironment may not work, because we replace the whole container in `setVolumeMounts`\n\tpatch = append(patch, setEnvironment(pod.Spec.Containers, inj.Environment)...)\n\n\t// patch containers with our injected containers\n\tpatch = append(patch, addContainers(pod.Spec.Containers, mutatedInjectedContainers, \"/spec/containers\")...)\n\n\t// add initContainers, hostAliases and volumes\n\tpatch = append(patch, addContainers(pod.Spec.InitContainers, mutatedInjectedInitContainers, \"/spec/initContainers\")...)\n\tpatch = append(patch, addHostAliases(pod.Spec.HostAliases, inj.HostAliases, \"/spec/hostAliases\")...)\n\tpatch = append(patch, addVolumes(pod.Spec.Volumes, inj.Volumes, \"/spec/volumes\")...)\n\n\t// set annotations\n\tpatch = append(patch, updateAnnotations(pod.Annotations, annotations)...)\n\n\t// set shareProcessNamespace\n\tpatch = append(patch, updateShareProcessNamespace(inj.ShareProcessNamespace)...)\n\n\t// TODO: remove injecting commands when sidecar container supported\n\t// set commands and args\n\tpatch = append(patch, setCommands(pod.Spec.Containers, inj.PostStart)...)\n\n\treturn json.Marshal(patch)\n}", "func (i *LibpodAPI) TagImage(call ioprojectatomicpodman.VarlinkCall, name, tag string) error {\n\truntime, err := libpodruntime.GetRuntime(i.Cli)\n\tif err != nil {\n\t\treturn call.ReplyRuntimeError(err.Error())\n\t}\n\tnewImage, err := runtime.ImageRuntime().NewFromLocal(name)\n\tif err != nil {\n\t\treturn call.ReplyImageNotFound(name)\n\t}\n\tif err := newImage.TagImage(tag); err != nil {\n\t\treturn call.ReplyErrorOccurred(err.Error())\n\t}\n\treturn call.ReplyTagImage(newImage.ID())\n}", "func podInfo(pod v1.Pod) (result string) {\n\tpodname := pod.Name\n\tpodstatus := strings.ToLower(string(pod.Status.Phase))\n\timages := \"\"\n\tfor _, container := range pod.Spec.Containers {\n\t\timages += fmt.Sprintf(\"%v \", container.Image)\n\t}\n\tresult += fmt.Sprintf(\"pod [%v] is %v and uses image(s) %v\\n\", podname, podstatus, images)\n\treturn result\n}", "func newPod(ctx context.Context, cl client.Client, ns, name, image string, cmd []string) (*corev1.Pod, error) {\n\tc := corev1.Container{\n\t\tName: name,\n\t\tImage: image,\n\t\tCommand: cmd,\n\t}\n\tp := &corev1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: ns,\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tContainers: []corev1.Container{c},\n\t\t\t// Kill the pod immediately so it exits quickly on deletion.\n\t\t\tTerminationGracePeriodSeconds: pointer.Int64Ptr(0),\n\t\t},\n\t}\n\tif err := cl.Create(ctx, p); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create pod %s/%s: %v\", p.Namespace, p.Name, err)\n\t}\n\treturn p, nil\n}", "func (d *Driver) writeDiskImage() error { // TODO\n\tlog.Debugf(\"Creating hard disk image...\")\n\n\tmagicString := \"boot2docker, this is xhyve speaking\"\n\n\tbuf := new(bytes.Buffer)\n\ttw := tar.NewWriter(buf)\n\n\t// magicString first so the automount script knows to format the disk\n\tfile := &tar.Header{Name: magicString, Size: int64(len(magicString))}\n\tif err := tw.WriteHeader(file); err != nil {\n\t\treturn err\n\t}\n\tif _, err := tw.Write([]byte(magicString)); err != nil {\n\t\treturn err\n\t}\n\t// .ssh/key.pub => authorized_keys\n\tfile = &tar.Header{Name: \".ssh\", Typeflag: tar.TypeDir, Mode: 0700}\n\tif err := tw.WriteHeader(file); err != nil {\n\t\treturn err\n\t}\n\tpubKey, err := ioutil.ReadFile(d.publicSSHKeyPath())\n\tif err != nil {\n\t\treturn err\n\t}\n\tfile = &tar.Header{Name: \".ssh/authorized_keys\", Size: int64(len(pubKey)), Mode: 0644}\n\tif err := tw.WriteHeader(file); err != nil {\n\t\treturn err\n\t}\n\tif _, err := tw.Write([]byte(pubKey)); err != nil {\n\t\treturn err\n\t}\n\tfile = &tar.Header{Name: \".ssh/authorized_keys2\", Size: int64(len(pubKey)), Mode: 0644}\n\tif err := tw.WriteHeader(file); err != nil {\n\t\treturn err\n\t}\n\tif _, err := tw.Write([]byte(pubKey)); err != nil {\n\t\treturn err\n\t}\n\tif err := tw.Close(); err != nil {\n\t\treturn err\n\t}\n\traw := buf.Bytes()\n\n\tif err := ioutil.WriteFile(d.imgPath(), raw, 0644); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Build(k kubectl.CLI, pod string, d docker.CLI, options *Options, image string, context string, out *output.Interface) error {\n\treturn pkgerror(out.Do(\"Building image\", func(op output.Operation) error {\n\t\top.Progress(\"determining build node\")\n\t\tvar node string\n\t\tfor {\n\t\t\tvar err error\n\t\t\tnode, err = k.String(\"get\", \"pod\", pod, \"--output\", `go-template={{.spec.nodeName}}`)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t} else if node != \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t}\n\n\t\top.Progress(\"determining build pod\")\n\t\tnodePods, err := server.NodePods(k, out)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif nodePods[node] == \"\" {\n\t\t\treturn fmt.Errorf(\"cannot build on node %s\", node)\n\t\t}\n\n\t\top.Progress(\"connecting to docker daemon\")\n\t\tdockerPort, stop, err := portforward.StartOne(k, \"kube-system\", nodePods[node], \"2375\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer stop()\n\n\t\tbuildArgs := []string{\"--host\", \"localhost:\" + dockerPort, \"build\"}\n\t\tif options.File != \"\" {\n\t\t\tbuildArgs = append(buildArgs, \"--file\", options.File)\n\t\t}\n\t\tfor _, arg := range options.Args {\n\t\t\tbuildArgs = append(buildArgs, \"--build-arg\", arg)\n\t\t}\n\t\tif options.Target != \"\" {\n\t\t\tbuildArgs = append(buildArgs, \"--target\", options.Target)\n\t\t}\n\t\tbuildArgs = append(buildArgs, \"--tag\", image, context)\n\n\t\top.Progress(\"running\")\n\t\treturn d.EachLine(buildArgs, func(line string) {\n\t\t\tif out.Level < output.LevelVerbose && (strings.HasPrefix(line, \"Sending build context \") || strings.HasPrefix(line, \"Step \")) {\n\t\t\t\top.Progress(\"s\" + line[1:])\n\t\t\t} else {\n\t\t\t\tout.Verbose(\"[docker] %s\", line)\n\t\t\t}\n\t\t})\n\t}))\n}", "func (dc *DockerClient) Push(image string) error {\n\tlogrus.WithField(\"image\", image).Debugln(\"Pushing image\")\n\tvar c *client.Client\n\tvar err error\n\tif c, err = dc.Client(); err != nil {\n\t\tlogrus.WithError(err).Fatalln(\"Error occured while connecting to docker daemon\")\n\t\treturn err\n\t}\n\n\tvar a string\n\tvar n reference.Named\n\tif n, err = reference.ParseNamed(image); err != nil {\n\t\treturn err\n\t}\n\n\tif a, err = dc.Authenticate(n.Hostname()); err != nil {\n\t\treturn err\n\t}\n\tvar resp io.ReadCloser\n\tresp, err = c.ImagePush(context.Background(), image, types.ImagePushOptions{RegistryAuth: a})\n\n\tif resp != nil {\n\t\tdefer resp.Close()\n\t\tfmt.Print(\"Pushing image...\")\n\t\tdec := json.NewDecoder(resp)\n\t\tfor dec.More() {\n\t\t\tdec.Decode(struct{}{})\n\t\t\tfmt.Print(\".\")\n\t\t}\n\t\tfmt.Println(\".\")\n\t}\n\n\treturn err\n}", "func createDaemonSetPatch(daemonSet *appsv1.DaemonSet, labels map[string]string, annotations map[string]string) ([]byte, error) {\n\tvar patch []k8s.PatchOperation\n\tpatch = append(patch, k8s.GenerateSpecTemplateAnnotationPatch(daemonSet.Spec.Template.Annotations, annotations)...)\n\tpatch = append(patch, k8s.GenerateMetadataLabelsPatch(daemonSet.Labels, labels)...)\n\treturn json.Marshal(patch)\n}", "func TagPodsIfPresent(unstruct *unstructured.Unstructured, tag string) {\n\n\tspec, ok := unstruct.Object[\"spec\"].(map[string]interface{})\n\tif !ok {\n\t\tlog.Println(\"Error converting spec to map\")\n\t\treturn\n\t}\n\n\ttemplate, ok := spec[\"template\"].(map[string]interface{})\n\tif !ok {\n\t\t//log.Println(\"Error converting template to map\")\n\t\treturn\n\t}\n\tlog.Println(\"Apply label in template\")\n\t//Attempt to convert the template to a podtemplatespec.\n\t//This is to check if we have any pods being created.\n\tpodTemplateSpec := &corev1.PodTemplateSpec{}\n\terr := runtime.DefaultUnstructuredConverter.FromUnstructured(template, podTemplateSpec)\n\tif err != nil {\n\t\tlog.Println(\"Did not find a podTemplateSpec: \" + err.Error())\n\t\treturn\n\t}\n\n\tlabels := podTemplateSpec.GetLabels()\n\tif labels == nil {\n\t\tlabels = map[string]string{}\n\t}\n\tlabels[\"emco/deployment-id\"] = tag\n\tpodTemplateSpec.SetLabels(labels)\n\n\tupdatedTemplate, err := runtime.DefaultUnstructuredConverter.ToUnstructured(podTemplateSpec)\n\n\t//Set the label\n\tspec[\"template\"] = updatedTemplate\n}", "func (is *ObjectStorage) PutImageManifest(repo, reference, mediaType string, //nolint: gocyclo\n\tbody []byte,\n) (godigest.Digest, godigest.Digest, error) {\n\tif err := is.InitRepo(repo); err != nil {\n\t\tis.log.Debug().Err(err).Msg(\"init repo\")\n\n\t\treturn \"\", \"\", err\n\t}\n\n\tvar lockLatency time.Time\n\n\tvar err error\n\n\tis.Lock(&lockLatency)\n\tdefer func() {\n\t\tis.Unlock(&lockLatency)\n\n\t\tif err == nil {\n\t\t\tmonitoring.SetStorageUsage(is.metrics, is.rootDir, repo)\n\t\t\tmonitoring.IncUploadCounter(is.metrics, repo)\n\t\t}\n\t}()\n\n\trefIsDigest := true\n\n\tmDigest, err := common.GetAndValidateRequestDigest(body, reference, is.log)\n\tif err != nil {\n\t\tif errors.Is(err, zerr.ErrBadManifest) {\n\t\t\treturn mDigest, \"\", err\n\t\t}\n\n\t\trefIsDigest = false\n\t}\n\n\tdig, err := common.ValidateManifest(is, repo, reference, mediaType, body, is.log)\n\tif err != nil {\n\t\treturn dig, \"\", err\n\t}\n\n\tindex, err := common.GetIndex(is, repo, is.log)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\t// create a new descriptor\n\tdesc := ispec.Descriptor{\n\t\tMediaType: mediaType, Size: int64(len(body)), Digest: mDigest,\n\t}\n\n\tif !refIsDigest {\n\t\tdesc.Annotations = map[string]string{ispec.AnnotationRefName: reference}\n\t}\n\n\tvar subjectDigest godigest.Digest\n\n\tartifactType := \"\"\n\n\tif mediaType == ispec.MediaTypeImageManifest {\n\t\tvar manifest ispec.Manifest\n\n\t\terr := json.Unmarshal(body, &manifest)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\n\t\tif manifest.Subject != nil {\n\t\t\tsubjectDigest = manifest.Subject.Digest\n\t\t}\n\n\t\tartifactType = zcommon.GetManifestArtifactType(manifest)\n\t} else if mediaType == ispec.MediaTypeImageIndex {\n\t\tvar index ispec.Index\n\n\t\terr := json.Unmarshal(body, &index)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\n\t\tif index.Subject != nil {\n\t\t\tsubjectDigest = index.Subject.Digest\n\t\t}\n\n\t\tartifactType = zcommon.GetIndexArtifactType(index)\n\t}\n\n\tupdateIndex, oldDgst, err := common.CheckIfIndexNeedsUpdate(&index, &desc, is.log)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tif !updateIndex {\n\t\treturn desc.Digest, subjectDigest, nil\n\t}\n\n\t// write manifest to \"blobs\"\n\tdir := path.Join(is.rootDir, repo, \"blobs\", mDigest.Algorithm().String())\n\tmanifestPath := path.Join(dir, mDigest.Encoded())\n\n\tif err = is.store.PutContent(context.Background(), manifestPath, body); err != nil {\n\t\tis.log.Error().Err(err).Str(\"file\", manifestPath).Msg(\"unable to write\")\n\n\t\treturn \"\", \"\", err\n\t}\n\n\terr = common.UpdateIndexWithPrunedImageManifests(is, &index, repo, desc, oldDgst, is.log)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\t// now update \"index.json\"\n\tindex.Manifests = append(index.Manifests, desc)\n\tdir = path.Join(is.rootDir, repo)\n\tindexPath := path.Join(dir, \"index.json\")\n\n\tbuf, err := json.Marshal(index)\n\tif err != nil {\n\t\tis.log.Error().Err(err).Str(\"file\", indexPath).Msg(\"unable to marshal JSON\")\n\n\t\treturn \"\", \"\", err\n\t}\n\n\t// update the descriptors artifact type in order to check for signatures when applying the linter\n\tdesc.ArtifactType = artifactType\n\n\t// apply linter only on images, not signatures\n\tpass, err := common.ApplyLinter(is, is.linter, repo, desc)\n\tif !pass {\n\t\tis.log.Error().Err(err).Str(\"repository\", repo).Str(\"reference\", reference).Msg(\"linter didn't pass\")\n\n\t\treturn \"\", \"\", err\n\t}\n\n\tif err = is.store.PutContent(context.Background(), indexPath, buf); err != nil {\n\t\tis.log.Error().Err(err).Str(\"file\", manifestPath).Msg(\"unable to write\")\n\n\t\treturn \"\", \"\", err\n\t}\n\n\treturn desc.Digest, subjectDigest, nil\n}", "func main() {\n\n\tc := new(bluemix.Config)\n\n\tvar imageTag string\n\t// should same form of registry.ng.bluemix.net/<namespace>/<imagename>\n\tflag.StringVar(&imageTag, \"t\", \"registry.ng.bluemix.net/ibmcloud-go/build\", \"tag\")\n\n\tvar dockerFile string\n\tflag.StringVar(&dockerFile, \"f\", \"Dockerfile\", \"Dockerfile\")\n\n\tvar region string\n\tflag.StringVar(&region, \"region\", \"us-south\", \"region\")\n\n\tflag.Parse()\n\n\tc.Region = region\n\tdirectory := flag.Args()\n\n\tfmt.Println(directory)\n\ttrace.Logger = trace.NewLogger(\"true\")\n\tif len(directory) < 1 || directory[0] == \"\" {\n\n\t\tflag.Usage()\n\t\tfmt.Println(\"Example: ./build -f Dockerfile -t registry.ng.bluemix.net/ibmcloud-go/imagtest .\")\n\t\tos.Exit(1)\n\t}\n\n\tsession, _ := session.New(c)\n\n\tiamAPI, err := iamv1.New(session)\n\tidentityAPI := iamAPI.Identity()\n\tuserInfo, err := identityAPI.UserInfo()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tregistryClient, err := registryv1.New(session)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tnamespaceHeaderStruct := registryv1.NamespaceTargetHeader{\n\t\tAccountID: userInfo.Account.Bss,\n\t}\n\n\tnamespace := strings.Split(imageTag, \"/\")\n\tif len(namespace) != 3 {\n\t\tlog.Fatal(\"Image Tag not correct format\")\n\t}\n\n\tnamespaces, err := registryClient.Namespaces().GetNamespaces(namespaceHeaderStruct)\n\tfound := false\n\tfor _, a := range namespaces {\n\t\tif a == namespace[1] {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\t_, err := registryClient.Namespaces().AddNamespace(namespace[1], namespaceHeaderStruct)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t}\n\n\theaderStruct := registryv1.BuildTargetHeader{\n\t\tAccountID: userInfo.Account.Bss,\n\t}\n\n\trequestStruct := registryv1.DefaultImageBuildRequest()\n\trequestStruct.T = imageTag\n\trequestStruct.Dockerfile = dockerFile\n\n\ttarName, err := tarGzContext(directory[0])\n\tif err != nil {\n\n\t}\n\ttarFile, err := os.Open(tarName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttarReader := bufio.NewReader(tarFile)\n\t//Too much binary output\n\ttrace.Logger = trace.NewLogger(\"false\")\n\n\tfmt.Println(\"Building...\")\n\terr = registryClient.Builds().ImageBuild(*requestStruct, tarReader, headerStruct, os.Stdout)\n\n\timageHeaderStruct := registryv1.ImageTargetHeader{\n\t\tAccountID: userInfo.Account.Bss,\n\t}\n\n\tfmt.Println(\"\\nInspecting Built Image...\")\n\timage, err := registryClient.Images().InspectImage(imageTag, imageHeaderStruct)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tjsonBytes, err := json.MarshalIndent(image, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(string(jsonBytes))\n\n\tfmt.Println(\"\\nScanning Built Image...\")\n\timageVulnerabiliyRequst := registryv1.DefaultImageVulnerabilitiesRequest()\n\timageReport, err := registryClient.Images().ImageVulnerabilities(imageTag, *imageVulnerabiliyRequst, imageHeaderStruct)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tjsonBytes, err = json.MarshalIndent(imageReport, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(string(jsonBytes))\n}", "func saveTagImage(tidx tagindex) (*os.File, func(), error) {\n\tfsh := fs.New(\"\")\n\tfp, cleanup, err := fsh.TempFile()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tstr := fmt.Sprintf(\"docker-archive:%s\", fp.Name())\n\tdstref, err := alltransports.ParseImageName(str)\n\tif err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, err\n\t}\n\n\tsrcref, err := tidx.localref()\n\tif err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, err\n\t}\n\n\tpol := &signature.Policy{\n\t\tDefault: signature.PolicyRequirements{\n\t\t\tsignature.NewPRInsecureAcceptAnything(),\n\t\t},\n\t}\n\tpctx, err := signature.NewPolicyContext(pol)\n\tif err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, err\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\tdefer cancel()\n\n\tif _, err := imgcopy.Image(\n\t\tctx, pctx, dstref, srcref, &imgcopy.Options{},\n\t); err != nil {\n\t\tcleanup()\n\t\treturn nil, nil, err\n\t}\n\n\treturn fp, cleanup, err\n}", "func (c *ClusterController) addSimulatorToPod(name string, pod corev1.Pod) error {\n\tcommand := fmt.Sprintf(\"onos devices add \\\"id: '%s', address: '%s:10161' version: '1.0.0' devicetype: 'Devicesim'\\\" --address 127.0.0.1:5150 --keyPath /etc/onos-config/certs/client1.key --certPath /etc/onos-config/certs/client1.crt\", name, name)\n\treturn c.execute(pod, []string{\"/bin/bash\", \"-c\", command})\n}", "func AddTagsToPodSelector(runnerBuilds []graph.Artifact, deployerArtifacts []graph.Artifact, podSelector *kubernetes.ImageList) {\n\t// This implementation is mostly picked from v1 for fixing log duplication issue when multiple deployers are used.\n\t// According to the original author \"Each Deployer will be directly responsible for adding its deployed artifacts to the PodSelector\n\t// by cross-referencing them against the list of images parsed out of the set of manifests they each deploy\". Each deploy should only\n\t// add its own deployed artifacts to the PodSelector to avoid duplicate logging when multi-deployers are used.\n\t// This implementation only streams logs for the intersection of runnerBuilds and deployerArtifacts images, not all images from a deployer\n\t// probably because at that time the team didn't want to stream logs from images not built by Skaffold, e.g. images from docker hub, but this\n\t// may change. The initial implementation was using imageName as map key for getting shared elements, this was ok as deployerArtifacts were\n\t// parsed out from skaffold config files in v1 and tag was not available if not specified. Now deployers don't own render responsibilities\n\t// anymore, instead callers pass rendered manifests to deployers, we can only parse artifacts from these rendered manifests. The imageName\n\t// from deployerArtifacts here has the default-repo value as prefix while the one from runnerBuilds doesn't. This discrepancy causes artifact.Tag\n\t// fail to add into podSelector, which leads to podWatchers fail to get events from pods. As tags are available in deployerArtifacts now, so using\n\t// tag as map key to get the shared elements.\n\tm := map[string]bool{}\n\tfor _, a := range deployerArtifacts {\n\t\tm[a.Tag] = true\n\t}\n\tfor _, artifact := range runnerBuilds {\n\t\tif _, ok := m[artifact.Tag]; ok {\n\t\t\tpodSelector.Add(artifact.Tag)\n\t\t}\n\t}\n}", "func Encode(w io.Writer, m image.Image) error {}", "func Encode(w io.Writer, m image.Image, o *Options) error", "func Encode(w io.Writer, m image.Image, o *Options) error", "func (i *LibpodAPI) ExportImage(call ioprojectatomicpodman.VarlinkCall, name, destination string, compress bool) error {\n\truntime, err := libpodruntime.GetRuntime(i.Cli)\n\tif err != nil {\n\t\treturn call.ReplyRuntimeError(err.Error())\n\t}\n\tnewImage, err := runtime.ImageRuntime().NewFromLocal(name)\n\tif err != nil {\n\t\treturn call.ReplyImageNotFound(name)\n\t}\n\tif err := newImage.PushImage(getContext(), destination, \"\", \"\", \"\", nil, compress, image.SigningOptions{}, &image.DockerRegistryOptions{}, false); err != nil {\n\t\treturn call.ReplyErrorOccurred(err.Error())\n\t}\n\treturn call.ReplyExportImage(newImage.ID())\n}", "func createDaemonSetObject(cr *hostpathprovisionerv1alpha1.HostPathProvisioner, provisionerImage, namespace string) *appsv1.DaemonSet {\n\tvolumeType := corev1.HostPathDirectoryOrCreate\n\tlabels := map[string]string{\n\t\t\"k8s-app\": cr.Name,\n\t}\n\treturn &appsv1.DaemonSet{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t\tKind: \"DaemonSet\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: appsv1.DaemonSetSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\"k8s-app\": cr.Name,\n\t\t\t\t},\n\t\t\t},\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tServiceAccountName: cr.Name + \"-admin\",\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: cr.Name,\n\t\t\t\t\t\t\tImage: provisionerImage,\n\t\t\t\t\t\t\tImagePullPolicy: cr.Spec.ImagePullPolicy,\n\t\t\t\t\t\t\tEnv: []corev1.EnvVar{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"USE_NAMING_PREFIX\",\n\t\t\t\t\t\t\t\t\tValue: cr.Spec.PathConfig.UseNamingPrefix,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"NODE_NAME\",\n\t\t\t\t\t\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\t\t\t\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\t\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\t\t\t\t\t\t\tFieldPath: \"spec.nodeName\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"PV_DIR\",\n\t\t\t\t\t\t\t\t\tValue: cr.Spec.PathConfig.Path,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"pv-volume\",\n\t\t\t\t\t\t\t\t\tMountPath: cr.Spec.PathConfig.Path,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tTerminationMessagePath: \"/dev/termination-log\",\n\t\t\t\t\t\t\tTerminationMessagePolicy: corev1.TerminationMessageReadFile,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tVolumes: []corev1.Volume{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"pv-volume\", // Has to match VolumeMounts in containers\n\t\t\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\t\t\tHostPath: &corev1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\t\tPath: cr.Spec.PathConfig.Path,\n\t\t\t\t\t\t\t\t\tType: &volumeType,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func uploadManifest(registry, name, tag, layerDigest string) error {\n\tfmt.Printf(\"Upload manifest to %s (%s:%s): %s\\n\", registry, name, tag, layerDigest)\n\n\tmanifest, err := buildManifest(name, tag, layerDigest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmanifestURL := fmt.Sprintf(\"%s/v2/%s/manifests/%s\", registry, name, tag)\n\treq, err := http.NewRequest(http.MethodPut, manifestURL, manifest)\n\treq.Header.Set(\"Content-Type\", \"application/vnd.docker.distribution.manifest.v1+json\")\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Got response: %s\\n\", resp.Status)\n\tfor k, v := range resp.Header {\n\t\tfmt.Printf(\"%s: %s\\n\", k, v)\n\t}\n\tfmt.Printf(\"\\n\")\n\tio.Copy(os.Stdout, resp.Body)\n\tfmt.Printf(\"\\n\")\n\n\tif resp.StatusCode < 200 || resp.StatusCode > 299 {\n\t\treturn fmt.Errorf(\"Registry error: %s\", resp.Status)\n\t}\n\treturn nil\n}", "func pushImage(w http.ResponseWriter, r *http.Request) {\r\n\tvar ci CRImage\r\n\tif err := json.NewDecoder(r.Body).Decode(&ci); err != nil {\r\n\t\tlogger.Warnf(\"error decoding image: %s\", err)\r\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\r\n\t\treturn\r\n\t}\r\n\tif err := ci.dockerPush(); err != nil {\r\n\t\tlogger.Warnf(\"error pushing image: %s\", err)\r\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\r\n\t\treturn\r\n\t}\r\n\tif err := ci.UpdateStatus(1); err != nil {\r\n\t\tlogger.Warnf(\"error updating image status: %s\", err)\r\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\r\n\t\treturn\r\n\t}\r\n\tw.Header().Set(\"content-type\", \"application/json\")\r\n\tw.WriteHeader(http.StatusCreated)\r\n}", "func (cli *DockerClient) ImagePush(ctx context.Context, registry, repo, tag string) error {\n\tv := url.Values{}\n\timage := repo\n\tif registry != \"\" {\n\t\timage = fmt.Sprintf(\"%s/%s\", registry, repo)\n\t}\n\tv.Set(\"tag\", tag)\n\n\theaders := map[string][]string{\n\t\t\"X-Registry-Auth\": {base64.URLEncoding.EncodeToString([]byte(\"{\\\"username\\\":\\\"\\\",\\\"password\\\":\\\"\\\", \\\"auth\\\":\\\"\\\",\\\"email\\\":\\\"\\\"}\"))},\n\t}\n\treturn cli.post(ctx, fmt.Sprintf(\"/images/%s/push\", image), v, nil, headers, true)\n}", "func (o *CreateDeploymentOptions) buildPodSpec() corev1.PodSpec {\n\tpodSpec := corev1.PodSpec{Containers: []corev1.Container{}}\n\tfor _, imageString := range o.Images {\n\t\t// Retain just the image name\n\t\timageSplit := strings.Split(imageString, \"/\")\n\t\tname := imageSplit[len(imageSplit)-1]\n\t\t// Remove any tag or hash\n\t\tif strings.Contains(name, \":\") {\n\t\t\tname = strings.Split(name, \":\")[0]\n\t\t}\n\t\tif strings.Contains(name, \"@\") {\n\t\t\tname = strings.Split(name, \"@\")[0]\n\t\t}\n\t\tname = sanitizeAndUniquify(name)\n\t\tpodSpec.Containers = append(podSpec.Containers, corev1.Container{\n\t\t\tName: name,\n\t\t\tImage: imageString,\n\t\t\tCommand: o.Command,\n\t\t})\n\t}\n\treturn podSpec\n}", "func Write(ref name.Reference, img v1.Image, w io.Writer, opts ...WriteOption) error {\n\treturn MultiRefWrite(map[name.Reference]v1.Image{ref: img}, w, opts...)\n}", "func (dc *DockerClient) Push(ref string) (io.ReadCloser, error) {\n\tregistryAuth := dc.cnf.GetRegistryAuth(\n\t\trepository.GetRegistry(ref),\n\t)\n\n\tpushOptions := types.ImagePushOptions{RegistryAuth: registryAuth}\n\tif registryAuth == \"\" {\n\t\tpushOptions = types.ImagePushOptions{RegistryAuth: \"IA==\"}\n\t}\n\n\treturn dc.cli.ImagePush(context.Background(), ref, pushOptions)\n}", "func newImageDestination(ctx context.Context, sys *types.SystemContext, ref daemonReference) (private.ImageDestination, error) {\n\tif ref.ref == nil {\n\t\treturn nil, fmt.Errorf(\"Invalid destination docker-daemon:%s: a destination must be a name:tag\", ref.StringWithinTransport())\n\t}\n\tnamedTaggedRef, ok := ref.ref.(reference.NamedTagged)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Invalid destination docker-daemon:%s: a destination must be a name:tag\", ref.StringWithinTransport())\n\t}\n\n\tvar mustMatchRuntimeOS = true\n\tif sys != nil && sys.DockerDaemonHost != client.DefaultDockerHost {\n\t\tmustMatchRuntimeOS = false\n\t}\n\n\tc, err := newDockerClient(sys)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"initializing docker engine client: %w\", err)\n\t}\n\n\treader, writer := io.Pipe()\n\tarchive := tarfile.NewWriter(writer)\n\t// Commit() may never be called, so we may never read from this channel; so, make this buffered to allow imageLoadGoroutine to write status and terminate even if we never read it.\n\tstatusChannel := make(chan error, 1)\n\n\tgoroutineContext, goroutineCancel := context.WithCancel(ctx)\n\tgo imageLoadGoroutine(goroutineContext, c, reader, statusChannel)\n\n\treturn &daemonImageDestination{\n\t\tref: ref,\n\t\tmustMatchRuntimeOS: mustMatchRuntimeOS,\n\t\tDestination: tarfile.NewDestination(sys, archive, ref.Transport().Name(), namedTaggedRef),\n\t\tarchive: archive,\n\t\tgoroutineCancel: goroutineCancel,\n\t\tstatusChannel: statusChannel,\n\t\twriter: writer,\n\t\tcommitted: false,\n\t}, nil\n}", "func PullImage(\n\tctx context.Context,\n\treq docker.PullImage,\n\tp events.Publisher[docker.Event],\n\twg *waitgroupx.Group,\n\tlog *logrus.Entry,\n\tgetPullCommand func(docker.PullImage, string) (string, []string),\n) (err error) {\n\tif err = p.Publish(ctx, docker.NewBeginStatsEvent(docker.ImagePullStatsKind)); err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err = p.Publish(ctx, docker.NewEndStatsEvent(docker.ImagePullStatsKind)); err != nil {\n\t\t\tlog.WithError(err).Warn(\"did not send image pull done stats\")\n\t\t}\n\t}()\n\n\timage := CanonicalizeImage(req.Name)\n\n\turi, err := url.Parse(image)\n\tif err != nil || uri.Scheme == \"\" {\n\t\tif err = p.Publish(ctx, docker.NewLogEvent(\n\t\t\tmodel.LogLevelInfo,\n\t\t\tfmt.Sprintf(\"image %s isn't a pullable URI; skipping pull\", image),\n\t\t)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t// TODO(DET-9078): Support registry auth. Investigate other auth mechanisms\n\t// with singularity & podman.\n\tcommand, args := getPullCommand(req, image)\n\n\tif err = PprintCommand(ctx, command, args, p, log); err != nil {\n\t\treturn err\n\t}\n\n\tcmd := exec.CommandContext(ctx, command, args...) // #nosec G204 'command' is under our control\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating stdout pipe: %w\", err)\n\t}\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating stderr pipe: %w\", err)\n\t}\n\n\t// The return codes from `podman pull` aren't super helpful in determining the error, so we\n\t// wrap the publisher and skim logs to see what happened as we ship them.\n\tignoreErrorsSig := make(chan bool)\n\tcheckIgnoreErrors := events.FuncPublisher[docker.Event](\n\t\tfunc(ctx context.Context, t docker.Event) error {\n\t\t\tif t.Log != nil && strings.Contains(t.Log.Message, \"Image file already exists\") {\n\t\t\t\tignoreErrorsSig <- true\n\t\t\t}\n\t\t\treturn p.Publish(ctx, t)\n\t\t},\n\t)\n\twg.Go(func(ctx context.Context) { ShipContainerCommandLogs(ctx, stdout, stdcopy.Stdout, p) })\n\twg.Go(func(ctx context.Context) {\n\t\tdefer close(ignoreErrorsSig)\n\t\tShipContainerCommandLogs(ctx, stderr, stdcopy.Stderr, checkIgnoreErrors)\n\t})\n\n\tif err = cmd.Start(); err != nil {\n\t\treturn fmt.Errorf(\"starting pull command: %w\", err)\n\t}\n\n\tvar ignoreErrors bool\n\tselect {\n\tcase ignoreErrors = <-ignoreErrorsSig:\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\n\tif err = cmd.Wait(); err != nil && !ignoreErrors {\n\t\treturn fmt.Errorf(\"pulling %s: %w\", image, err)\n\t}\n\treturn nil\n}", "func (s *publisherServer) Publish(ctx context.Context, request *api.Request) (*api.Response, error) {\n\timageName := calcImageName(request)\n\tresponse := &api.Response{ ImageName: imageName }\t\n\n\tapiNamespaces := s.Clientset.CoreV1().Namespaces()\n\n\tif _, err := apiNamespaces.Get(request.Namespace, kubemeta.GetOptions{}); err != nil {\n\t\treturn resp_error(response, fmt.Sprintf(\"Could not get namespace `%s`, got error '%s'\\n\", request.Namespace, err.Error())), nil\n\t}\n\n\tnewVersion := time.Now().Format(\"0601021504\") // stdYear stdZeroMonth stdZeroDay stdHour stdZeroMinute\n\tnvi,_ := strconv.Atoi(newVersion)\n\tnewVersion = strings.ToUpper( fmt.Sprintf(strconv.FormatInt(int64(nvi), 16)) )\n\n\tnewImageName := s.RegistryURL + \"/\" + imageName + \":\" + newVersion\n\n\tswitch request.Kind {\n\tcase api.ArtifactKind_CronJob:\n\t\t{\n\t\t\tbatchAPI := s.Clientset.BatchV1beta1()\n\t\t\tapiJobs := batchAPI.CronJobs(request.Namespace)\n\n\t\t\tjob, err := apiJobs.Get(request.Name, kubemeta.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn resp_error(response, fmt.Sprintf(\"Could not get job `%s`, got error '%s'\\n\", request.Name, err.Error())), nil\n\t\t\t}\n\t\t\tcontainers := job.Spec.JobTemplate.Spec.Template.Spec.Containers\n\t\t\tidx := searchContainerIdxByImageName(containers, imageName)\n\t\t\tif idx == -1 {\n\t\t\t\treturn resp_error(response, fmt.Sprintf(\"Could not get container with image `%s`\\n\", imageName)), nil\n\t\t\t}\n\n\t\t\tif err = PushImage(newImageName, request.DockerContent, s.Credentials); err != nil {\n\t\t\t\treturn resp_error(response, err.Error()), nil\n\t\t\t}\n\n\t\t\tjob.Spec.JobTemplate.Spec.Template.Spec.Containers[idx].Image = newImageName\n\t\t\tif _, err := apiJobs.Update(job); err != nil {\n\t\t\t\treturn resp_error(response, fmt.Sprintf(\"job update error `%v`\\n\", err)), nil\n\t\t\t}\n\t\t}\n\tcase api.ArtifactKind_Deployment:\n\t\t{\n\t\t\tappsAPI := s.Clientset.AppsV1()\n\t\t\tapiDeployments := appsAPI.Deployments(request.Namespace)\n\n\t\t\tdeployment, err := apiDeployments.Get(request.Name + \".\" + request.Tier, kubemeta.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn resp_error(response, fmt.Sprintf(\"Could not get deployment `%s`, got error '%s'\\n\", request.Name, err.Error())), nil\n\t\t\t}\n\t\t\tcontainers := deployment.Spec.Template.Spec.Containers\n\t\t\tidx := searchContainerIdxByImageName(containers, imageName)\n\t\t\tif idx == -1 {\n\t\t\t\treturn resp_error(response, fmt.Sprintf(\"Could not get container with image `%s`\\n\", imageName)), nil\n\t\t\t}\n\n\t\t\tif err = PushImage(newImageName, request.DockerContent, s.Credentials); err != nil {\n\t\t\t\treturn resp_error(response, err.Error()), nil\n\t\t\t}\n\n\t\t\tdeployment.Spec.Template.Spec.Containers[idx].Image = newImageName\n\t\t\tif _, err := apiDeployments.Update(deployment); err != nil {\n\t\t\t\treturn resp_error(response, fmt.Sprintf(\"deployment update error `%v`\\n\", err)), nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn resp_ok(response, \"0x\" + newVersion), nil\n}", "func (is *ImageStoreLocal) PutImageManifest(repo, reference, mediaType string, //nolint: gocyclo\n\tbody []byte,\n) (godigest.Digest, godigest.Digest, error) {\n\tif err := is.InitRepo(repo); err != nil {\n\t\tis.log.Debug().Err(err).Msg(\"init repo\")\n\n\t\treturn \"\", \"\", err\n\t}\n\n\tvar lockLatency time.Time\n\n\tvar err error\n\n\tis.Lock(&lockLatency)\n\tdefer func() {\n\t\tis.Unlock(&lockLatency)\n\n\t\tif err == nil {\n\t\t\tmonitoring.SetStorageUsage(is.metrics, is.rootDir, repo)\n\t\t\tmonitoring.IncUploadCounter(is.metrics, repo)\n\t\t}\n\t}()\n\n\trefIsDigest := true\n\n\tmDigest, err := common.GetAndValidateRequestDigest(body, reference, is.log)\n\tif err != nil {\n\t\tif errors.Is(err, zerr.ErrBadManifest) {\n\t\t\treturn mDigest, \"\", err\n\t\t}\n\n\t\trefIsDigest = false\n\t}\n\n\tdigest, err := common.ValidateManifest(is, repo, reference, mediaType, body, is.log)\n\tif err != nil {\n\t\treturn digest, \"\", err\n\t}\n\n\tindex, err := common.GetIndex(is, repo, is.log)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\t// create a new descriptor\n\tdesc := ispec.Descriptor{\n\t\tMediaType: mediaType, Size: int64(len(body)), Digest: mDigest,\n\t}\n\n\tif !refIsDigest {\n\t\tdesc.Annotations = map[string]string{ispec.AnnotationRefName: reference}\n\t}\n\n\tvar subjectDigest godigest.Digest\n\n\tartifactType := \"\"\n\n\tif mediaType == ispec.MediaTypeImageManifest {\n\t\tvar manifest ispec.Manifest\n\n\t\terr := json.Unmarshal(body, &manifest)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\n\t\tif manifest.Subject != nil {\n\t\t\tsubjectDigest = manifest.Subject.Digest\n\t\t}\n\n\t\tartifactType = zcommon.GetManifestArtifactType(manifest)\n\t} else if mediaType == ispec.MediaTypeImageIndex {\n\t\tvar index ispec.Index\n\n\t\terr := json.Unmarshal(body, &index)\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\n\t\tif index.Subject != nil {\n\t\t\tsubjectDigest = index.Subject.Digest\n\t\t}\n\n\t\tartifactType = zcommon.GetIndexArtifactType(index)\n\t}\n\n\tupdateIndex, oldDgst, err := common.CheckIfIndexNeedsUpdate(&index, &desc, is.log)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tif !updateIndex {\n\t\treturn desc.Digest, subjectDigest, nil\n\t}\n\n\t// write manifest to \"blobs\"\n\tdir := path.Join(is.rootDir, repo, \"blobs\", mDigest.Algorithm().String())\n\t_ = ensureDir(dir, is.log)\n\tfile := path.Join(dir, mDigest.Encoded())\n\n\t// in case the linter will not pass, it will be garbage collected\n\tif err := is.writeFile(file, body); err != nil {\n\t\tis.log.Error().Err(err).Str(\"file\", file).Msg(\"unable to write\")\n\n\t\treturn \"\", \"\", err\n\t}\n\n\terr = common.UpdateIndexWithPrunedImageManifests(is, &index, repo, desc, oldDgst, is.log)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\t// now update \"index.json\"\n\tindex.Manifests = append(index.Manifests, desc)\n\tdir = path.Join(is.rootDir, repo)\n\tfile = path.Join(dir, \"index.json\")\n\n\tbuf, err := json.Marshal(index)\n\tif err := inject.Error(err); err != nil {\n\t\tis.log.Error().Err(err).Str(\"file\", file).Msg(\"unable to marshal JSON\")\n\n\t\treturn \"\", \"\", err\n\t}\n\n\t// update the descriptors artifact type in order to check for signatures when applying the linter\n\tdesc.ArtifactType = artifactType\n\n\t// apply linter only on images, not signatures or indexes\n\tpass, err := common.ApplyLinter(is, is.linter, repo, desc)\n\tif !pass {\n\t\tis.log.Error().Err(err).Str(\"repository\", repo).Str(\"reference\", reference).Msg(\"linter didn't pass\")\n\n\t\treturn \"\", \"\", err\n\t}\n\n\terr = is.writeFile(file, buf)\n\tif err := inject.Error(err); err != nil {\n\t\tis.log.Error().Err(err).Str(\"file\", file).Msg(\"unable to write\")\n\n\t\treturn \"\", \"\", err\n\t}\n\n\treturn desc.Digest, subjectDigest, nil\n}", "func (cli Client) ImagePush(options v1alpha1.OCIPushOptions) (v1alpha1.OCIPushResponse, error) {\n\n\tpushFlags := []command.Flag{\n\t\t// Buildah registry auth in format username[:password]\n\t\t{Name: \"creds\", Value: options.RegistryAuth, Short: false, OmitEmpty: true},\n\t}\n\n\tcmd := command.Builder(\"buildah\").Command(\"push\").Flags(pushFlags...).Args(options.Ref).Build()\n\tcli.Logger.WithField(\"cmd\", cmd).Debugln(\"executing push with command\")\n\n\tstdout, stderr, err := execute(&cmd)\n\tif err != nil {\n\t\tcli.Logger.WithError(err).Errorln(\"error building image...\")\n\t\treturn v1alpha1.OCIPushResponse{}, err\n\t}\n\treturn v1alpha1.OCIPushResponse{\n\t\tBody: stdout,\n\t\tExec: &cmd,\n\t\tStderr: stderr,\n\t}, nil\n}", "func (dc *DockerClient) Tag(src, dst string) error {\n\treturn dc.cli.ImageTag(context.Background(), src, dst)\n}", "func (b *EtcdManagerBuilder) buildPod(etcdCluster kops.EtcdClusterSpec, instanceGroupName string) (*v1.Pod, error) {\n\tvar pod *v1.Pod\n\tvar container *v1.Container\n\n\tvar manifest []byte\n\n\t// TODO: pull from bundle\n\tbundle := \"(embedded etcd manifest)\"\n\tmanifest = []byte(defaultManifest)\n\n\t{\n\t\tobjects, err := model.ParseManifest(manifest)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(objects) != 1 {\n\t\t\treturn nil, fmt.Errorf(\"expected exactly one object in manifest %s, found %d\", bundle, len(objects))\n\t\t}\n\t\tif podObject, ok := objects[0].(*v1.Pod); !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected v1.Pod object in manifest %s, found %T\", bundle, objects[0])\n\t\t} else {\n\t\t\tpod = podObject\n\t\t}\n\t}\n\n\t{\n\t\tutilMounts := []v1.VolumeMount{\n\t\t\t{\n\t\t\t\tMountPath: \"/opt\",\n\t\t\t\tName: \"opt\",\n\t\t\t},\n\t\t}\n\t\t{\n\t\t\tinitContainer := v1.Container{\n\t\t\t\tName: \"kops-utils-cp\",\n\t\t\t\tImage: kopsUtilsImage,\n\t\t\t\tCommand: []string{\"/ko-app/kops-utils-cp\"},\n\t\t\t\tArgs: []string{\n\t\t\t\t\t\"--target-dir=/opt/kops-utils/\",\n\t\t\t\t\t\"--src=/ko-app/kops-utils-cp\",\n\t\t\t\t},\n\t\t\t\tVolumeMounts: utilMounts,\n\t\t\t}\n\t\t\tpod.Spec.InitContainers = append(pod.Spec.InitContainers, initContainer)\n\t\t}\n\n\t\tsymlinkToVersions := sets.NewString()\n\t\tfor _, etcdVersion := range etcdSupportedVersions() {\n\t\t\tif etcdVersion.SymlinkToVersion != \"\" {\n\t\t\t\tsymlinkToVersions.Insert(etcdVersion.SymlinkToVersion)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tinitContainer := v1.Container{\n\t\t\t\tName: \"init-etcd-\" + strings.ReplaceAll(etcdVersion.Version, \".\", \"-\"),\n\t\t\t\tImage: etcdVersion.Image,\n\t\t\t\tCommand: []string{\"/opt/kops-utils/kops-utils-cp\"},\n\t\t\t\tVolumeMounts: utilMounts,\n\t\t\t}\n\n\t\t\tinitContainer.Args = []string{\n\t\t\t\t\"--target-dir=/opt/etcd-v\" + etcdVersion.Version,\n\t\t\t\t\"--src=/usr/local/bin/etcd\",\n\t\t\t\t\"--src=/usr/local/bin/etcdctl\",\n\t\t\t}\n\n\t\t\tpod.Spec.InitContainers = append(pod.Spec.InitContainers, initContainer)\n\t\t}\n\n\t\tfor _, symlinkToVersion := range symlinkToVersions.List() {\n\t\t\ttargetVersions := sets.NewString()\n\n\t\t\tfor _, etcdVersion := range etcdSupportedVersions() {\n\t\t\t\tif etcdVersion.SymlinkToVersion == symlinkToVersion {\n\t\t\t\t\ttargetVersions.Insert(etcdVersion.Version)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tinitContainer := v1.Container{\n\t\t\t\tName: \"init-etcd-symlinks-\" + strings.ReplaceAll(symlinkToVersion, \".\", \"-\"),\n\t\t\t\tImage: kopsUtilsImage,\n\t\t\t\tCommand: []string{\"/opt/kops-utils/kops-utils-cp\"},\n\t\t\t\tVolumeMounts: utilMounts,\n\t\t\t}\n\n\t\t\tinitContainer.Args = []string{\n\t\t\t\t\"--symlink\",\n\t\t\t}\n\t\t\tfor _, targetVersion := range targetVersions.List() {\n\t\t\t\tinitContainer.Args = append(initContainer.Args, \"--target-dir=/opt/etcd-v\"+targetVersion)\n\t\t\t}\n\t\t\t// NOTE: Flags must come before positional arguments\n\t\t\tinitContainer.Args = append(initContainer.Args,\n\t\t\t\t\"--src=/opt/etcd-v\"+symlinkToVersion+\"/etcd\",\n\t\t\t\t\"--src=/opt/etcd-v\"+symlinkToVersion+\"/etcdctl\",\n\t\t\t)\n\n\t\t\tpod.Spec.InitContainers = append(pod.Spec.InitContainers, initContainer)\n\t\t}\n\n\t\t// Remap image via AssetBuilder\n\t\tfor i := range pod.Spec.InitContainers {\n\t\t\tinitContainer := &pod.Spec.InitContainers[i]\n\t\t\tremapped, err := b.AssetBuilder.RemapImage(initContainer.Image)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to remap init container image %q: %w\", container.Image, err)\n\t\t\t}\n\t\t\tinitContainer.Image = remapped\n\t\t}\n\t}\n\n\t{\n\t\tif len(pod.Spec.Containers) != 1 {\n\t\t\treturn nil, fmt.Errorf(\"expected exactly one container in etcd-manager Pod, found %d\", len(pod.Spec.Containers))\n\t\t}\n\t\tcontainer = &pod.Spec.Containers[0]\n\n\t\tif etcdCluster.Manager != nil && etcdCluster.Manager.Image != \"\" {\n\t\t\tklog.Warningf(\"overloading image in manifest %s with images %s\", bundle, etcdCluster.Manager.Image)\n\t\t\tcontainer.Image = etcdCluster.Manager.Image\n\t\t}\n\n\t\t// Remap image via AssetBuilder\n\t\tremapped, err := b.AssetBuilder.RemapImage(container.Image)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to remap container image %q: %w\", container.Image, err)\n\t\t}\n\t\tcontainer.Image = remapped\n\t}\n\n\tvar clientHost string\n\n\tif featureflag.APIServerNodes.Enabled() {\n\t\tclientHost = etcdCluster.Name + \".etcd.internal.\" + b.ClusterName()\n\t} else {\n\t\tclientHost = \"__name__\"\n\t}\n\n\tclusterName := \"etcd-\" + etcdCluster.Name\n\tbackupStore := \"\"\n\tif etcdCluster.Backups != nil {\n\t\tbackupStore = etcdCluster.Backups.BackupStore\n\t}\n\n\tpod.Name = \"etcd-manager-\" + etcdCluster.Name\n\n\tif pod.Annotations == nil {\n\t\tpod.Annotations = make(map[string]string)\n\t}\n\n\tif featureflag.APIServerNodes.Enabled() {\n\t\tpod.Annotations[\"dns.alpha.kubernetes.io/internal\"] = clientHost\n\t}\n\n\tif pod.Labels == nil {\n\t\tpod.Labels = make(map[string]string)\n\t}\n\tfor k, v := range SelectorForCluster(etcdCluster) {\n\t\tpod.Labels[k] = v\n\t}\n\n\t// The dns suffix logic mirrors the existing logic, so we should be compatible with existing clusters\n\t// (etcd makes it difficult to change peer urls, treating it as a cluster event, for reasons unknown)\n\tdnsInternalSuffix := \".internal.\" + b.Cluster.Name\n\n\tports, err := PortsForCluster(etcdCluster)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch etcdCluster.Name {\n\tcase \"main\":\n\t\tclusterName = \"etcd\"\n\n\tcase \"events\":\n\t\t// ok\n\n\tcase \"cilium\":\n\t\tif !featureflag.APIServerNodes.Enabled() {\n\t\t\tclientHost = b.Cluster.APIInternalName()\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown etcd cluster key %q\", etcdCluster.Name)\n\t}\n\n\tif backupStore == \"\" {\n\t\treturn nil, fmt.Errorf(\"backupStore must be set for use with etcd-manager\")\n\t}\n\n\tname := clusterName\n\tif !strings.HasPrefix(name, \"etcd\") {\n\t\t// For sanity, and to avoid collisions in directories / dns\n\t\treturn nil, fmt.Errorf(\"unexpected name for etcd cluster (must start with etcd): %q\", name)\n\t}\n\tlogFile := \"/var/log/\" + name + \".log\"\n\n\tconfig := &config{\n\t\tContainerized: true,\n\t\tClusterName: clusterName,\n\t\tBackupStore: backupStore,\n\t\tGrpcPort: ports.GRPCPort,\n\t\tDNSSuffix: dnsInternalSuffix,\n\t}\n\n\tconfig.LogLevel = 6\n\n\tif etcdCluster.Manager != nil && etcdCluster.Manager.LogLevel != nil {\n\t\tklog.Warningf(\"overriding log level in manifest %s, new level is %d\", bundle, int(*etcdCluster.Manager.LogLevel))\n\t\tconfig.LogLevel = int(*etcdCluster.Manager.LogLevel)\n\t}\n\n\tif etcdCluster.Manager != nil && etcdCluster.Manager.BackupInterval != nil {\n\t\tconfig.BackupInterval = fi.PtrTo(etcdCluster.Manager.BackupInterval.Duration.String())\n\t}\n\n\tif etcdCluster.Manager != nil && etcdCluster.Manager.DiscoveryPollInterval != nil {\n\t\tconfig.DiscoveryPollInterval = fi.PtrTo(etcdCluster.Manager.DiscoveryPollInterval.Duration.String())\n\t}\n\n\t{\n\t\tscheme := \"https\"\n\n\t\tconfig.PeerUrls = fmt.Sprintf(\"%s://__name__:%d\", scheme, ports.PeerPort)\n\t\tconfig.ClientUrls = fmt.Sprintf(\"%s://%s:%d\", scheme, clientHost, ports.ClientPort)\n\t\tconfig.QuarantineClientUrls = fmt.Sprintf(\"%s://__name__:%d\", scheme, ports.QuarantinedGRPCPort)\n\n\t\t// TODO: We need to wire these into the etcd-manager spec\n\t\t// // add timeout/heartbeat settings\n\t\tif etcdCluster.LeaderElectionTimeout != nil {\n\t\t\t// envs = append(envs, v1.EnvVar{Name: \"ETCD_ELECTION_TIMEOUT\", Value: convEtcdSettingsToMs(etcdClusterSpec.LeaderElectionTimeout)})\n\t\t\treturn nil, fmt.Errorf(\"LeaderElectionTimeout not supported by etcd-manager\")\n\t\t}\n\t\tif etcdCluster.HeartbeatInterval != nil {\n\t\t\t// envs = append(envs, v1.EnvVar{Name: \"ETCD_HEARTBEAT_INTERVAL\", Value: convEtcdSettingsToMs(etcdClusterSpec.HeartbeatInterval)})\n\t\t\treturn nil, fmt.Errorf(\"HeartbeatInterval not supported by etcd-manager\")\n\t\t}\n\t}\n\n\t{\n\t\tswitch b.Cluster.Spec.GetCloudProvider() {\n\t\tcase kops.CloudProviderAWS:\n\t\t\tconfig.VolumeProvider = \"aws\"\n\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\tfmt.Sprintf(\"kubernetes.io/cluster/%s=owned\", b.Cluster.Name),\n\t\t\t\tawsup.TagNameEtcdClusterPrefix + etcdCluster.Name,\n\t\t\t\tawsup.TagNameRolePrefix + \"control-plane=1\",\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = awsup.TagNameEtcdClusterPrefix + etcdCluster.Name\n\n\t\tcase kops.CloudProviderAzure:\n\t\t\tconfig.VolumeProvider = \"azure\"\n\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\t// Use dash (_) as a splitter. Other CSPs use slash (/), but slash is not\n\t\t\t\t// allowed as a tag key in Azure.\n\t\t\t\tfmt.Sprintf(\"kubernetes.io_cluster_%s=owned\", b.Cluster.Name),\n\t\t\t\tazure.TagNameEtcdClusterPrefix + etcdCluster.Name,\n\t\t\t\tazure.TagNameRolePrefix + \"control_plane=1\",\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = azure.TagNameEtcdClusterPrefix + etcdCluster.Name\n\n\t\tcase kops.CloudProviderGCE:\n\t\t\tconfig.VolumeProvider = \"gce\"\n\n\t\t\tclusterLabel := gce.LabelForCluster(b.Cluster.Name)\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\tclusterLabel.Key + \"=\" + clusterLabel.Value,\n\t\t\t\tgce.GceLabelNameEtcdClusterPrefix + etcdCluster.Name,\n\t\t\t\tgce.GceLabelNameRolePrefix + \"master=master\",\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = gce.GceLabelNameEtcdClusterPrefix + etcdCluster.Name\n\n\t\tcase kops.CloudProviderDO:\n\t\t\tconfig.VolumeProvider = \"do\"\n\n\t\t\t// DO does not support . in tags / names\n\t\t\tsafeClusterName := do.SafeClusterName(b.Cluster.Name)\n\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\tfmt.Sprintf(\"%s=%s\", do.TagKubernetesClusterNamePrefix, safeClusterName),\n\t\t\t\tdo.TagKubernetesClusterIndex,\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = do.TagNameEtcdClusterPrefix + etcdCluster.Name\n\n\t\tcase kops.CloudProviderHetzner:\n\t\t\tconfig.VolumeProvider = \"hetzner\"\n\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\tfmt.Sprintf(\"%s=%s\", hetzner.TagKubernetesClusterName, b.Cluster.Name),\n\t\t\t\tfmt.Sprintf(\"%s=%s\", hetzner.TagKubernetesVolumeRole, etcdCluster.Name),\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = fmt.Sprintf(\"%s=%s\", hetzner.TagKubernetesInstanceGroup, instanceGroupName)\n\n\t\tcase kops.CloudProviderOpenstack:\n\t\t\tconfig.VolumeProvider = \"openstack\"\n\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\topenstack.TagNameEtcdClusterPrefix + etcdCluster.Name,\n\t\t\t\topenstack.TagNameRolePrefix + \"control-plane=1\",\n\t\t\t\tfmt.Sprintf(\"%s=%s\", openstack.TagClusterName, b.Cluster.Name),\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = openstack.TagNameEtcdClusterPrefix + etcdCluster.Name\n\t\t\tconfig.NetworkCIDR = fi.PtrTo(b.Cluster.Spec.Networking.NetworkCIDR)\n\n\t\tcase kops.CloudProviderScaleway:\n\t\t\tconfig.VolumeProvider = \"scaleway\"\n\n\t\t\tconfig.VolumeTag = []string{\n\t\t\t\tfmt.Sprintf(\"%s=%s\", scaleway.TagClusterName, b.Cluster.Name),\n\t\t\t\tfmt.Sprintf(\"%s=%s\", scaleway.TagNameEtcdClusterPrefix, etcdCluster.Name),\n\t\t\t\tfmt.Sprintf(\"%s=%s\", scaleway.TagNameRolePrefix, scaleway.TagRoleControlPlane),\n\t\t\t}\n\t\t\tconfig.VolumeNameTag = fmt.Sprintf(\"%s=%s\", scaleway.TagInstanceGroup, instanceGroupName)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"CloudProvider %q not supported with etcd-manager\", b.Cluster.Spec.GetCloudProvider())\n\t\t}\n\t}\n\n\targs, err := flagbuilder.BuildFlagsList(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t{\n\t\tcontainer.Command = exec.WithTee(\"/etcd-manager\", args, \"/var/log/etcd.log\")\n\n\t\tcpuRequest := resource.MustParse(\"200m\")\n\t\tif etcdCluster.CPURequest != nil {\n\t\t\tcpuRequest = *etcdCluster.CPURequest\n\t\t}\n\t\tmemoryRequest := resource.MustParse(\"100Mi\")\n\t\tif etcdCluster.MemoryRequest != nil {\n\t\t\tmemoryRequest = *etcdCluster.MemoryRequest\n\t\t}\n\n\t\tcontainer.Resources = v1.ResourceRequirements{\n\t\t\tRequests: v1.ResourceList{\n\t\t\t\tv1.ResourceCPU: cpuRequest,\n\t\t\t\tv1.ResourceMemory: memoryRequest,\n\t\t\t},\n\t\t}\n\n\t\tkubemanifest.AddHostPathMapping(pod, container, \"varlogetcd\", \"/var/log/etcd.log\",\n\t\t\tkubemanifest.WithReadWrite(),\n\t\t\tkubemanifest.WithType(v1.HostPathFileOrCreate),\n\t\t\tkubemanifest.WithHostPath(logFile))\n\n\t\tif fi.ValueOf(b.Cluster.Spec.UseHostCertificates) {\n\t\t\tkubemanifest.AddHostPathMapping(pod, container, \"etc-ssl-certs\", \"/etc/ssl/certs\", kubemanifest.WithType(v1.HostPathDirectoryOrCreate))\n\t\t}\n\t}\n\n\tenvMap := env.BuildSystemComponentEnvVars(&b.Cluster.Spec)\n\n\tcontainer.Env = envMap.ToEnvVars()\n\n\tif etcdCluster.Manager != nil {\n\t\tif etcdCluster.Manager.BackupRetentionDays != nil {\n\t\t\tenvVar := v1.EnvVar{\n\t\t\t\tName: \"ETCD_MANAGER_DAILY_BACKUPS_RETENTION\",\n\t\t\t\tValue: strconv.FormatUint(uint64(fi.ValueOf(etcdCluster.Manager.BackupRetentionDays)), 10) + \"d\",\n\t\t\t}\n\n\t\t\tcontainer.Env = append(container.Env, envVar)\n\t\t}\n\n\t\tif len(etcdCluster.Manager.ListenMetricsURLs) > 0 {\n\t\t\tenvVar := v1.EnvVar{\n\t\t\t\tName: \"ETCD_LISTEN_METRICS_URLS\",\n\t\t\t\tValue: strings.Join(etcdCluster.Manager.ListenMetricsURLs, \",\"),\n\t\t\t}\n\n\t\t\tcontainer.Env = append(container.Env, envVar)\n\t\t}\n\n\t\tfor _, envVar := range etcdCluster.Manager.Env {\n\t\t\tklog.V(2).Infof(\"overloading ENV var in manifest %s with %s=%s\", bundle, envVar.Name, envVar.Value)\n\t\t\tconfigOverwrite := v1.EnvVar{\n\t\t\t\tName: envVar.Name,\n\t\t\t\tValue: envVar.Value,\n\t\t\t}\n\n\t\t\tcontainer.Env = append(container.Env, configOverwrite)\n\t\t}\n\t}\n\n\t{\n\t\tfoundPKI := false\n\t\tfor i := range pod.Spec.Volumes {\n\t\t\tv := &pod.Spec.Volumes[i]\n\t\t\tif v.Name == \"pki\" {\n\t\t\t\tif v.HostPath == nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"found PKI volume, but HostPath was nil\")\n\t\t\t\t}\n\t\t\t\tdirname := \"etcd-manager-\" + etcdCluster.Name\n\t\t\t\tv.HostPath.Path = \"/etc/kubernetes/pki/\" + dirname\n\t\t\t\tfoundPKI = true\n\t\t\t}\n\t\t}\n\t\tif !foundPKI {\n\t\t\treturn nil, fmt.Errorf(\"did not find PKI volume\")\n\t\t}\n\t}\n\n\tkubemanifest.MarkPodAsCritical(pod)\n\tkubemanifest.MarkPodAsClusterCritical(pod)\n\n\treturn pod, nil\n}", "func (p *Pod) SetImages(ctx context.Context, path string, imageSpecs ImageSpecs) error {\n\tns, n := client.Namespaced(path)\n\tauth, err := p.Client().CanI(ns, \"v1/pod\", []string{client.PatchVerb})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !auth {\n\t\treturn fmt.Errorf(\"user is not authorized to patch a deployment\")\n\t}\n\tmanager, isManaged, err := p.isControlled(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isManaged {\n\t\treturn fmt.Errorf(\"Unable to set image. This pod is managed by %s. Please set the image on the controller\", manager)\n\t}\n\tjsonPatch, err := GetJsonPatch(imageSpecs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdial, err := p.Client().Dial()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = dial.CoreV1().Pods(ns).Patch(\n\t\tctx,\n\t\tn,\n\t\ttypes.StrategicMergePatchType,\n\t\tjsonPatch,\n\t\tmetav1.PatchOptions{},\n\t)\n\treturn err\n}", "func (rc *regClient) TagDelete(ctx context.Context, ref types.Ref) error {\n\tvar tempManifest manifest.Manifest\n\tif ref.Tag == \"\" {\n\t\treturn ErrMissingTag\n\t}\n\n\t// attempt to delete the tag directly, available in OCI distribution-spec, and Hub API\n\treq := httpReq{\n\t\thost: ref.Registry,\n\t\tnoMirrors: true,\n\t\tapis: map[string]httpReqAPI{\n\t\t\t\"\": {\n\t\t\t\tmethod: \"DELETE\",\n\t\t\t\trepository: ref.Repository,\n\t\t\t\tpath: \"manifests/\" + ref.Tag,\n\t\t\t\tignoreErr: true, // do not trigger backoffs if this fails\n\t\t\t},\n\t\t\t\"hub\": {\n\t\t\t\tmethod: \"DELETE\",\n\t\t\t\tpath: \"repositories/\" + ref.Repository + \"/tags/\" + ref.Tag + \"/\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresp, err := rc.httpDo(ctx, req)\n\tif resp != nil {\n\t\tdefer resp.Close()\n\t}\n\t// TODO: Hub may return a different status\n\tif err == nil && resp != nil && resp.HTTPResponse().StatusCode == 202 {\n\t\treturn nil\n\t}\n\t// ignore errors, fallback to creating a temporary manifest to replace the tag and deleting that manifest\n\n\t// lookup the current manifest media type\n\tcurManifest, err := rc.ManifestHead(ctx, ref)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// create empty image config with single label\n\t// Note, this should be MediaType specific, but it appears that docker uses OCI for the config\n\tnow := time.Now()\n\tconf := ociv1.Image{\n\t\tCreated: &now,\n\t\tConfig: ociv1.ImageConfig{\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"delete-tag\": ref.Tag,\n\t\t\t\t\"delete-date\": now.String(),\n\t\t\t},\n\t\t},\n\t\tOS: \"linux\",\n\t\tArchitecture: \"amd64\",\n\t\tRootFS: ociv1.RootFS{\n\t\t\tType: \"layers\",\n\t\t\tDiffIDs: []digest.Digest{},\n\t\t},\n\t}\n\tconfB, err := json.Marshal(conf)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdigester := digest.Canonical.Digester()\n\tconfBuf := bytes.NewBuffer(confB)\n\t_, err = confBuf.WriteTo(digester.Hash())\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfDigest := digester.Digest()\n\n\t// create manifest with config, matching the original tag manifest type\n\tswitch curManifest.GetMediaType() {\n\tcase MediaTypeOCI1Manifest, MediaTypeOCI1ManifestList:\n\t\ttempManifest, err = manifest.FromOrig(ociv1.Manifest{\n\t\t\tVersioned: ociv1Specs.Versioned{\n\t\t\t\tSchemaVersion: 1,\n\t\t\t},\n\t\t\tConfig: ociv1.Descriptor{\n\t\t\t\tMediaType: MediaTypeOCI1ImageConfig,\n\t\t\t\tDigest: confDigest,\n\t\t\t\tSize: int64(len(confB)),\n\t\t\t},\n\t\t\tLayers: []ociv1.Descriptor{},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault: // default to the docker v2 schema\n\t\ttempManifest, err = manifest.FromOrig(dockerSchema2.Manifest{\n\t\t\tVersioned: dockerManifest.Versioned{\n\t\t\t\tSchemaVersion: 2,\n\t\t\t\tMediaType: MediaTypeDocker2Manifest,\n\t\t\t},\n\t\t\tConfig: dockerDistribution.Descriptor{\n\t\t\t\tMediaType: MediaTypeDocker2ImageConfig,\n\t\t\t\tDigest: confDigest,\n\t\t\t\tSize: int64(len(confB)),\n\t\t\t},\n\t\t\tLayers: []dockerDistribution.Descriptor{},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\trc.log.WithFields(logrus.Fields{\n\t\t\"ref\": ref.Reference,\n\t}).Debug(\"Sending dummy manifest to replace tag\")\n\n\t// push config\n\t_, _, err = rc.BlobPut(ctx, ref, confDigest, ioutil.NopCloser(bytes.NewReader(confB)), MediaTypeDocker2ImageConfig, int64(len(confB)))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed sending dummy config to delete %s: %w\", ref.CommonName(), err)\n\t}\n\n\t// push manifest to tag\n\terr = rc.ManifestPut(ctx, ref, tempManifest)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed sending dummy manifest to delete %s: %w\", ref.CommonName(), err)\n\t}\n\n\tref.Digest = tempManifest.GetDigest().String()\n\n\t// delete manifest by digest\n\trc.log.WithFields(logrus.Fields{\n\t\t\"ref\": ref.Reference,\n\t\t\"digest\": ref.Digest,\n\t}).Debug(\"Deleting dummy manifest\")\n\terr = rc.ManifestDelete(ctx, ref)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed deleting dummy manifest for %s: %w\", ref.CommonName(), err)\n\t}\n\n\treturn nil\n}", "func putImageConfig(ctx context.Context, img imageSpec, auth string, tgzInfo *layerMetadata) (json.RawMessage, error) {\n\tnow := time.Now().UTC()\n\trunConfig := struct {\n\t\tArch string `json:\"architecture\"`\n\t\tOS string `json:\"os\"`\n\t\tTime time.Time `json:\"created\"`\n\t\tConfig containerConfig `json:\"config\"`\n\t\tRootfs struct {\n\t\t\tType string `json:\"type\"`\n\t\t\tDiffs []string `json:\"diff_ids\"`\n\t\t} `json:\"rootfs\"`\n\t}{\n\t\tArch: \"amd64\",\n\t\tOS: \"linux\",\n\t\tTime: now,\n\t\tConfig: containerConfig{\n\t\t\tEnv: []string{\"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"},\n\t\t\tCmd: []string{insideContainerPath},\n\t\t\tArgsEscaped: true,\n\t\t\tWorkingDir: \"/\",\n\t\t},\n\t}\n\trunConfig.Rootfs.Type = \"layers\"\n\trunConfig.Rootfs.Diffs = []string{tgzInfo.innerDigest}\n\tbody, err := json.Marshal(&runConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfigDigest := fmt.Sprintf(\"sha256:%x\", sha256.Sum256(body))\n\n\tif err := uploadBlob(ctx, img, auth, body); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttype blobInfo struct {\n\t\tMediaType string `json:\"mediaType\"`\n\t\tSize int `json:\"size\"`\n\t\tDigest string `json:\"digest\"`\n\t}\n\tmanifest := struct {\n\t\tVersion int `json:\"schemaVersion\"`\n\t\tMediaType string `json:\"mediaType\"`\n\t\tConfig blobInfo `json:\"config\"`\n\t\tLayers []blobInfo `json:\"layers\"`\n\t}{\n\t\tVersion: 2,\n\t\tMediaType: \"application/vnd.docker.distribution.manifest.v2+json\",\n\t\tConfig: blobInfo{\n\t\t\tMediaType: \"application/vnd.docker.container.image.v1+json\",\n\t\t\tSize: len(body),\n\t\t\tDigest: configDigest,\n\t\t},\n\t\tLayers: []blobInfo{\n\t\t\t{\n\t\t\t\tMediaType: \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n\t\t\t\tSize: tgzInfo.outerSize,\n\t\t\t\tDigest: tgzInfo.outerDigest,\n\t\t\t},\n\t\t},\n\t}\n\treturn json.Marshal(&manifest)\n}", "func writeContainerFile(tempDir string) {\n\tcontainerFilePath := filepath.Join(tempDir, metaInfFolderName, containerFilename)\n\tif err := ioutil.WriteFile(\n\t\tcontainerFilePath,\n\t\t[]byte(\n\t\t\tfmt.Sprintf(\n\t\t\t\tcontainerFileTemplate,\n\t\t\t\tcontentFolderName,\n\t\t\t\tpkgFilename,\n\t\t\t),\n\t\t),\n\t\tfilePermissions,\n\t); err != nil {\n\t\tpanic(fmt.Sprintf(\"Error writing container file: %s\", err))\n\t}\n}", "func addPodMetadata(c kubernetes.Interface, field, podName, namespace, key, value string) error {\n\tmetadata := map[string]interface{}{\n\t\t\"metadata\": map[string]interface{}{\n\t\t\tfield: map[string]string{\n\t\t\t\tkey: value,\n\t\t\t},\n\t\t},\n\t}\n\tvar err error\n\tpatch, err := json.Marshal(metadata)\n\tif err != nil {\n\t\treturn errors.InternalWrapError(err)\n\t}\n\tfor attempt := 0; attempt < patchRetries; attempt++ {\n\t\t_, err = c.Core().Pods(namespace).Patch(podName, types.MergePatchType, patch)\n\t\tif err != nil {\n\t\t\tif !apierr.IsConflict(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\treturn err\n}", "func WriteImageSummary(scope *Scope, writer tf.Output, step tf.Output, tag tf.Output, tensor tf.Output, bad_color tf.Output, optional ...WriteImageSummaryAttr) (o *tf.Operation) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"WriteImageSummary\",\n\t\tInput: []tf.Input{\n\t\t\twriter, step, tag, tensor, bad_color,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\treturn scope.AddOperation(opspec)\n}", "func (o EnvironmentContainerImageOutput) Tag() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v EnvironmentContainerImage) *string { return v.Tag }).(pulumi.StringPtrOutput)\n}", "func MultiWrite(tagToImage map[name.Tag]v1.Image, w io.Writer, opts ...WriteOption) error {\n\trefToImage := make(map[name.Reference]v1.Image, len(tagToImage))\n\tfor i, d := range tagToImage {\n\t\trefToImage[i] = d\n\t}\n\treturn MultiRefWrite(refToImage, w, opts...)\n}", "func (h *podDeletionHandler) Track(p *corev1.Pod) {\n\tlog.Printf(\"[track_pod] %s/%s\", p.GetNamespace(), p.GetName())\n\tfor _, c := range p.Spec.Containers {\n\t\th.pods.add(pod{\n\t\t\tnamespace: p.Namespace,\n\t\t\tname: p.Name}, canonicalImage(c.Image))\n\t}\n}", "func (f *fixture) buildPod(namespace k8s.Namespace, name string, podLabels labels.Set, rs *appsv1.ReplicaSet) *v1.Pod {\n\tf.t.Helper()\n\n\tif podLabels == nil {\n\t\tpodLabels = make(labels.Set)\n\t}\n\n\tp := &v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tUID: types.UID(name + \"-uid\"),\n\t\t\tNamespace: namespace.String(),\n\t\t\tName: name,\n\t\t\tLabels: podLabels,\n\t\t},\n\t\tStatus: v1.PodStatus{\n\t\t\tPhase: v1.PodRunning,\n\t\t},\n\t}\n\n\tif rs != nil {\n\t\tif rs.Namespace != p.Namespace {\n\t\t\tf.t.Fatalf(\"Pod (namespace=%s) cannot differ from ReplicaSet (namespace=%s)\", p.Namespace, rs.Namespace)\n\t\t}\n\t\tp.OwnerReferences = []metav1.OwnerReference{k8s.RuntimeObjToOwnerRef(rs)}\n\t}\n\n\treturn p\n}", "func (m *manifestService) Put(ctx context.Context, manifest distribution.Manifest, options ...distribution.ManifestServiceOption) (digest.Digest, error) {\n\tcontext.GetLogger(ctx).Debugf(\"(*manifestService).Put\")\n\n\tmh, err := NewManifestHandler(m.repo, manifest)\n\tif err != nil {\n\t\treturn \"\", regapi.ErrorCodeManifestInvalid.WithDetail(err)\n\t}\n\tmediaType, payload, _, err := mh.Payload()\n\tif err != nil {\n\t\treturn \"\", regapi.ErrorCodeManifestInvalid.WithDetail(err)\n\t}\n\n\t// this is fast to check, let's do it before verification\n\tif !m.acceptschema2 && mediaType == schema2.MediaTypeManifest {\n\t\treturn \"\", regapi.ErrorCodeManifestInvalid.WithDetail(fmt.Errorf(\"manifest V2 schema 2 not allowed\"))\n\t}\n\n\t// in order to stat the referenced blobs, repository need to be set on the context\n\tif err := mh.Verify(withRepository(ctx, m.repo), false); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t_, err = m.manifests.Put(withRepository(ctx, m.repo), manifest, options...)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tconfig, err := mh.Config(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdgst, err := mh.Digest()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Upload to openshift\n\tism := imageapiv1.ImageStreamMapping{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: m.repo.namespace,\n\t\t\tName: m.repo.name,\n\t\t},\n\t\tImage: imageapiv1.Image{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: dgst.String(),\n\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\timageapi.ManagedByOpenShiftAnnotation: \"true\",\n\t\t\t\t\timageapi.ImageManifestBlobStoredAnnotation: \"true\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tDockerImageReference: fmt.Sprintf(\"%s/%s/%s@%s\", m.repo.config.registryAddr, m.repo.namespace, m.repo.name, dgst.String()),\n\t\t\tDockerImageManifest: string(payload),\n\t\t\tDockerImageManifestMediaType: mediaType,\n\t\t\tDockerImageConfig: string(config),\n\t\t},\n\t}\n\n\tfor _, option := range options {\n\t\tif opt, ok := option.(distribution.WithTagOption); ok {\n\t\t\tism.Tag = opt.Tag\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif _, err = m.repo.registryOSClient.ImageStreamMappings(m.repo.namespace).Create(&ism); err != nil {\n\t\t// if the error was that the image stream wasn't found, try to auto provision it\n\t\tstatusErr, ok := err.(*kerrors.StatusError)\n\t\tif !ok {\n\t\t\tcontext.GetLogger(ctx).Errorf(\"error creating ImageStreamMapping: %s\", err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif quotautil.IsErrorQuotaExceeded(statusErr) {\n\t\t\tcontext.GetLogger(ctx).Errorf(\"denied creating ImageStreamMapping: %v\", statusErr)\n\t\t\treturn \"\", distribution.ErrAccessDenied\n\t\t}\n\n\t\tstatus := statusErr.ErrStatus\n\t\tkind := strings.ToLower(status.Details.Kind)\n\t\tisValidKind := kind == \"imagestream\" /*pre-1.2*/ || kind == \"imagestreams\" /*1.2 to 1.6*/ || kind == \"imagestreammappings\" /*1.7+*/\n\t\tif !isValidKind || status.Code != http.StatusNotFound || status.Details.Name != m.repo.name {\n\t\t\tcontext.GetLogger(ctx).Errorf(\"error creating ImageStreamMapping: %s\", err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif _, err := m.repo.createImageStream(ctx); err != nil {\n\t\t\tif e, ok := err.(errcode.Error); ok && e.ErrorCode() == errcode.ErrorCodeUnknown {\n\t\t\t\t// TODO: convert statusErr to distribution error\n\t\t\t\treturn \"\", statusErr\n\t\t\t}\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t// try to create the ISM again\n\t\tif _, err := m.repo.registryOSClient.ImageStreamMappings(m.repo.namespace).Create(&ism); err != nil {\n\t\t\tif quotautil.IsErrorQuotaExceeded(err) {\n\t\t\t\tcontext.GetLogger(ctx).Errorf(\"denied a creation of ImageStreamMapping: %v\", err)\n\t\t\t\treturn \"\", distribution.ErrAccessDenied\n\t\t\t}\n\t\t\tcontext.GetLogger(ctx).Errorf(\"error creating ImageStreamMapping: %s\", err)\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn dgst, nil\n}", "func Tag(ctx context.Context, nameOrID, tag, repo string, options *TagOptions) error {\n\tif options == nil {\n\t\toptions = new(TagOptions)\n\t}\n\t_ = options\n\tconn, err := bindings.GetClient(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparams := url.Values{}\n\tparams.Set(\"tag\", tag)\n\tparams.Set(\"repo\", repo)\n\tresponse, err := conn.DoRequest(ctx, nil, http.MethodPost, \"/images/%s/tag\", params, nil, nameOrID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\n\treturn response.Process(nil)\n}", "func writeKubeletFlagBytesToDisk(b []byte, kubeletDir string) error {\n\tkubeletEnvFilePath := filepath.Join(kubeletDir, constants.KubeletEnvFileName)\n\tfmt.Printf(\"[kubelet-start] Writing kubelet environment file with flags to file %q\\n\", kubeletEnvFilePath)\n\n\t// creates target folder if not already exists\n\tif err := os.MkdirAll(kubeletDir, 0700); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create directory %q\", kubeletDir)\n\t}\n\tif err := os.WriteFile(kubeletEnvFilePath, b, 0644); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to write kubelet configuration to the file %q\", kubeletEnvFilePath)\n\t}\n\treturn nil\n}", "func (o *DeploymentOpts) buildPodSpec() v1.PodSpec {\n\tpodSpec := v1.PodSpec{Containers: []v1.Container{}}\n\tfor _, imageString := range o.Images {\n\t\t// Retain just the image name\n\t\timageSplit := strings.Split(imageString, \"/\")\n\t\tname := imageSplit[len(imageSplit)-1]\n\t\t// Remove any tag or hash\n\t\tif strings.Contains(name, \":\") {\n\t\t\tname = strings.Split(name, \":\")[0]\n\t\t}\n\t\tif strings.Contains(name, \"@\") {\n\t\t\tname = strings.Split(name, \"@\")[0]\n\t\t}\n\t\tname = sanitizeAndUniquify(name)\n\t\tpodSpec.Containers = append(podSpec.Containers, v1.Container{Name: name, Image: imageString})\n\t}\n\treturn podSpec\n}", "func writePolicyInPod() {\n\n\tfirstPodName, firstPodIP := getFirstResponsivePod()\n\tpolicyWritePodURL := \"http://\" + strings.TrimSpace(firstPodIP) + \":8200/v1/sys/policy/\"\n\tldapConfigGroupPolicyPodURL := \"http://\" + strings.TrimSpace(firstPodIP) + \":8200/v1/auth/ldap/groups/\"\n\tldapConfigUserPolicyPodURL := \"http://\" + strings.TrimSpace(firstPodIP) + \":8200/v1/auth/ldap/users/\"\n\n\tfor key, val := range configMapObject.Data {\n\t\tif strings.HasSuffix(key, \".hcl\") {\n\t\t\tlog.Infof(\"Proceeding to write the policy %s with the value: %v\", key, val)\n\t\t\tbyteDataArray, err := json.Marshal(val)\n\t\t\tjsonPayload := `{ \"policy\":` + string(byteDataArray) + `}`\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"error in marshalling the %s file for passing as payload\", err)\n\t\t\t} else {\n\t\t\t\tresponse, err := FireRequest(jsonPayload, policyWritePodURL+strings.TrimSuffix(key, \".hcl\"), getAuthTokenHeaders(), common.HttpMethodPUT)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"error while creating %s policy on %s pod: %v \", key, firstPodName, err)\n\t\t\t\t}\n\t\t\t\tlog.Debugf(\"response from write policy on the pod %s is: %v\", firstPodName, response)\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Infof(\"Policy upload done, proceeding to bind the policies.\")\n\tif len(configMapObject.Data[\"ldapPolicyGroupMappings\"]) > 0 {\n\t\tvar policyMappingInterface map[string]map[string][]string\n\t\terr := json.Unmarshal([]byte(configMapObject.Data[\"ldapPolicyGroupMappings\"]), &policyMappingInterface)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"error while un-marshalling the policy mappings, err: %v\", err)\n\t\t} else {\n\t\t\treadGroups := policyMappingInterface[\"groups\"][\"r_groups\"]\n\t\t\treadWriteGroups := policyMappingInterface[\"groups\"][\"rw_groups\"]\n\t\t\treadUsers := policyMappingInterface[\"groups\"][\"r_users\"]\n\t\t\treadWriteUsers := policyMappingInterface[\"groups\"][\"rw_users\"]\n\n\t\t\treadPolicies := policyMappingInterface[\"policies\"][\"r_policy\"]\n\t\t\treadPolicyPayload := `{\"policies\":\"` + strings.Join(readPolicies, \",\") + `\"}`\n\t\t\treadWritePolicies := policyMappingInterface[\"policies\"][\"rw_policy\"]\n\t\t\treadWritePolicyPayload := `{\"policies\":\"` + strings.Join(readWritePolicies, \",\") + `\"}`\n\n\t\t\tbindPolicy(readGroups, readPolicyPayload, ldapConfigGroupPolicyPodURL)\n\t\t\tbindPolicy(readWriteGroups, readWritePolicyPayload, ldapConfigGroupPolicyPodURL)\n\t\t\tbindPolicy(readUsers, readPolicyPayload, ldapConfigUserPolicyPodURL)\n\t\t\tbindPolicy(readWriteUsers, readWritePolicyPayload, ldapConfigUserPolicyPodURL)\n\t\t}\n\t} else {\n\t\tlog.Info(\"No policy mappings found for the groups\")\n\t}\n}", "func (m *ExecMeta) WriteToDisk(dir string) error {\n\tpath := filepath.Join(dir, MetaFileName)\n\tbuf := &bytes.Buffer{}\n\tif err := m.Encode(buf); err != nil {\n\t\treturn err\n\t}\n\tif err := writeFile(path, buf.Bytes()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func testPod() string {\n\treturn `id: thepod\nlaunchables:\n my-app:\n launchable_type: hoist\n launchable_id: web\n location: https://localhost:4444/foo/bar/baz.tar.gz\nconfig:\n ENVIRONMENT: staging\nstatus_port: 8000\n`\n}", "func WriteImages(manifest Manifest, rii RegInvImage) error {\n\t// Chop off trailing \"promoter-manifest.yaml\".\n\tp := path.Dir(manifest.Filepath)\n\t// Get staging repo directory name as it is laid out in the thin manifest\n\t// dir.\n\tstagingRepoName := path.Base(p)\n\t// Construct path to the images.yaml.\n\timagesPath := path.Join(p, \"..\", \"..\",\n\t\t\"images\", stagingRepoName, \"images.yaml\")\n\tlogrus.Infoln(\"RENDER\", imagesPath)\n\n\t// Write the file.\n\terr := ioutil.WriteFile(\n\t\timagesPath, []byte(rii.ToYAML(YamlMarshalingOpts{})), 0o644)\n\treturn err\n}", "func (d *Docker) CreateImage(parentRef string) {}", "func pushTestImages(ctx context.Context, repoURL string, tags []string) error {\n\tfor _, tag := range tags {\n\t\tremoteImg := fmt.Sprintf(\"%s/podinfo:%s\", repoURL, tag)\n\t\terr := tftestenv.RetagAndPush(ctx, fmt.Sprintf(\"%s:%s\", localImg, tag), remoteImg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\treturn nil\n}", "func Ensure(ctx context.Context, kubeClient kubernetes.Interface, namespace, image string, debug bool) (bool, error) {\n\toperatorName := names.OperatorComponent\n\treplicas := int32(1)\n\timagePullPolicy := v1.PullAlways\n\n\t// If we are running with a local development image, don't try to pull from registry.\n\tif strings.HasSuffix(image, \":local\") {\n\t\timagePullPolicy = v1.PullIfNotPresent\n\t}\n\n\tcommand := []string{operatorName}\n\tif debug {\n\t\tcommand = append(command, \"-v=3\")\n\t} else {\n\t\tcommand = append(command, \"-v=1\")\n\t}\n\n\topDeployment := &appsv1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tName: operatorName,\n\t\t},\n\t\tSpec: appsv1.DeploymentSpec{\n\t\t\tReplicas: &replicas,\n\t\t\tSelector: &metav1.LabelSelector{MatchLabels: map[string]string{\"name\": operatorName}},\n\t\t\tTemplate: v1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: map[string]string{\"name\": operatorName},\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tServiceAccountName: operatorName,\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: operatorName,\n\t\t\t\t\t\t\tImage: image,\n\t\t\t\t\t\t\tCommand: command,\n\t\t\t\t\t\t\tImagePullPolicy: imagePullPolicy,\n\t\t\t\t\t\t\tSecurityContext: &v1.SecurityContext{\n\t\t\t\t\t\t\t\tRunAsNonRoot: ptr.To(true),\n\t\t\t\t\t\t\t\tAllowPrivilegeEscalation: ptr.To(false),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tEnv: []v1.EnvVar{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"WATCH_NAMESPACE\", ValueFrom: &v1.EnvVarSource{\n\t\t\t\t\t\t\t\t\t\tFieldRef: &v1.ObjectFieldSelector{\n\t\t\t\t\t\t\t\t\t\t\tFieldPath: \"metadata.namespace\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\t\t\tName: \"POD_NAME\", ValueFrom: &v1.EnvVarSource{\n\t\t\t\t\t\t\t\t\t\tFieldRef: &v1.ObjectFieldSelector{\n\t\t\t\t\t\t\t\t\t\t\tFieldPath: \"metadata.name\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}, {\n\t\t\t\t\t\t\t\t\tName: \"OPERATOR_NAME\", Value: operatorName,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tcreated, err := deployment.Ensure(ctx, kubeClient, namespace, opDeployment)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"error creating/updating Deployment\")\n\t}\n\n\terr = deployment.AwaitReady(ctx, kubeClient, namespace, opDeployment.Name)\n\n\treturn created, errors.Wrap(err, \"error awaiting Deployment ready\")\n}", "func prepareDeployment(deploymentObj metav1.Object, sha string) error {\n\t// Add sha to image, configMapRef, and secretRef\n\t// Find container in deployment that matches the deployment name\n\tapplicationContainer := findContainer(deploymentObj)\n\tif applicationContainer == nil {\n\t\treturn fmt.Errorf(\"unable to find application image in deployment spec\")\n\t}\n\n\t// Remove docker tag, if it exists.\n\t// The image in the deployment.yaml should not have a tag.\n\tshaReplacement := fmt.Sprintf(\"$1:%s\", sha)\n\t// Replace everything after the colon, if it exists. See tests for examples.\n\tregex := regexp.MustCompile(`(.*?)(:|\\z).*`)\n\tapplicationContainer.Image = regex.ReplaceAllString(applicationContainer.Image, shaReplacement)\n\n\trefName := fmt.Sprintf(\"%s-%s\", deploymentObj.GetName(), sha)\n\t// Stub out references to configmap and secret ref to be filled out for each region later.\n\tenvSourceConfigMap := v1.EnvFromSource{\n\t\tConfigMapRef: &v1.ConfigMapEnvSource{\n\t\t\tv1.LocalObjectReference{\n\t\t\t\tName: refName,\n\t\t\t},\n\t\t\tboolRef(false),\n\t\t},\n\t}\n\tenvSourceSecret := v1.EnvFromSource{\n\t\tSecretRef: &v1.SecretEnvSource{\n\t\t\tv1.LocalObjectReference{\n\t\t\t\tName: refName,\n\t\t\t},\n\t\t\t// Secrets may not be defined.\n\t\t\tboolRef(true),\n\t\t},\n\t}\n\tapplicationContainer.EnvFrom = append(applicationContainer.EnvFrom, envSourceConfigMap, envSourceSecret)\n\n\t// Add sha label to deployment and pod.\n\tappendLabel(deploymentObj, \"sha\", sha)\n\tappendLabel(findPodTemplateSpec(deploymentObj), \"sha\", sha)\n\n\treturn nil\n}", "func createNginxDeployment() {\n\tdeploymentData := &appsv1beat.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"test-nginx\",\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"name\": \"test-nginx\",\n\t\t\t},\n\t\t\tAnnotations: map[string]string{\n\t\t\t\t\"name\": \"test-nginx\",\n\t\t\t},\n\t\t},\n\t\tSpec: appsv1beat.DeploymentSpec{\n\t\t\tReplicas: int32Ptr(1),\n\t\t\tTemplate: apiv1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"app\": \"test-nginx\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: apiv1.PodSpec{\n\t\t\t\t\tContainers: []apiv1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"test-nginx\",\n\t\t\t\t\t\t\tImage: \"test-nginx\",\n\t\t\t\t\t\t\tImagePullPolicy: apiv1.PullNever,\n\t\t\t\t\t\t\tCommand: []string{\"/bin/sh\"},\n\t\t\t\t\t\t\tArgs: []string{\"-c\", \"nginx -g 'daemon off;'\"},\n\t\t\t\t\t\t\tPorts: []apiv1.ContainerPort{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tContainerPort: 80,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tcreateDeployment(deploymentData)\n}", "func setImageVersion(dep *appsv1.Deployment, ctn string, version string) {\n\tfor index, value := range dep.Spec.Template.Spec.Containers {\n\t\tif value.Name == ctn {\n\t\t\tnewImage := \"\"\n\t\t\toriImage := dep.Spec.Template.Spec.Containers[index].Image\n\t\t\timageStrutct := strings.Split(oriImage, \":\")\n\t\t\tif len(imageStrutct) != 0 {\n\t\t\t\tnewImage = fmt.Sprintf(\"%s:%s\", strings.Join(imageStrutct[:len(imageStrutct)-1], \":\"), version)\n\t\t\t\tdep.Spec.Template.Spec.Containers[index].Image = newImage\n\t\t\t}\n\t\t\tlog.V(1).Info(\"SetImageVersion\", \"Deployment.Name\", dep.Name, \"Container.Name\", dep.Spec.Template.Spec.Containers[index].Name, \"Image\", newImage)\n\t\t}\n\t}\n}", "func (b *Bag) WriteTagFiles() (err error) {\n\terr = b.GenerateChecksums()\n\tif err == nil {\n\t\terr = b.writeManifest()\n\t}\n\tif err == nil {\n\t\terr = b.writeBagitFile()\n\t}\n\tif err == nil {\n\t\terr = b.writeTagManifest()\n\t}\n\n\treturn\n}", "func pvcsiUpdatePod(ctx context.Context, pod *v1.Pod, metadataSyncer *metadataSyncInformer, deleteFlag bool) {\n\tlog := logger.GetLogger(ctx)\n\tsupervisorNamespace, err := cnsconfig.GetSupervisorNamespace(ctx)\n\tif err != nil {\n\t\tlog.Errorf(\"pvCSI PODUpdatedDeleted: Unable to fetch supervisor namespace. Err: %v\", err)\n\t\treturn\n\t}\n\tvar entityReferences []cnsvolumemetadatav1alpha1.CnsOperatorEntityReference\n\tvar volumes []string\n\t// Iterate through volumes attached to pod.\n\tfor _, volume := range pod.Spec.Volumes {\n\t\tif volume.PersistentVolumeClaim != nil {\n\t\t\tvalid, pv, pvc := IsValidVolume(ctx, volume, pod, metadataSyncer)\n\t\t\tif valid {\n\t\t\t\tentityReferences = append(entityReferences,\n\t\t\t\t\tcnsvolumemetadatav1alpha1.GetCnsOperatorEntityReference(pvc.Name, pvc.Namespace,\n\t\t\t\t\t\tcnsvolumemetadatav1alpha1.CnsOperatorEntityTypePVC,\n\t\t\t\t\t\tmetadataSyncer.configInfo.Cfg.GC.TanzuKubernetesClusterUID))\n\t\t\t\tvolumes = append(volumes, pv.Spec.CSI.VolumeHandle)\n\t\t\t}\n\t\t}\n\t}\n\tif len(volumes) > 0 {\n\t\tif !deleteFlag {\n\t\t\tnewMetadata := cnsvolumemetadatav1alpha1.CreateCnsVolumeMetadataSpec(volumes,\n\t\t\t\tmetadataSyncer.configInfo.Cfg.GC, string(pod.GetUID()), pod.Name,\n\t\t\t\tcnsvolumemetadatav1alpha1.CnsOperatorEntityTypePOD, nil, pod.Namespace, entityReferences)\n\t\t\tlog.Debugf(\"pvCSI PodUpdated: Invoking create CnsVolumeMetadata : %v\", newMetadata)\n\t\t\tnewMetadata.Namespace = supervisorNamespace\n\t\t\tif err := metadataSyncer.cnsOperatorClient.Create(ctx, newMetadata); err != nil {\n\t\t\t\tlog.Errorf(\"pvCSI PodUpdated: Failed to create CnsVolumeMetadata: %v. Error: %v\", newMetadata.Name, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Infof(\"pvCSI PodUpdated: Successfully created CnsVolumeMetadata: %v\", newMetadata.Name)\n\t\t} else {\n\t\t\tvolumeMetadataName := cnsvolumemetadatav1alpha1.GetCnsVolumeMetadataName(\n\t\t\t\tmetadataSyncer.configInfo.Cfg.GC.TanzuKubernetesClusterUID, string(pod.GetUID()))\n\t\t\tlog.Debugf(\"pvCSI PodDeleted: Invoking delete on CnsVolumeMetadata : %v\", volumeMetadataName)\n\t\t\terr = metadataSyncer.cnsOperatorClient.Delete(ctx, &cnsvolumemetadatav1alpha1.CnsVolumeMetadata{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: volumeMetadataName,\n\t\t\t\t\tNamespace: supervisorNamespace,\n\t\t\t\t},\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"pvCSI PodDeleted: Failed to delete CnsVolumeMetadata: %v. Error: %v\", volumeMetadataName, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Infof(\"pvCSI PodDeleted: Successfully deleted CnsVolumeMetadata: %v\", volumeMetadataName)\n\t\t}\n\t}\n}", "func newPodForCR(cr *operatorv1alpha1.Minecraft) *corev1.Pod {\n\tvar envVars []corev1.EnvVar\n\tenvVars = []corev1.EnvVar {\n\t\tcorev1.EnvVar {\n\t\tName: \"EULA\",\n\t\tValue: cr.Spec.Uela,\n\t\t},\n\t}\n\n\tvar fsType int64\n\tfsType = int64(1000)\n\n\tlabels := map[string]string{\n\t\t\"app\": cr.Name,\n \"version\": cr.Spec.Version,\n\t\t\"uela\": cr.Spec.Uela,\n\t}\n\treturn &corev1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name + \"-pod\",\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tSecurityContext: &corev1.PodSecurityContext{\n\t\t\t\tFSGroup: &fsType,\n\t\t\t\tRunAsUser: &fsType,\n\t\t\t},\n\t\t\tContainers: []corev1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: \"minecraft\",\n\t\t\t\t\tImage: \"hoeghh/minecraft:\" + cr.Spec.Version,\n\t\t\t\t\tPorts: []corev1.ContainerPort{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tContainerPort: 25565,\n\t\t\t\t\t\t\tName: \"minecraft\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tEnv: envVars,\n\t\t\t\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"minecraft-volume\",\n\t\t\t\t\t\t\tMountPath: \"/minecraft-data\",\n\t\t\t\t\t\t\tReadOnly: false,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumes: []corev1.Volume{\n\t\t\t\t{\n\t\t\t\t\tName: \"minecraft-volume\",\n\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\tPersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{\n\t\t\t\t\t\t\tClaimName: cr.Name + \"-pvc\", //cr.Spec.StorageClassName\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func writeMetadata(f *os.File) error {\n\t// The first entry is reserved for metadata. Right now only the version\n\t// number.\n\tinitData := make([]byte, PersistedEntrySize)\n\tcopy(initData[:], registryVersion[:])\n\n\t// Write data to disk.\n\t_, err := f.WriteAt(initData, 0)\n\tif err != nil {\n\t\treturn errors.AddContext(err, \"failed to write metadata to registry\")\n\t}\n\treturn err\n}", "func (c *Client) SaveImage(ctx context.Context, image, format string, writer io.WriteCloser) error {\n\t// Parse the image name and tag.\n\tnamed, err := reference.ParseNormalizedNamed(image)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing image name %q failed: %v\", image, err)\n\t}\n\t// Add the latest lag if they did not provide one.\n\tnamed = reference.TagNameOnly(named)\n\timage = named.String()\n\n\t// Create the worker opts.\n\topt, err := c.createWorkerOpt(false)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating worker opt failed: %v\", err)\n\t}\n\n\tif opt.ImageStore == nil {\n\t\treturn errors.New(\"image store is nil\")\n\t}\n\n\texportOpts := []archive.ExportOpt{\n\t\tarchive.WithImage(opt.ImageStore, image),\n\t}\n\n\tswitch format {\n\tcase \"docker\":\n\n\tcase \"oci\":\n\t\texportOpts = append(exportOpts, archive.WithSkipDockerManifest())\n\n\tdefault:\n\t\treturn fmt.Errorf(\"%q is not a valid format\", format)\n\t}\n\n\tif err := archive.Export(ctx, opt.ContentStore, writer, exportOpts...); err != nil {\n\t\treturn fmt.Errorf(\"exporting image %s failed: %v\", image, err)\n\t}\n\n\treturn writer.Close()\n}", "func uxTag(cmd cli.Command) cli.Command {\n\tcmd.Flags = append(cmd.Flags, cli.StringFlag{\n\t\tName: \"tag\",\n\t\tUsage: \"new tag name (if empty, overwrite --image tag)\",\n\t})\n\n\toldBefore := cmd.Before\n\tcmd.Before = func(ctx *cli.Context) error {\n\t\t// Verify tag value.\n\t\tif ctx.IsSet(\"tag\") {\n\t\t\ttag := ctx.String(\"tag\")\n\t\t\tif !casext.IsValidReferenceName(tag) {\n\t\t\t\treturn errors.Wrap(fmt.Errorf(\"tag contains invalid characters: '%s'\", tag), \"invalid --tag\")\n\t\t\t}\n\t\t\tif tag == \"\" {\n\t\t\t\treturn errors.Wrap(fmt.Errorf(\"tag is empty\"), \"invalid --tag\")\n\t\t\t}\n\t\t\tctx.App.Metadata[\"--tag\"] = tag\n\t\t}\n\n\t\t// Include any old befores set.\n\t\tif oldBefore != nil {\n\t\t\treturn oldBefore(ctx)\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn cmd\n}", "func TestWriteSharedLayers(t *testing.T) {\n\t// Make a tempfile for tarball writes.\n\tfp, err := os.CreateTemp(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating temp file: %v\", err)\n\t}\n\tt.Log(fp.Name())\n\tdefer fp.Close()\n\tdefer os.Remove(fp.Name())\n\n\tconst baseImageLayerCount = 8\n\n\t// Make a random image\n\tbaseImage, err := random.Image(256, baseImageLayerCount)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating base image: %v\", err)\n\t}\n\n\t// Make another random image\n\trandLayer, err := random.Layer(256, types.DockerLayer)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating random layer %v\", err)\n\t}\n\textendedImage, err := mutate.Append(baseImage, mutate.Addendum{\n\t\tLayer: randLayer,\n\t})\n\tif err != nil {\n\t\tt.Fatalf(\"Error mutating base image %v\", err)\n\t}\n\n\t// Create two tags, one pointing to each image created.\n\ttag1, err := name.NewTag(\"gcr.io/foo/bar:latest\", name.StrictValidation)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating test tag1: %v\", err)\n\t}\n\ttag2, err := name.NewTag(\"gcr.io/baz/bat:latest\", name.StrictValidation)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating test tag2: %v\", err)\n\t}\n\trefToImage := map[name.Reference]v1.Image{\n\t\ttag1: baseImage,\n\t\ttag2: extendedImage,\n\t}\n\n\to, err := os.Create(fp.Name())\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating %q to write image tarball: %v\", fp.Name(), err)\n\t}\n\tdefer o.Close()\n\n\t// Write both images to the tarball.\n\tif err := MultiWrite(refToImage, o); err != nil {\n\t\tt.Fatalf(\"Unexpected error writing tarball: %v\", err)\n\t}\n\tfor ref, img := range refToImage {\n\t\ttag, ok := ref.(name.Tag)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\ttarImage, err := tarball.ImageFromPath(fp.Name(), &tag)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unexpected error reading tarball: %v\", err)\n\t\t}\n\t\tif err := validate.Image(tarImage); err != nil {\n\t\t\tt.Errorf(\"validate.Image: %v\", err)\n\t\t}\n\t\tif err := compare.Images(img, tarImage); err != nil {\n\t\t\tt.Errorf(\"compare.Images: %v\", err)\n\t\t}\n\t}\n\n\twantIDs := make(map[string]struct{})\n\tids, err := v1LayerIDs(baseImage)\n\tif err != nil {\n\t\tt.Fatalf(\"Error getting base image IDs: %v\", err)\n\t}\n\tfor _, id := range ids {\n\t\twantIDs[id] = struct{}{}\n\t}\n\tids, err = v1LayerIDs(extendedImage)\n\tif err != nil {\n\t\tt.Fatalf(\"Error getting extended image IDs: %v\", err)\n\t}\n\tfor _, id := range ids {\n\t\twantIDs[id] = struct{}{}\n\t}\n\n\t// base + extended layer + different top base layer\n\tif len(wantIDs) != baseImageLayerCount+2 {\n\t\tt.Errorf(\"Expected to have %d unique layer IDs but have %d\", baseImageLayerCount+2, len(wantIDs))\n\t}\n\n\tconst layerFileName = \"layer.tar\"\n\tr := tar.NewReader(fp)\n\tfor {\n\t\thdr, err := r.Next()\n\t\tif err != nil {\n\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tt.Fatalf(\"Get tar header: %v\", err)\n\t\t}\n\t\tif filepath.Base(hdr.Name) == layerFileName {\n\t\t\tid := filepath.Dir(hdr.Name)\n\t\t\tif _, ok := wantIDs[id]; ok {\n\t\t\t\tdelete(wantIDs, id)\n\t\t\t} else {\n\t\t\t\tt.Errorf(\"Found unwanted layer with ID %q\", id)\n\t\t\t}\n\t\t}\n\t}\n\tif len(wantIDs) != 0 {\n\t\tfor id := range wantIDs {\n\t\t\tt.Errorf(\"Expected to find layer with ID %q but it didn't exist\", id)\n\t\t}\n\t}\n}", "func podRWCmdExec(f *framework.Framework, pod *v1.Pod, cmd string) string {\n\tstdout, stderr, err := e2evolume.PodExec(f, pod, cmd)\n\tframework.Logf(\"podRWCmdExec cmd: %q, out: %q, stderr: %q, err: %v\", cmd, stdout, stderr, err)\n\tframework.ExpectNoError(err)\n\treturn stdout\n}", "func (vr *VulnerabilityReport) AddPod(pod, img string) bool {\n\tchanged := false\n\n\tif images, ok := vr.Status.Pods[pod]; ok {\n\t\tif !contains(images, img) {\n\t\t\timages = append(images, img)\n\t\t\tvr.Status.Pods[pod] = images\n\t\t\tchanged = true\n\t\t}\n\t\treturn changed\n\t}\n\n\tif vr.Status.Pods == nil {\n\t\tvr.Status.Pods = make(map[string][]string)\n\t}\n\n\tvr.Status.Pods[pod] = append(vr.Status.Pods[pod], img)\n\tchanged = true\n\n\treturn changed\n}", "func (pc *BasicECSPodCreator) CreatePod(ctx context.Context, opts ...cocoa.ECSPodCreationOptions) (cocoa.ECSPod, error) {\n\tmergedPodCreationOpts := cocoa.MergeECSPodCreationOptions(opts...)\n\tvar mergedPodExecutionOpts cocoa.ECSPodExecutionOptions\n\tif mergedPodCreationOpts.ExecutionOpts != nil {\n\t\tmergedPodExecutionOpts = cocoa.MergeECSPodExecutionOptions(*mergedPodCreationOpts.ExecutionOpts)\n\t}\n\n\tif err := mergedPodCreationOpts.Validate(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"invalid pod creation options\")\n\t}\n\n\tif err := mergedPodExecutionOpts.Validate(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"invalid pod execution options\")\n\t}\n\n\tif err := pc.createSecrets(ctx, &mergedPodCreationOpts); err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating new secrets\")\n\t}\n\ttaskDefinition := pc.exportPodCreationOptions(mergedPodCreationOpts)\n\n\tregisterOut, err := pc.client.RegisterTaskDefinition(ctx, taskDefinition)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"registering task definition\")\n\t}\n\n\tif registerOut.TaskDefinition == nil || registerOut.TaskDefinition.TaskDefinitionArn == nil {\n\t\treturn nil, errors.New(\"expected a task definition from ECS, but none was returned\")\n\t}\n\n\ttaskDef := cocoa.NewECSTaskDefinition().\n\t\tSetID(utility.FromStringPtr(registerOut.TaskDefinition.TaskDefinitionArn)).\n\t\tSetOwned(true)\n\n\trunTask := pc.exportTaskExecutionOptions(mergedPodExecutionOpts, *taskDef)\n\n\trunOut, err := pc.client.RunTask(ctx, runTask)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"running task for definition '%s' in cluster '%s'\", utility.FromStringPtr(runTask.TaskDefinition), utility.FromStringPtr(runTask.Cluster))\n\t}\n\n\tif len(runOut.Failures) > 0 {\n\t\tcatcher := grip.NewBasicCatcher()\n\t\tfor _, failure := range runOut.Failures {\n\t\t\tcatcher.Errorf(\"task '%s': %s: %s\\n\", utility.FromStringPtr(failure.Arn), utility.FromStringPtr(failure.Detail), utility.FromStringPtr(failure.Reason))\n\t\t}\n\t\treturn nil, errors.Wrap(catcher.Resolve(), \"running task\")\n\t}\n\n\tif len(runOut.Tasks) == 0 || runOut.Tasks[0].TaskArn == nil {\n\t\treturn nil, errors.New(\"expected a task to be running in ECS, but none was returned\")\n\t}\n\n\tresources := cocoa.NewECSPodResources().\n\t\tSetCluster(utility.FromStringPtr(mergedPodExecutionOpts.Cluster)).\n\t\tSetContainers(pc.translateContainerResources(runOut.Tasks[0].Containers, mergedPodCreationOpts.ContainerDefinitions)).\n\t\tSetTaskDefinition(*taskDef).\n\t\tSetTaskID(utility.FromStringPtr(runOut.Tasks[0].TaskArn))\n\n\tpodOpts := NewBasicECSPodOptions().\n\t\tSetClient(pc.client).\n\t\tSetVault(pc.vault).\n\t\tSetStatusInfo(translatePodStatusInfo(runOut.Tasks[0])).\n\t\tSetResources(*resources)\n\n\tp, err := NewBasicECSPod(podOpts)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating pod\")\n\t}\n\n\treturn p, nil\n}", "func generatePod(ip string) *corev1.Pod {\n\tpod := &corev1.Pod{}\n\tpod.Status.PodIP = ip\n\tpod.Status.Phase = corev1.PodRunning\n\tpod.Spec.Containers = []corev1.Container{\n\t\t{Ports: []corev1.ContainerPort{\n\t\t\t{Name: \"management\", ContainerPort: 8558},\n\t\t}},\n\t}\n\treturn pod\n}", "func OnUpdateManifest(repo, reference, mediaType string, digest godigest.Digest, body []byte,\n\tstoreController storage.StoreController, metaDB mTypes.MetaDB, log log.Logger,\n) error {\n\timgStore := storeController.GetImageStore(repo)\n\n\t// check if image is a signature\n\tisSignature, signatureType, signedManifestDigest, err := storage.CheckIsImageSignature(repo, body, reference)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"can't check if image is a signature or not\")\n\n\t\tif err := imgStore.DeleteImageManifest(repo, reference, false); err != nil {\n\t\t\tlog.Error().Err(err).Str(\"manifest\", reference).Str(\"repository\", repo).Msg(\"couldn't remove image manifest in repo\")\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn err\n\t}\n\n\tmetadataSuccessfullySet := true\n\n\tif isSignature {\n\t\tlayersInfo, errGetLayers := GetSignatureLayersInfo(repo, reference, digest.String(), signatureType, body,\n\t\t\timgStore, log)\n\t\tif errGetLayers != nil {\n\t\t\tmetadataSuccessfullySet = false\n\t\t\terr = errGetLayers\n\t\t} else {\n\t\t\terr = metaDB.AddManifestSignature(repo, signedManifestDigest, mTypes.SignatureMetadata{\n\t\t\t\tSignatureType: signatureType,\n\t\t\t\tSignatureDigest: digest.String(),\n\t\t\t\tLayersInfo: layersInfo,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tlog.Error().Err(err).Msg(\"metadb: error while putting repo meta\")\n\t\t\t\tmetadataSuccessfullySet = false\n\t\t\t} else {\n\t\t\t\terr = metaDB.UpdateSignaturesValidity(repo, signedManifestDigest)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error().Err(err).Str(\"repository\", repo).Str(\"reference\", reference).Str(\"digest\",\n\t\t\t\t\t\tsignedManifestDigest.String()).Msg(\"metadb: failed verify signatures validity for signed image\")\n\t\t\t\t\tmetadataSuccessfullySet = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\terr = SetImageMetaFromInput(repo, reference, mediaType, digest, body,\n\t\t\timgStore, metaDB, log)\n\t\tif err != nil {\n\t\t\tmetadataSuccessfullySet = false\n\t\t}\n\t}\n\n\tif !metadataSuccessfullySet {\n\t\tlog.Info().Str(\"tag\", reference).Str(\"repository\", repo).Msg(\"uploading image meta was unsuccessful for tag in repo\")\n\n\t\tif err := imgStore.DeleteImageManifest(repo, reference, false); err != nil {\n\t\t\tlog.Error().Err(err).Str(\"reference\", reference).Str(\"repository\", repo).\n\t\t\t\tMsg(\"couldn't remove image manifest in repo\")\n\n\t\t\treturn err\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s replicatedSession) WriteTagged(\n\tnamespace, id ident.ID, tags ident.TagIterator, t xtime.UnixNano,\n\tvalue float64, unit xtime.Unit, annotation []byte,\n) error {\n\treturn s.replicate(replicatedParams{\n\t\tnamespace: namespace,\n\t\tid: id,\n\t\tt: t.Add(-s.writeTimestampOffset),\n\t\tvalue: value,\n\t\tunit: unit,\n\t\tannotation: annotation,\n\t\ttags: tags,\n\t\tuseTags: true,\n\t})\n}", "func buildExecPod(name, namespace, image string) *corev1.Pod {\n\treturn &corev1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tContainers: []corev1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: \"execpod\",\n\t\t\t\t\tImage: image,\n\t\t\t\t\tCommand: []string{\"/bin/sleep\"},\n\t\t\t\t\tArgs: []string{\"4h\"},\n\t\t\t\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\t\t\t\tAllowPrivilegeEscalation: pointer.Bool(false),\n\t\t\t\t\t\tCapabilities: &corev1.Capabilities{\n\t\t\t\t\t\t\tDrop: []corev1.Capability{\"ALL\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tRunAsNonRoot: pointer.Bool(true),\n\t\t\t\t\t\tSeccompProfile: &corev1.SeccompProfile{\n\t\t\t\t\t\t\tType: corev1.SeccompProfileTypeRuntimeDefault,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tRestartPolicy: corev1.RestartPolicyNever,\n\t\t},\n\t}\n}", "func (d *swiftDriver) WriteManifest(account keppel.Account, repoName string, manifestDigest digest.Digest, contents []byte) error {\n\tc, _, err := d.getBackendConnection(account)\n\tif err != nil {\n\t\treturn err\n\t}\n\to := manifestObject(c, repoName, manifestDigest)\n\treturn uploadToObject(o, bytes.NewReader(contents), nil, nil)\n}", "func PinMediaControlsPod(tconn *chrome.TestConn) uiauto.Action {\n\tui := uiauto.New(tconn)\n\treturn uiauto.Combine(\"click pin button and check the widget\",\n\t\tui.LeftClick(nodewith.Name(\"Pin to shelf\").HasClass(\"IconButton\").Ancestor(MediaControlsDetailView)),\n\t\tui.WaitUntilExists(PinnedMediaControls),\n\t)\n}", "func MutatePod(vPod, pPod *corev1.Pod, vSASecret, SASecret *v1.Secret, services []*v1.Service) {\n\tpPod.Status = corev1.PodStatus{}\n\tpPod.Spec.NodeName = \"\"\n\n\t// setup env var map\n\tserviceEnv := getServiceEnvVarMap(pPod.Namespace, *pPod.Spec.EnableServiceLinks, services)\n\n\tfor i := range pPod.Spec.Containers {\n\t\tmutateContainerEnv(&pPod.Spec.Containers[i], vPod, serviceEnv)\n\t\tmutateContainerSecret(&pPod.Spec.Containers[i], vSASecret, SASecret)\n\t}\n\n\tfor i := range pPod.Spec.InitContainers {\n\t\tmutateContainerEnv(&pPod.Spec.InitContainers[i], vPod, serviceEnv)\n\t\tmutateContainerSecret(&pPod.Spec.InitContainers[i], vSASecret, SASecret)\n\t}\n\n\tfor i, volume := range pPod.Spec.Volumes {\n\t\tif volume.Name == vSASecret.Name {\n\t\t\tpPod.Spec.Volumes[i].Name = SASecret.Name\n\t\t\tpPod.Spec.Volumes[i].Secret.SecretName = SASecret.Name\n\t\t}\n\t}\n}", "func (imh *manifestHandler) PutManifest(w http.ResponseWriter, r *http.Request) {\n\tdcontext.GetLogger(imh).Debug(\"PutImageManifest\")\n\tmanifests, err := imh.Repository.Manifests(imh)\n\tif err != nil {\n\t\timh.Errors = append(imh.Errors, err)\n\t\treturn\n\t}\n\n\tvar jsonBuf bytes.Buffer\n\tif err := copyFullPayload(imh, w, r, &jsonBuf, maxManifestBodySize, \"image manifest PUT\"); err != nil {\n\t\t// copyFullPayload reports the error if necessary\n\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestInvalid.WithDetail(err.Error()))\n\t\treturn\n\t}\n\n\tmediaType := r.Header.Get(\"Content-Type\")\n\tmanifest, desc, err := distribution.UnmarshalManifest(mediaType, jsonBuf.Bytes())\n\tif err != nil {\n\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestInvalid.WithDetail(err))\n\t\treturn\n\t}\n\n\tif imh.Digest != \"\" {\n\t\tif desc.Digest != imh.Digest {\n\t\t\tdcontext.GetLogger(imh).Errorf(\"payload digest does not match: %q != %q\", desc.Digest, imh.Digest)\n\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeDigestInvalid)\n\t\t\treturn\n\t\t}\n\t} else if imh.Tag != \"\" {\n\t\timh.Digest = desc.Digest\n\t} else {\n\t\timh.Errors = append(imh.Errors, v2.ErrorCodeTagInvalid.WithDetail(\"no tag or digest specified\"))\n\t\treturn\n\t}\n\n\tisAnOCIManifest := mediaType == v1.MediaTypeImageManifest || mediaType == v1.MediaTypeImageIndex\n\n\tif isAnOCIManifest {\n\t\tdcontext.GetLogger(imh).Debug(\"Putting an OCI Manifest!\")\n\t} else {\n\t\tdcontext.GetLogger(imh).Debug(\"Putting a Docker Manifest!\")\n\t}\n\n\tvar options []distribution.ManifestServiceOption\n\tif imh.Tag != \"\" {\n\t\toptions = append(options, distribution.WithTag(imh.Tag))\n\t}\n\n\tif err := imh.applyResourcePolicy(manifest); err != nil {\n\t\timh.Errors = append(imh.Errors, err)\n\t\treturn\n\t}\n\n\t_, err = manifests.Put(imh, manifest, options...)\n\tif err != nil {\n\t\t// TODO(stevvooe): These error handling switches really need to be\n\t\t// handled by an app global mapper.\n\t\tif err == distribution.ErrUnsupported {\n\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnsupported)\n\t\t\treturn\n\t\t}\n\t\tif err == distribution.ErrAccessDenied {\n\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeDenied)\n\t\t\treturn\n\t\t}\n\t\tswitch err := err.(type) {\n\t\tcase distribution.ErrManifestVerification:\n\t\t\tfor _, verificationError := range err {\n\t\t\t\tswitch verificationError := verificationError.(type) {\n\t\t\t\tcase distribution.ErrManifestBlobUnknown:\n\t\t\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestBlobUnknown.WithDetail(verificationError.Digest))\n\t\t\t\tcase distribution.ErrManifestNameInvalid:\n\t\t\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeNameInvalid.WithDetail(err))\n\t\t\t\tcase distribution.ErrManifestUnverified:\n\t\t\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeManifestUnverified)\n\t\t\t\tdefault:\n\t\t\t\t\tif verificationError == digest.ErrDigestInvalidFormat {\n\t\t\t\t\t\timh.Errors = append(imh.Errors, v2.ErrorCodeDigestInvalid)\n\t\t\t\t\t} else {\n\t\t\t\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown, verificationError)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase errcode.Error:\n\t\t\timh.Errors = append(imh.Errors, err)\n\t\tdefault:\n\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))\n\t\t}\n\t\treturn\n\t}\n\n\t// Tag this manifest\n\tif imh.Tag != \"\" {\n\t\ttags := imh.Repository.Tags(imh)\n\t\terr = tags.Tag(imh, imh.Tag, desc)\n\t\tif err != nil {\n\t\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))\n\t\t\treturn\n\t\t}\n\n\t}\n\n\t// Construct a canonical url for the uploaded manifest.\n\tref, err := reference.WithDigest(imh.Repository.Named(), imh.Digest)\n\tif err != nil {\n\t\timh.Errors = append(imh.Errors, errcode.ErrorCodeUnknown.WithDetail(err))\n\t\treturn\n\t}\n\n\tlocation, err := imh.urlBuilder.BuildManifestURL(ref)\n\tif err != nil {\n\t\t// NOTE(stevvooe): Given the behavior above, this absurdly unlikely to\n\t\t// happen. We'll log the error here but proceed as if it worked. Worst\n\t\t// case, we set an empty location header.\n\t\tdcontext.GetLogger(imh).Errorf(\"error building manifest url from digest: %v\", err)\n\t}\n\n\tw.Header().Set(\"Location\", location)\n\tw.Header().Set(\"Docker-Content-Digest\", imh.Digest.String())\n\tw.WriteHeader(http.StatusCreated)\n\n\tdcontext.GetLogger(imh).Debug(\"Succeeded in putting manifest!\")\n}", "func GroupCreateAppHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\n\tlog.Infoln(\"CreateAppHandler invoked\", r.Method, r.URL.Path, r.RemoteAddr)\n\n\tuserid := vars[\"userid\"]\n\tgroupid := r.URL.Query().Get(\"groupid\")\n\ttaskid := r.URL.Query().Get(\"taskid\")\n\tif taskid == \"\" {\n\t\ttaskid = string(GenrandInt(32))\n\t}\n\n\tif len(groupid) < 1 {\n\t\trespondError(w, http.StatusBadRequest, \"groupid is requried\")\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tb, _ := ioutil.ReadAll(r.Body)\n\n\tlog.Debugln(string(b))\n\tvar js map[string]interface{}\n\n\terr := CheckPodcfg(b, false)\n\tif err != nil {\n\t\trespondError(w, http.StatusBadRequest, \"Input Error: \"+err.Error())\n\t\treturn\n\t}\n\tb, err = jsonparser.Set(b, []byte(`\"IfNotPresent\"`), \"spec\", \"containers\", \"[0]\", \"imagePullPolicy\")\n\tif err != nil {\n\t\trespondError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tcontainerimage, err := jsonparser.GetString(b, \"spec\", \"containers\", \"[0]\", \"image\")\n\tregistryL := strings.Split(strings.Split(containerimage, `:`)[0], `/`)\n\t//basename := registryL[len(registryL)-1] + fmt.Sprintf(\"-%d\", rand.Int(20))\n\tbasename := registryL[len(registryL)-1]\n\n\tb, err = jsonparser.Set(b, []byte(fmt.Sprintf(`\"%s\"`, basename)), \"metadata\", \"name\")\n\tif err != nil {\n\t\trespondError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tb, err = jsonparser.Set(b, []byte(fmt.Sprintf(`\"%s\"`, basename)), \"spec\", \"containers\", \"[0]\", \"name\")\n\tif err != nil {\n\t\trespondError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(b, &js); err != nil {\n\t\trespondError(w, http.StatusInternalServerError, \"Unexpect Error: \"+string(b))\n\t\treturn\n\t}\n\n\tb = jsonparser.Delete(b, \"spec\", \"nodeSelector\")\n\tcfg := jsonparser.Delete(b, \"spec\", \"imagePullSecrets\")\n\tlog.Debugln(string(cfg))\n\n\tT := TaskInfo{\n\t\tID: taskid,\n\t\tCurrent: 0,\n\t\tUserid: userid,\n\t\tGroupid: groupid,\n\t\tAppcfg: string(cfg),\n\t}\n\n\terr = DBGroupInQueue(T)\n\tif err != nil {\n\t\trespondError(w, http.StatusInternalServerError, \"Unexpect Error: \"+err.Error())\n\t}\n\trespondJSON(w, http.StatusOK,\n\t\tmap[string]interface{}{\"code\": 0, \"id\": T.ID})\n}", "func deployWorker(cli *dockerclient.Client, image string, identifier string, env []string) error {\n\t// Binds is the actual \"-v\" volume.\n\thostConfig := &container.HostConfig{\n\t\tLogConfig: container.LogConfig{\n\t\t\tType: \"json-file\",\n\t\t\tConfig: map[string]string{},\n\t\t},\n\t\tBinds: []string{\n\t\t\t\"/var/run/docker.sock:/var/run/docker.sock:rw\",\n\t\t},\n\t}\n\n\t// ROFL: https://docker-py.readthedocs.io/en/1.4.0/volumes/\n\tconfig := &container.Config{\n\t\tImage: image,\n\t\tEnv: env,\n\t}\n\t//Volumes: map[string]struct{}{\n\t//\t\"/var/run/docker.sock\": {},\n\t//},\n\n\tcont, err := cli.ContainerCreate(\n\t\tcontext.Background(),\n\t\tconfig,\n\t\thostConfig,\n\t\tnil,\n\t\tidentifier,\n\t)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\tcli.ContainerStart(context.Background(), cont.ID, types.ContainerStartOptions{})\n\tlog.Printf(\"Container %s is created\", cont.ID)\n\treturn nil\n}", "func makePodTemplate(image, target string, extEnv ...corev1.EnvVar) *corev1.PodTemplateSpec {\n\tenv := []corev1.EnvVar{{\n\t\tName: \"TARGET\",\n\t\tValue: target,\n\t}, {\n\t\tName: \"POD_NAME\",\n\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\tFieldPath: \"metadata.name\",\n\t\t\t},\n\t\t},\n\t}, {\n\t\tName: \"POD_NAMESPACE\",\n\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\tFieldPath: \"metadata.namespace\",\n\t\t\t},\n\t\t},\n\t}}\n\n\tif len(extEnv) > 0 {\n\t\tenv = append(env, extEnv...)\n\t}\n\n\treturn &corev1.PodTemplateSpec{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tAnnotations: map[string]string{\n\t\t\t\t\"sidecar.istio.io/inject\": \"false\",\n\t\t\t},\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tServiceAccountName: \"default\",\n\t\t\tRestartPolicy: corev1.RestartPolicyNever,\n\t\t\tContainers: []corev1.Container{{\n\t\t\t\tName: \"job\",\n\t\t\t\tImage: image,\n\t\t\t\tImagePullPolicy: \"Always\",\n\t\t\t\tEnv: env,\n\t\t\t}},\n\t\t},\n\t}\n}", "func writeImage(w http.ResponseWriter, img *image.Image) {\r\n\r\n\tbuffer := new(bytes.Buffer)\r\n\tif err := jpeg.Encode(buffer, *img, nil); err != nil {\r\n\t\tlog.Println(\"unable to encode image.\")\r\n\t}\r\n\r\n\tw.Header().Set(\"Content-Type\", \"image/jpeg\")\r\n\tw.Header().Set(\"Content-Length\", strconv.Itoa(len(buffer.Bytes())))\r\n\tif _, err := w.Write(buffer.Bytes()); err != nil {\r\n\t\tlog.Println(\"unable to write image.\")\r\n\t}\r\n}", "func createDeployment(k *kabanerov1alpha1.Kabanero, clientset *kubernetes.Clientset, c client.Client, name string, image string, env []corev1.EnvVar, envFrom []corev1.EnvFromSource, livenessProbe *corev1.Probe, reqLogger logr.Logger) error {\n\tcl := clientset.AppsV1().Deployments(k.ObjectMeta.Namespace)\n\n\t// Check if the Deployment resource already exists.\n\tdInstance := &appsv1.Deployment{}\n\terr := c.Get(context.Background(), types.NamespacedName{\n\t\tName: name,\n\t\tNamespace: k.ObjectMeta.Namespace}, dInstance)\n\n\tdeploymentExists := true\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) == false {\n\t\t\treturn err\n\t\t}\n\n\t\t// The deployment does not already exist. Create one.\n\t\tdeploymentExists = false\n\n\t\t// Gather Kabanero operator ownerReference information.\n\t\townerRef, err := getOwnerReference(k, c, reqLogger)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Initialize the deployment\n\t\tvar repCount int32 = 1\n\t\tdInstance = &appsv1.Deployment{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: name,\n\t\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t\t{\n\t\t\t\t\t\tAPIVersion: ownerRef.APIVersion,\n\t\t\t\t\t\tKind: ownerRef.Kind,\n\t\t\t\t\t\tName: ownerRef.Name,\n\t\t\t\t\t\tUID: ownerRef.UID,\n\t\t\t\t\t\tController: ownerRef.Controller,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tSpec: appsv1.DeploymentSpec{\n\t\t\t\tReplicas: &repCount,\n\t\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\t\t\"app\": name,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\t\"app\": name,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\t\tServiceAccountName: name,\n\t\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: name,\n\t\t\t\t\t\t\t\tImagePullPolicy: \"Always\",\n\t\t\t\t\t\t\t\tPorts: []corev1.ContainerPort{\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tContainerPort: 9443,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\t// Here we update the things that can change. In the future we could\n\t// consider re-applying all the fields in case someone hand-edited the\n\t// deployment object in an incompatible way.\n\tdInstance.Spec.Template.Spec.Containers[0].Env = env\n\tdInstance.Spec.Template.Spec.Containers[0].EnvFrom = envFrom\n\tdInstance.Spec.Template.Spec.Containers[0].Image = image\n\tdInstance.Spec.Template.Spec.Containers[0].LivenessProbe = livenessProbe\n\n\tif deploymentExists == false {\n\t\treqLogger.Info(fmt.Sprintf(\"createDeployment: Deployment for create: %v\", dInstance))\n\n\t\t_, err = cl.Create(dInstance)\n\t} else {\n\t\treqLogger.Info(fmt.Sprintf(\"createDeployment: Deployment for update: %v\", dInstance))\n\n\t\t_, err = cl.Update(dInstance)\n\t}\n\n\treturn err\n}", "func Write(device string, image, kernel, initrd []byte) {\n\t// write the image to the block device\n\tWriteBlockImage(device, image)\n\t// write kernel, use flag \"kernel\" to name location\n\tWriteOther(kernel, \"kernel\")\n\t// write initramfs, use name \"initrd\"\n\tWriteOther(initrd, \"initrd\")\n}", "func MultiRefWrite(refToImage map[name.Reference]v1.Image, w io.Writer, opts ...WriteOption) error {\n\t// process options\n\to := &writeOptions{\n\t\tupdates: nil,\n\t}\n\tfor _, option := range opts {\n\t\tif err := option(o); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\timageToTags := dedupRefToImage(refToImage)\n\tsize, mBytes, err := getSizeAndManifest(imageToTags)\n\tif err != nil {\n\t\treturn sendUpdateReturn(o, err)\n\t}\n\n\treturn writeImagesToTar(imageToTags, mBytes, size, w, o)\n}", "func (es *etcdStore) Put(image *Image) error {\n\timageJSON, err := json.Marshal(image)\n\tif err != nil {\n\t\tlog.WithFields(etcdLogFields).WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t\t\"image\": fmt.Sprintf(\"%+v\", image),\n\t\t}).Error(\"failed to marshal image to json\")\n\t\treturn err\n\t}\n\n\tmetadataKey := es.metadataKey(image.ID)\n\tif _, err := es.client.Set(metadataKey, string(imageJSON), 0); err != nil {\n\t\tlog.WithFields(etcdLogFields).WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t\t\"key\": metadataKey,\n\t\t\t\"value\": string(imageJSON),\n\t\t}).Error(\"failed to store image\")\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func linuxDockerWriteDockerfile(deps buildtoolmodel.Dependencies, dockerArch, golangDockerImage, uid string) {\n\tcontent := []byte(fmt.Sprintf(`\n\t\tFROM --platform=linux/%s %s\n\t\tRUN apk update\n\t\tRUN apk upgrade\n\t\tRUN apk add --no-progress gcc git linux-headers musl-dev\n\t\tRUN adduser -D -h /home/oobuild -G nobody -u %s oobuild\n\t\tENV HOME=/home/oobuild`, dockerArch, golangDockerImage, uid,\n\t))\n\tdeps.LinuxWriteDockerfile(filepath.Join(\"CLI\", \"Dockerfile\"), content, 0600)\n}" ]
[ "0.6227361", "0.5880108", "0.5780835", "0.5621885", "0.55258745", "0.5268894", "0.526887", "0.5263019", "0.5207825", "0.52056", "0.51899475", "0.51824105", "0.5133775", "0.50878125", "0.5065148", "0.50443953", "0.5037582", "0.503462", "0.5025062", "0.49834082", "0.4976932", "0.4888759", "0.48886704", "0.48684183", "0.48629206", "0.48552462", "0.4840008", "0.48388556", "0.48347878", "0.47766304", "0.4740768", "0.4740393", "0.47293252", "0.47293252", "0.47202268", "0.46939024", "0.4688689", "0.4686374", "0.4683736", "0.4659377", "0.4651324", "0.46507698", "0.4649601", "0.46489623", "0.464642", "0.46220365", "0.46199572", "0.46159676", "0.4598892", "0.45949203", "0.45900798", "0.45885453", "0.4584872", "0.45802444", "0.45620096", "0.4552183", "0.45466253", "0.45299083", "0.45278618", "0.45251006", "0.4518091", "0.45148385", "0.45131034", "0.45099297", "0.45084736", "0.45021677", "0.45020336", "0.4498764", "0.44948578", "0.4494326", "0.4488319", "0.44867298", "0.44857574", "0.44740328", "0.44722202", "0.44684437", "0.4458341", "0.4449244", "0.4448275", "0.44389454", "0.44387144", "0.4435655", "0.44354776", "0.44287682", "0.44173834", "0.44158608", "0.4411185", "0.4410018", "0.44080302", "0.44077736", "0.4403013", "0.43992755", "0.43971872", "0.43957573", "0.4394718", "0.43940806", "0.43915132", "0.43891096", "0.43848994", "0.4384879" ]
0.73809516
0
GenerateTestFile creates a file with the template values inserted into the template
func GenerateTestFile(testFileName string, templateValues *TemplateValues) error { outFile, err := os.Create(testFileName) if err != nil { fmt.Printf("Error creating test file named: %s\n", testFileName) } tmpl := template.Must(template.New("out").Parse(outputTemplate)) if err := tmpl.Execute(outFile, templateValues); err != nil { return err } if err := outFile.Close(); err != nil { return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateTestFile(fileName string) {\n\tif !strings.HasSuffix(fileName, \"_test.go\") {\n\t\treturn\n\t}\n\tcreateDir(fileName)\n\tif err := ioutil.WriteFile(fileName, []byte(mainttpl), 0644); err != nil {\n\t\tfmt.Printf(\"write file [%s] failed:%v\\n\", fileName, err)\n\t}\n}", "func GenerateWithTestFile(fileSet *token.FileSet, pkgs map[string]*ast.Package, pkgPath string, typeName string) (*ast.File, *ast.File) {\n\tpkg, spec, zeroValue, values, valueStrings, valueStringLits := findDefinitions(fileSet, pkgs, typeName)\n\treturn generateFile(pkg, spec, zeroValue, values, valueStrings), generateTestFile(pkg, pkgPath, spec, zeroValue, values, valueStringLits)\n}", "func createFile(name string, template interface{}) (interface{}, error) {\n\t// filling the template with a default value\n\tif err := iterateTemplate(template, true); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// casting a template to an array of bytes\n\tjsonBytes, err := json.MarshalIndent(template, \"\", \" \")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// write template to json file\n\tif err = ioutil.WriteFile(fmt.Sprintf(\"%s/%s.json\", configsDir, name), jsonBytes, 0644); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn template, err\n}", "func createFile(input map[string]*context,\n\ttemplate string, conf string) error {\n\t// read the template\n\tcontents, err := ioutil.ReadFile(template)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// replace\n\tfor _, ctx := range input {\n\t\tcontents = bytes.Replace(contents, []byte(ctx.templateKeyword),\n\t\t\t[]byte(ctx.cliInput), -1)\n\t}\n\t// write\n\terr = ioutil.WriteFile(conf, contents, 0644)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn nil\n}", "func GenerateTestConfig(content string) (string, error) {\n\tfile, err := ioutil.TempFile(\".\", \"smart_gateway_config_test\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\tfile.WriteString(content)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn file.Name(), nil\n}", "func generateAndRunFile(projectDir, fileName string, tmpl *template.Template) {\n\tprojectPack, err := build.ImportDir(path.Join(projectDir, \"config\"), 0)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Error while importing project path: %s\", err))\n\t}\n\n\ttmplData := struct {\n\t\tImports []string\n\t\tConfig string\n\t}{\n\t\tImports: projectPack.Imports,\n\t\tConfig: fmt.Sprintf(\"%#v\", viper.AllSettings()),\n\t}\n\tstartFileName := path.Join(projectDir, fileName)\n\tgenerate.CreateFileFromTemplate(startFileName, tmpl, tmplData)\n\tcmd := exec.Command(\"go\", \"run\", startFileName)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Run()\n}", "func TestGenerator_Generate(t *testing.T) {\n\timportmap := map[string]string{\n\t\t\"policy/v1beta1/value_type.proto\": \"istio.io/api/policy/v1beta1\",\n\t\t\"mixer/adapter/model/v1beta1/extensions.proto\": \"istio.io/api/mixer/adapter/model/v1beta1\",\n\t\t\"gogoproto/gogo.proto\": \"github.com/gogo/protobuf/gogoproto\",\n\t\t\"google/protobuf/duration.proto\": \"github.com/gogo/protobuf/types\",\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tfdsFiles map[string]string // FDS and their package import paths\n\t\twant string\n\t}{\n\t\t{\"AllTemplates\", map[string]string{\n\t\t\t\"testdata/check/template.descriptor\": \"istio.io/istio/mixer/template/list\",\n\t\t\t\"testdata/report2/template.descriptor\": \"istio.io/istio/mixer/template/metric\",\n\t\t\t\"testdata/quota/template.descriptor\": \"istio.io/istio/mixer/template/quota\",\n\t\t\t\"testdata/apa/template.descriptor\": \"istio.io/istio/mixer/template/apa\",\n\t\t\t\"testdata/report1/template.descriptor\": \"istio.io/istio/mixer/template/log\"},\n\t\t\t\"testdata/template.gen.go.golden\"},\n\t}\n\tfor _, v := range tests {\n\t\tt.Run(v.name, func(t *testing.T) {\n\t\t\ttestTmpDir := path.Join(os.TempDir(), \"bootstrapTemplateTest\")\n\t\t\t_ = os.MkdirAll(testTmpDir, os.ModeDir|os.ModePerm)\n\t\t\toutFile, err := os.Create(path.Join(testTmpDir, path.Base(v.want)))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tdefer func() {\n\t\t\t\tif !t.Failed() {\n\t\t\t\t\tif removeErr := os.RemoveAll(testTmpDir); removeErr != nil {\n\t\t\t\t\t\tt.Logf(\"Could not remove temporary folder %s: %v\", testTmpDir, removeErr)\n\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tt.Logf(\"Generated data is located at '%s'\", testTmpDir)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tg := Generator{OutFilePath: outFile.Name(), ImportMapping: importmap}\n\t\t\tif err := g.Generate(v.fdsFiles); err != nil {\n\t\t\t\tt.Fatalf(\"Generate(%s) produced an error: %v\", v.fdsFiles, err)\n\t\t\t}\n\n\t\t\tif same := fileCompare(outFile.Name(), v.want, t.Errorf); !same {\n\t\t\t\tt.Errorf(\"Files %v and %v were not the same.\", outFile.Name(), v.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestUsecaseInteractorFile(t *testing.T){\n\n\t// Build\n\tstatement, err := testInteractorGenerator.File(testEntity)\n\n\t// Return\n\tif err != nil {\n\t\tt.Errorf(`File() failed with error %v`, err)\n\t}\n\n\tf, err := os.Create(\"./testing/usecase/interactor/created/\" + testOutputUsecaseInteractorFileName)\n\tif err != nil {\n\t\tt.Errorf(`File() failed with error %v`, err)\n\t}\n\tbuf := &bytes.Buffer{}\n\terr = statement.Render(buf)\n\tif err != nil {\n\t\tt.Errorf(`File() failed with error %v`, err)\n\t}\n\t_, err = f.Write(buf.Bytes())\n\n\tif buf.String() != testOutputUsecaseInteractorFile {\n\t\tt.Errorf(`File() failed; want \"%s\", got \"%s\"`, testOutputUsecaseInteractorFile, buf.String())\n\t}\n\t\n}", "func generateFromTemplate(fullpath, templateName, actualTemplate string, data interface{}) {\n\tfullpath = filepath.FromSlash(fullpath)\n\tfile, err := os.Create(fullpath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: cannot create component file %s.\\n\"+\n\t\t\t\"The error is: %v\", fullpath, err)\n\t}\n\n\tt := template.Must(template.New(templateName).Parse(actualTemplate))\n\terr = t.Execute(file, data)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: cannot generate from template %s.\\n\"+\n\t\t\t\"The error is: %v\", fullpath, err)\n\t}\n\n\tlog.Successf(\"Created %v\\n\", fullpath)\n}", "func TestTemplatingAllVariables(t *testing.T) {\n\n\tsandbox, cleanup := cmdtest.TestSetupWithSandbox(t, true)\n\tdefer cleanup()\n\n\t// gets all the necessary data from a setup function\n\timageNamespace, imageRegistry, stackYaml, labels, err := setupStackPackageTests(sandbox.TestDataPath)\n\tif err != nil {\n\t\tt.Fatalf(\"Error during setup: %v\", err)\n\t}\n\n\t// creates templating.txt file where templating variables will appear\n\ttemplatingPath := filepath.Join(sandbox.TestDataPath, \"templating\", \"templating.txt\")\n\terr = os.MkdirAll(filepath.Dir(templatingPath), 0777)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating templating dir: %v\", err)\n\t}\n\tfile, err := os.Create(templatingPath)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating templating file: %v\", err)\n\t}\n\n\t// write some text to file\n\t_, err = file.WriteString(\"{{test}}, id: {{.stack.id}}, name: {{.stack.name}}, version: {{.stack.version}}, description: {{.stack.description}}, tag: {{.stack.tag}}, maintainers: {{.stack.maintainers}}, semver.major: {{.stack.semver.major}}, semver.minor: {{.stack.semver.minor}}, semver.patch: {{.stack.semver.patch}}, semver.majorminor: {{.stack.semver.majorminor}}, image.namespace: {{.stack.image.namespace}}, image.registry: {{.stack.image.registry}}, customvariable1: {{.stack.variable1}}, customvariable2: {{.stack.variable2}}\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error writing to file: %v\", err)\n\t}\n\n\t// save file changes\n\terr = file.Sync()\n\tif err != nil {\n\t\tt.Fatalf(\"Error saving file: %v\", err)\n\t}\n\n\t// create the template metadata\n\ttemplateMetadata, err := cmd.CreateTemplateMap(labels, stackYaml, imageNamespace, imageRegistry)\n\tif err != nil {\n\t\tt.Fatalf(\"Error creating template map: %v\", err)\n\t}\n\n\t// apply templating to stack\n\terr = cmd.ApplyTemplating(templatingPath, templateMetadata)\n\tif err != nil {\n\t\tt.Fatalf(\"Error applying template: %v\", err)\n\t}\n\n\t// read the whole file at once\n\tb, err := ioutil.ReadFile(templatingPath)\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading templating file: %v\", err)\n\t}\n\ts := string(b)\n\tt.Log(s)\n\tif !strings.Contains(s, \"{{test}}, id: starter, name: Starter Sample, version: 0.1.1, description: Runnable starter stack, copy to create a new stack, tag: appsody/starter:SNAPSHOT, maintainers: Henry Nash <henry.nash@uk.ibm.com>, semver.major: 0, semver.minor: 1, semver.patch: 1, semver.majorminor: 0.1, image.namespace: appsody, image.registry: dev.local, customvariable1: value1, customvariable2: value2\") {\n\t\tt.Fatal(\"Templating text did not match expected values\")\n\t}\n\n}", "func writeTemplate(templatePath string, writer io.Writer, ctx *Context) error {\n\ttmpl, err := template.New(filepath.Base(templatePath)).Funcs(template.FuncMap{\n\t\t\"test\": tplFuncTest,\n\t}).ParseFiles(templatePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to prepare template %s, error: %v\", templatePath, err)\n\t}\n\n\terr = tmpl.Execute(writer, &ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to generate template %s, error: %v\", templatePath, err)\n\t}\n\treturn nil\n}", "func TestInterfacePresenterFile(t *testing.T){\n\n\t// Build\n\tstatement, err := testPresenterGenerator.File(testEntity)\n\n\t// Return\n\tif err != nil {\n\t\tt.Errorf(`File() failed with error %v`, err)\n\t}\n\n\tf, err := os.Create(\"./testing/interface/presenter/created/\" + testOutputInterfacePresenterFileName)\n\tif err != nil {\n\t\tt.Errorf(`File() failed with error %v`, err)\n\t}\n\tbuf := &bytes.Buffer{}\n\terr = statement.Render(buf)\n\tif err != nil {\n\t\tt.Errorf(`File() failed with error %v`, err)\n\t}\n\t_, err = f.Write(buf.Bytes())\n\n\tif buf.String() != testOutputInterfacePresenterFile {\n\t\tt.Errorf(`File() failed; want \"%s\", got \"%s\"`, testOutputInterfacePresenterFile, buf.String())\n\t}\n\t\n}", "func (tg *Generate) WriteTmplToFile(filePath string, tmpl string, data interface{}) (err error) {\n\tfile, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tt := template.Must(template.New(\"toFile\").Funcs(template.FuncMap{\n\t\t\"ToLower\": func(str string) string {\n\t\t\treturn strings.ToLower(str)\n\t\t},\n\t}).Funcs(\n\t\ttemplate.FuncMap{\n\t\t\t\"Initial\": func(str string) string {\n\t\t\t\tif len(str) > 0 {\n\t\t\t\t\treturn string(strings.ToLower(str)[0])\n\t\t\t\t}\n\t\t\t\treturn \"x\"\n\t\t\t},\n\t\t}).Funcs(template.FuncMap{\n\t\t\"Counter\": func(str string) string {\n\t\t\tif s, err := strconv.Atoi(str); err == nil {\n\t\t\t\tcount := s + 1\n\t\t\t\treturn strconv.Itoa(count)\n\t\t\t}\n\t\t\treturn \"0\"\n\t\t}}).Funcs(template.FuncMap{\n\t\t\"GoType\": func(tpe string) string {\n\t\t\tif scler := tg.Scalars.GetScalar(tpe); scler != nil {\n\t\t\t\treturn scler.GoType\n\t\t\t}\n\t\t\treturn \"\"\n\t\t}}).Funcs(template.FuncMap{\n\t\t\"GrpcType\": func(tpe string) string {\n\t\t\tif scler := tg.Scalars.GetScalar(tpe); scler != nil {\n\t\t\t\treturn scler.GrpcType\n\t\t\t}\n\t\t\treturn \"\"\n\t\t}}).Funcs(template.FuncMap{\n\t\t\"GrpcArrayModel\": func(tpe string) string {\n\t\t\tss := strings.Split(tpe, \"[]\")\n\t\t\tif len(ss) > 1 {\n\t\t\t\treturn ss[1]\n\t\t\t}\n\t\t\treturn \"\"\n\t\t}}).Funcs(template.FuncMap{\n\t\t\"GoRegExFormat\": func(str string) string {\n\t\t\tif str == \"\" {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\tstr = strings.Trim(str, \" \")\n\t\t\t//strbuff := []byte(str)\n\t\t\tif len(str) > 2 {\n\t\t\t\t//\tstrbuff[0] = 96\n\t\t\t\t//\tstrbuff[len(strbuff)-1] = 96\n\t\t\t\tstroriginal := str\n\t\t\t\tstr = strings.Replace(str[1:len(str)-1], \"`\", `\"`+\"`\"+`\"`, -2)\n\t\t\t\treturn string(stroriginal[0]) + str + string(stroriginal[len(stroriginal)-1])\n\t\t\t}\n\t\t\treturn string(str)\n\t\t}}).Parse(tmpl))\n\terr = t.Execute(file, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func createFileFromTemplate(input string, output string) {\n\tt := loadTemplateFromFile(input)\n\n\tf, err := os.Create(output)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = t.Execute(f, packageName)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (t *templater) templateFile(workDir string, outDir string, file os.FileInfo, d map[string]interface{}) {\n\tif strings.Contains(file.Name(), \"yaml\") {\n\n\t\tfilePath := workDir + \"/\" + file.Name()\n\t\ttEx := templ.New(file.Name())\n\t\ttEx.Funcs(templateFuncs(workDir))\n\t\ttEx.ParseFiles(filePath)\n\t\tb := bytes.NewBuffer([]byte{})\n\t\terr := tEx.Execute(b, d)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Failed to execute template\")\n\t\t}\n\t\tnewF, err := os.Create(outDir + \"/\" + file.Name())\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Failed to create file\", \"file\", file.Name())\n\t\t\treturn\n\t\t}\n\t\tnewF.Write(b.Bytes())\n\t\tnewF.Close()\n\t}\n}", "func createTestFile(content string) string {\n\tdoc, err := ioutil.TempFile(\"\", \"testFile\")\n\tif err != nil {\n\t\tpanic(\"cannot create the temporary test file\")\n\t}\n\tif _, err := doc.Write([]byte(content)); err != nil {\n\t\tpanic(\"cannot write to the temporary test file\")\n\t}\n\treturn doc.Name()\n}", "func (cfg *Config) GenerateSampleConfig(dstDir string) error {\n\n\t// get a *Template\n\tat, err := prepareTemplate(\"/templates/config.json.gotmpl\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check the destination file-path and create if required\n\t_, err = os.Stat(dstDir)\n\tif err != nil {\n\t\tos.Mkdir(dstDir, 0755)\n\t}\n\n\tvar tfDir string\n\n\tfor i := 0; i < 2; i++ {\n\n\t\tswitch i {\n\t\tcase 0:\n\t\t\ttfDir = dstDir + \"/.dev.config.json\"\n\t\t\tcfg.Env = \"dev\"\n\t\tcase 1:\n\t\t\ttfDir = dstDir + \"/.prd.config.json\"\n\t\t\tcfg.Env = \"prod\"\n\t\tdefault:\n\n\t\t}\n\n\t\t// create the .xxx.config.json file\n\t\tf, err := os.Create(tfDir)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"GenerateSampleConfig: %v\\n\", err)\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\n\t\t// set permissions\n\t\terr = f.Chmod(0755)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"GenerateSampleConfig: %v\\n\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t// execute the config.json.gotmpl template using new file .xxx.config.json as a target\n\t\terr = at.Execute(f, cfg)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"GenerateSampleConfig: %v\\n\", err)\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"generated:\", tfDir)\n\t}\n\treturn nil\n}", "func generateFileFromTemplate(t template.Template, data interface{}) (string, error) {\n\t// generate temporary file\n\ttmpfile, err := ioutil.TempFile(\"\", \"lift-*\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer tmpfile.Close()\n\n\t// execute the template, saving the result in the tempfile\n\tif err := t.Execute(tmpfile, data); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"template\": t.Name(),\n\t\t\"file\": tmpfile.Name(),\n\t}).Debug(\"parsed template to file\")\n\n\t// return handle to the temp file\n\treturn tmpfile.Name(), nil\n}", "func TestGenerateConfigGoResource(t *testing.T) {\n\tconst (\n\t\toutFileName = \"configtemplate.go\"\n\t\tsourceFileName = \"testdata/config.yaml\"\n\t)\n\n\tif _, err := os.Stat(outFileName); !os.IsNotExist(err) {\n\t\tif b, _ := strconv.ParseBool(os.Getenv(\"GENERATE_CONFIG_TEMPLATE\")); !b {\n\t\t\tt.Skip(\"GENERATE_CONFIG_TEMPLATE is not set. Skipping template generation.\")\n\t\t\treturn\n\t\t}\n\t}\n\n\toutFile, err := os.Create(outFileName)\n\tassert.NoError(t, err)\n\n\tinFileData, err := ioutil.ReadFile(sourceFileName)\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write([]byte(\"package main\\n\"))\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write([]byte(\"// Generated content\\n\"))\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write([]byte(\"var templateConfigData = []byte(`\\n\"))\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write(inFileData)\n\tassert.NoError(t, err)\n\n\t_, err = outFile.Write([]byte(\"`)\\n\"))\n\tassert.NoError(t, err)\n}", "func testTemplate(w http.ResponseWriter, r *http.Request) {\n\ttestpage := Page{\n\t\tID: \"urn:cts:tests:test1.test1:1\",\n\t\tText: template.HTML(\"This is a testing of the template\")}\n\n\trenderTemplate(w, \"view\", testpage)\n}", "func setupTestFile(t *testing.T, name, content string) *os.File {\n\tdir, err := ioutil.TempDir(\"\", \"wt-go-sdk\")\n\tif err != nil {\n\t\tt.Errorf(\"openTestFile returned an error: %v\", err)\n\t}\n\n\tfile, err := os.OpenFile(path.Join(dir, name), os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)\n\tif err != nil {\n\t\tt.Errorf(\"openTestFile returned an error: %v\", err)\n\t}\n\n\tfmt.Fprint(file, content)\n\n\t// close and re-open the file to keep file.Stat() happy\n\tfile.Close()\n\tfile, err = os.Open(file.Name())\n\tif err != nil {\n\t\tt.Errorf(\"openTestFile returned an error: %v\", err)\n\t}\n\n\treturn file\n}", "func main() {\n\tl := []yamlFile{\n\t\t{\"configurations.yml\", false, cfgTemplate},\n\t\t{\"configurationsResponse.yml\", true, responseTemplate},\n\t}\n\tfor _, file := range l {\n\t\tf, err := os.Create(file.Name)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdoc := document{\n\t\t\tItems: userCfgItems(file.IsResponse),\n\t\t}\n\t\ttmpl, err := template.New(\"test\").Parse(file.TempName)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = tmpl.Execute(f, doc)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tf.Close()\n\t}\n}", "func createTestFile(t *testing.T, name string) string {\n\tfile, err := os.CreateTemp(testRepoPath, name)\n\trequire.NoError(t, err)\n\n\treturn file.Name()\n}", "func GenerateFile(filename, packagePath string, opts *GenerateOptions, values ...interface{}) error {\n\tif !strings.HasSuffix(filename, \".go\") {\n\t\tfilename += \".go\"\n\t}\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfieldTag := \"codec\"\n\tif opts != nil && opts.FieldTag != \"\" {\n\t\tfieldTag = opts.FieldTag\n\t}\n\tif err := generate(f, packagePath, fieldTag, values...); err != nil {\n\t\t_ = f.Close()\n\t\treturn err\n\t}\n\treturn f.Close()\n}", "func writeTestmain(out string, t *testFuncs) error {\n\tf, err := os.Create(out)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tif err := testmainTmpl.Execute(f, t); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func InitTomlFile(c *cli.Context) {\n\tname := \"spring-sample\"\n\tgroupId := \"com.sample\"\n\tartifactId := \"spring-sample\"\n\tspringVersion := \"2.1.2.RELEASE\"\n\tjavaVersion := \"1.8\"\n\n\tif c.String(\"n\") != \"name\" {\n\t\tname = \"\\\"\" + c.String(\"n\") + \"\\\"\"\n\t}\n\n\tif c.String(\"a\") != \"artifactId\" {\n\t\tartifactId = \"\\\"\" + c.String(\"a\") + \"\\\"\"\n\t}\n\n\tif c.String(\"g\") != \"\" {\n\t\tgroupId = \"\\\"\" + c.String(\"g\") + \"\\\"\"\n\t}\n\n\tif c.String(\"s\") != \"\" {\n\t\tspringVersion = \"\\\"\" + c.String(\"s\") + \"\\\"\"\n\t}\n\n\tif c.String(\"j\") != \"\" {\n\t\tjavaVersion = \"\\\"\" + c.String(\"j\") + \"\\\"\"\n\t}\n\n\t// generate file.\n\tfileName := \"spg.toml\"\n\twriteFile, err := os.OpenFile(fileName, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0777)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\twriter := bufio.NewWriter(writeFile)\n\tdefer writer.Flush()\n\n\tcontent := string(template.DEFAULT)\n\tcontent = strings.Replace(content, \"${name}\", name, -1)\n\tcontent = strings.Replace(content, \"${artifactId}\", artifactId, -1)\n\tcontent = strings.Replace(content, \"${groupId}\", groupId, -1)\n\tcontent = strings.Replace(content, \"${springVersion}\", springVersion, -1)\n\tcontent = strings.Replace(content, \"${javaVersion}\", javaVersion, -1)\n\twriter.WriteString(content)\n\n\tfmt.Printf(\"\\x1b[1;32mGenerating spg.toml file completed!\\x1b[0m\\n\")\n}", "func setupFileConfiguration(t *testing.T, configContent string) string {\n\tfile, err := ioutil.TempFile(\"\", \"ecs-test\")\n\trequire.NoError(t, err, \"creating temp file for configuration failed\")\n\n\t_, err = file.Write([]byte(configContent))\n\trequire.NoError(t, err, \"writing configuration to file failed\")\n\n\treturn file.Name()\n}", "func generateFile(fileName string, content string) {\n\tif content == \"\" {\n\t\tcontent = \"#empty\"\n\t}\n\tif _, err := os.Stat(fileName); err == nil {\n\t\tfmt.Printf(\"File exists\\n\")\n\t} else {\n\t\td := []byte(content)\n\t\tcheck(ioutil.WriteFile(fileName, d, 0644))\n\t}\n\n}", "func (suite *fileTestSuite) TestFileCreate() {\n\tfileName := suite.testPath + \"/small_write.txt\"\n\tsrcFile, err := os.OpenFile(fileName, os.O_CREATE, 0777)\n\tsuite.Equal(nil, err)\n\tsrcFile.Close()\n\n\tsuite.fileTestCleanup([]string{fileName})\n}", "func GenerateTestSupport(name string, modelNames, operationIDs []string, includeUI bool,includeTCK bool, opts GenOpts) error {\n\t\t// Load the spec\n\t_, specDoc, err := loadSpec(opts.Spec)\n\t\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\t\n\tmodels, mnc := make(map[string]spec.Schema), len(modelNames)\n\tfor k, v := range specDoc.Spec().Definitions {\n\t\tfor _, nm := range modelNames {\n\t\t\tif mnc == 0 || k == nm {\n\t\t\t\tmodels[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\toperations := make(map[string]spec.Operation)\n\tif len(modelNames) == 0 {\n\t\tfor _, k := range specDoc.OperationIDs() {\n\t\t\tif op, ok := specDoc.OperationForName(k); ok {\n\t\t\t\toperations[k] = *op\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor _, k := range specDoc.OperationIDs() {\n\t\t\tfor _, nm := range operationIDs {\n\t\t\t\tif k == nm {\n\t\t\t\t\tif op, ok := specDoc.OperationForName(k); ok {\n\t\t\t\t\t\toperations[k] = *op\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif name == \"\" {\n\t\tif specDoc.Spec().Info != nil && specDoc.Spec().Info.Title != \"\" {\n\t\t\tname = swag.ToGoName(specDoc.Spec().Info.Title)\n\t\t} else {\n\t\t\tname = \"swagger\"\n\t\t}\n\t}\n\n\tgenerator := testGenerator{\n\t\tName: name,\n\t\tSpecDoc: specDoc,\n\t\tModels: models,\n\t\tOperations: operations,\n\t\tTarget: opts.Target,\n\t\tDumpData: opts.DumpData,\n\t\tPackage: opts.APIPackage,\n\t\tAPIPackage: opts.APIPackage,\n\t\tModelsPackage: opts.ModelPackage,\n\t\tServerPackage: opts.ServerPackage,\n\t\tClientPackage: opts.ClientPackage,\n\t\tPrincipal: opts.Principal,\n\t\tIncludeUI: includeUI,\n\t\tIncludeTCK: includeTCK,\n\t}\n\n\treturn generator.GenerateTest()\n}", "func (j *tfvarsJSON) Generate(module *terraform.Module) error {\n\tcopy := orderedmap.New()\n\tcopy.SetEscapeHTML(false)\n\tfor _, i := range module.Inputs {\n\t\tcopy.Set(i.Name, i.Default)\n\t}\n\n\tbuffer := new(bytes.Buffer)\n\tencoder := jsonsdk.NewEncoder(buffer)\n\tencoder.SetIndent(\"\", \" \")\n\tencoder.SetEscapeHTML(false)\n\n\tif err := encoder.Encode(copy); err != nil {\n\t\treturn err\n\t}\n\n\tj.generator.funcs(withContent(strings.TrimSuffix(buffer.String(), \"\\n\")))\n\n\treturn nil\n}", "func (h testHelper) makeTestDir() (path string) {\n\tpath, err := ioutil.TempDir(\"\", \"TestDir\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\n\t// Now populate it with interesting files.\n\t// - zero byte file\n\th.writeFile(\"0_byte_file\", path, makeRisingIntsSlice(0))\n\t\n\t// - one byte file, zero value\n\th.writeFile(\"1_byte_file_0_value\", path,\n\t\tmakeConstantSlice(1, 0))\n\n\t// - one byte file, 128 value\n\th.writeFile(\"1_byte_file_128_value\", path,\n\t\tmakeConstantSlice(1, 128))\n\n\t// - ascending ints file, 10 bytes\n\th.writeFile(\"10_byte_file_rising_ints\", path,\n\t\tmakeRisingIntsSlice(10))\n\n\t// - ascending ints file, 100 bytes\n\th.writeFile(\"100_byte_file_rising_ints\", path,\n\t\tmakeRisingIntsSlice(100))\n\n\t// - all zeros, 100 byte file\n\th.writeFile(\"100_byte_file_0_value\", path,\n\t\tmakeConstantSlice(100, 0))\n\t\n\t// - all 255, 100 byte file\n\th.writeFile(\"100_byte_file_255_value\", path,\n\t\tmakeConstantSlice(100, 255))\n\n\t// - Hello World! file\n\th.writeFile(\"hello_world_file_plain\", path,\n\t\tmakeStringSlice(\"Hello World!\"))\n\n\t// - Hello World!\\n file\n\th.writeFile(\"hello_world_file_nl\", path,\n\t\tmakeStringSlice(\"Hello World!\\n\"))\n\n\t// - Hello World!\\r\\n file\n\th.writeFile(\"hello_world_file_crnl\", path,\n\t\tmakeStringSlice(\"Hello World!\\r\\n\"))\n\n\treturn path\n}", "func TestRegistryScaffoldFile(t *testing.T){\n\n\t// Build\n\tstatement, err := testRegistryGenerator.ScaffoldFile(testEntities)\n\n\t// Return\n\tif err != nil {\n\t\tt.Errorf(`ScaffoldFile() failed with error %v`, err)\n\t}\n\n\tf, err := os.Create(\"./testing/registry/created/\" + testOutputRegistryScaffoldFileName)\n\tif err != nil {\n\t\tt.Errorf(`ScaffoldFile() failed with error %v`, err)\n\t}\n\tbuf := &bytes.Buffer{}\n\terr = statement.Render(buf)\n\tif err != nil {\n\t\tt.Errorf(`ScaffoldFile() failed with error %v`, err)\n\t}\n\t_, err = f.Write(buf.Bytes())\n\n\tif buf.String() != testOutputRegistryScaffoldFile {\n\t\tt.Errorf(`ScaffoldFile() failed; want \"%s\", got \"%s\"`, testOutputRegistryScaffoldFile, buf.String())\n\t}\n\t\n}", "func testGenerateGraphite(t *testing.T) {\n\tRunTest(t, generateGraphiteTests, \"generateGraphite.txt\")\n}", "func jobGenerate(ctx context.Context, cfg *Config, cluster string, tmplFN string, output io.Writer, queues *Queues) (err kv.Error) {\n\n\t// Open the template file to be used\n\ttmplFile, errGo := os.Open(tmplFN)\n\tif errGo != nil {\n\t\treturn kv.Wrap(errGo).With(\"stack\", stack.Trace().TrimRuntime())\n\t}\n\n\t// Get a working directory to be used for generating values files\n\ttmpDir, errGo := ioutil.TempDir(\"\", \"\")\n\tif errGo != nil {\n\t\treturn kv.Wrap(errGo).With(\"stack\", stack.Trace().TrimRuntime())\n\t}\n\tdefer func() {\n\t\tos.RemoveAll(tmpDir)\n\t}()\n\n\tif logger.IsDebug() {\n\t\tnames := []string{}\n\t\tfor qName, _ := range *queues {\n\t\t\tnames = append(names, qName)\n\t\t}\n\t\tlogger.Debug(\"generating job templates\", \"queues\", strings.Join(names, \", \"), \"stack\", stack.Trace().TrimRuntime())\n\t}\n\n\tfor qName, qDetails := range *queues {\n\t\tjson, errGo := json.MarshalIndent(qDetails, \"\", \" \")\n\t\tif errGo != nil {\n\t\t\treturn kv.Wrap(errGo).With(\"stack\", stack.Trace().TrimRuntime())\n\t\t}\n\n\t\tqVarsFN := filepath.Join(tmpDir, qName+\".json\")\n\t\tif errGo = ioutil.WriteFile(qVarsFN, json, 0600); errGo != nil {\n\t\t\treturn kv.Wrap(errGo).With(\"stack\", stack.Trace().TrimRuntime())\n\t\t}\n\n\t\topts := stencil.TemplateOptions{\n\t\t\tIOFiles: []stencil.TemplateIOFiles{{\n\t\t\t\tIn: tmplFile,\n\t\t\t\tOut: output,\n\t\t\t}},\n\t\t\tValueFiles: []string{qVarsFN},\n\t\t\tOverrideValues: map[string]string{\n\t\t\t\t\"QueueName\": qName,\n\t\t\t},\n\t\t}\n\t\terr, warns := stencil.Template(opts)\n\t\tlogger.Warn(spew.Sdump(warns))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttmplFile.Seek(0, io.SeekStart) // The template is read multiple times so we rewindow between each\n\t\t// Write comments in the output to ensure kubernetes resource sections in the file are split\n\t\toutput.Write([]byte(\"\\n---\\n\"))\n\t}\n\treturn nil\n}", "func (c Codeowners) GenerateFile(ctx context.Context, root string) error {\n\tf, err := os.Create(c.PathOrDefault())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() { _ = f.Close() }()\n\tc.Debugf(\"codeowners path: %s\", c.PathOrDefault())\n\treturn c.Generate(ctx, root, f)\n}", "func genTemplate(w http.ResponseWriter, tmpt string, p *Page) {\n\tt, _ := template.ParseFiles(\"templates/\" + tmpt + \".html\")\n\tt.Execute(w, p)\n}", "func TestScaffoldUsecaseInteractorFile(t *testing.T){\n\n\t// Build\n\tstatement, err := testInteractorGenerator.ScaffoldFile(testEntity)\n\n\t// Return\n\tif err != nil {\n\t\tt.Errorf(`scaffoldUsecaseInteractorFile() failed with error %v`, err)\n\t}\n\n\tf, err := os.Create(\"./testing/usecase/interactor/created/\" + testOutputScaffoldUsecaseInteractorFileName)\n\tif err != nil {\n\t\tt.Errorf(`scaffoldUsecaseInteractorFile() failed with error %v`, err)\n\t}\n\tbuf := &bytes.Buffer{}\n\terr = statement.Render(buf)\n\tif err != nil {\n\t\tt.Errorf(`scaffoldUsecaseInteractorFile() failed with error %v`, err)\n\t}\n\t_, err = f.Write(buf.Bytes())\n\n\tif buf.String() != testOutputScaffoldUsecaseInteractorFile {\n\t\tt.Errorf(`scaffoldUsecaseInteractorFile() failed; want \"%s\", got \"%s\"`, testOutputScaffoldUsecaseInteractorFile, buf.String())\n\t}\n\t\n}", "func TestMainCreate(t *testing.T) {\n\trunEndToEnd(t, \"testdata/config.create.yaml\")\n}", "func TestScaffoldInterfacePresenterFile(t *testing.T){\n\n\t// Build\n\tstatement, err := testPresenterGenerator.ScaffoldFile(testEntity)\n\n\t// Return\n\tif err != nil {\n\t\tt.Errorf(`scaffoldInterfacePresenterFile() failed with error %v`, err)\n\t}\n\n\tf, err := os.Create(\"./testing/interface/presenter/created/\" + testOutputScaffoldInterfacePresenterFileName)\n\tif err != nil {\n\t\tt.Errorf(`scaffoldInterfacePresenterFile() failed with error %v`, err)\n\t}\n\tbuf := &bytes.Buffer{}\n\terr = statement.Render(buf)\n\tif err != nil {\n\t\tt.Errorf(`scaffoldInterfacePresenterFile() failed with error %v`, err)\n\t}\n\t_, err = f.Write(buf.Bytes())\n\n\tif buf.String() != testOutputScaffoldInterfacePresenterFile {\n\t\tt.Errorf(`scaffoldInterfacePresenterFile() failed; want \"%s\", got \"%s\"`, testOutputScaffoldInterfacePresenterFile, buf.String())\n\t}\n\t\n}", "func genFile() {\n\tout, _ := exec.Command(\"go\", \"version\").Output()\n\toutString := string(out[13:17])\n\n\ttestfile := goPack{\n\t\tGoVersion: outString}\n\n\terr := saveFile(testfile)\n\tcheck(err, \"Failed to generate gopack.yml\")\n\n\tfmt.Println(\"Created gopack.yml\")\n}", "func Generate() error {\n\tlogCategories, err := getDefinitions()\n\tif err != nil {\n\t\treturn err\n\t}\n\ttemp, err := getTemplates()\n\tif err != nil {\n\t\treturn err\n\t}\n\toutputPath := os.Getenv(\"GENERATOR_OUTPUT_PATH\")\n\tavailable := make([]string, 0)\n\tif len(outputPath) == 0 {\n\t\toutputPath = \"./templates\"\n\t}\n\tfor k, content := range logCategories {\n\t\tavailable = append(available, content.ResourceType)\n\t\tos.MkdirAll(fmt.Sprintf(\"%s/%s/\", outputPath, k), os.ModePerm)\n\t\tfr, err := os.Create(fmt.Sprintf(\"%s/%s/rule.json\", outputPath, k))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = temp.ExecuteTemplate(fr, ruleTemplate, content)\n\t\tfp, err := os.Create(fmt.Sprintf(\"%s/%s/parameters.json\", outputPath, k))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = temp.ExecuteTemplate(fp, paramTemplate, nil)\n\t}\n\tos.MkdirAll(outputPath, os.ModePerm)\n\tfa, err := os.Create(fmt.Sprintf(\"%s/available_resources.json\", outputPath))\n\tif err != nil {\n\t\treturn err\n\t}\n\t_ = temp.ExecuteTemplate(fa, generatedTemplate, available)\n\treturn nil\n}", "func generateTemplate() (string, string) {\n\t// load data from other modules\n\ttableName := shell.TableName\n\tschema := parser.ProcessedCommands\n\n\t// filenames to access data from\n\toutputFile := strings.ToLower(tableName) + \".insert.template.txt\"\n\n\tsql := fmt.Sprintf(\"INSERT INTO %s (\", tableName)\n\tfor counter, column := range schema {\n\t\tif column.AutoIncrement == false {\n\t\t\tsql += column.Name\n\t\t\tif counter != len(schema)-1 {\n\t\t\t\tsql += \",\"\n\t\t\t}\n\t\t}\n\t}\n\tsql += \") VALUES (__DATA_HERE__);\"\n\tui.ContextPrint(\"construction\", \"Building insertion template for : \"+shell.TableName)\n\ttemplateString = sql\n\treturn outputFile, sql\n}", "func WriteTemplateToFile(tpl string, config interface{}, writepath string, filemode os.FileMode) error {\n\tvar tplbuffer bytes.Buffer\n\tvar packageTemplate = template.Must(template.New(\"\").Parse(tpl))\n\terr := packageTemplate.Execute(&tplbuffer, config)\n\tif err != nil {\n\t\tlog.Warnf(\"Unable to translate template %q to string using the data %v\", tpl, config)\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(writepath, tplbuffer.Bytes(), filemode)\n\tif err != nil {\n\t\tlog.Warnf(\"Error writing file at %s : %s\", writepath, err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func fixture(filename string) string {\n\tcontents := MustAsset(filename)\n\n\ttmpfile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif _, err := tmpfile.Write(contents); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := tmpfile.Close(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn tmpfile.Name()\n}", "func CreateTemplate(oc *exutil.CLI, baseName string, ns string, configPath string, numObjects int, tuning *TuningSetType) {\n\t// Try to read the file\n\tcontent, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\tframework.Failf(\"Error reading file: %s\", err)\n\t}\n\n\t// ${IDENTIFER} is what we're replacing in the file\n\tregex, err := regexp.Compile(\"\\\\${IDENTIFIER}\")\n\tif err != nil {\n\t\tframework.Failf(\"Error compiling regex: %v\", err)\n\t}\n\n\tfor i := 0; i < numObjects; i++ {\n\t\tresult := regex.ReplaceAll(content, []byte(strconv.Itoa(i)))\n\n\t\ttmpfile, err := ioutil.TempFile(\"\", \"cl\")\n\t\tif err != nil {\n\t\t\te2e.Failf(\"Error creating new tempfile: %v\", err)\n\t\t}\n\t\tdefer os.Remove(tmpfile.Name())\n\n\t\tif _, err := tmpfile.Write(result); err != nil {\n\t\t\te2e.Failf(\"Error writing to tempfile: %v\", err)\n\t\t}\n\t\tif err := tmpfile.Close(); err != nil {\n\t\t\te2e.Failf(\"Error closing tempfile: %v\", err)\n\t\t}\n\n\t\terr = oc.Run(\"new-app\").Args(\"-f\", tmpfile.Name(), getNsCmdFlag(ns)).Execute()\n\t\te2e.Logf(\"%d/%d : Created template %s\", i+1, numObjects, baseName)\n\n\t\t// If there is a tuning set defined for this template\n\t\tif tuning != nil {\n\t\t\tif tuning.Templates.RateLimit.Delay != 0 {\n\t\t\t\te2e.Logf(\"Sleeping %d ms between template creation.\", tuning.Templates.RateLimit.Delay)\n\t\t\t\ttime.Sleep(time.Duration(tuning.Templates.RateLimit.Delay) * time.Millisecond)\n\t\t\t}\n\t\t\tif tuning.Templates.Stepping.StepSize != 0 && (i+1)%tuning.Templates.Stepping.StepSize == 0 {\n\t\t\t\te2e.Logf(\"We have created %d templates and are now sleeping for %d seconds\", i+1, tuning.Templates.Stepping.Pause)\n\t\t\t\ttime.Sleep(time.Duration(tuning.Templates.Stepping.Pause) * time.Second)\n\t\t\t}\n\t\t}\n\t}\n}", "func outputToFile(data interface{}, outputFilePath string, templateName string) error {\n\tfile, err := os.Create(outputFilePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tstatikFs, err := fs.New()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ----- コンテンツテンプレート\n\ttemplateFile, err := statikFs.Open(\"/\" + templateName)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttemplateBytes, err := ioutil.ReadAll(templateFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// --------------\n\n\tfuncs := template.FuncMap{\n\t\t\"add\": func(x, y int) int {\n\t\t\treturn x + y\n\t\t},\n\t}\n\ttpl := template.Must(template.New(templateName).Funcs(funcs).Parse(string(templateBytes)))\n\n\t// HTML テンプレートを指定された場合\n\tif strings.Index(templateName, \".html\") > -1 {\n\n\t\t// ----- ヘッダーテンプレート\n\t\theaderTemplateFile, err := statikFs.Open(\"/header.tmpl.html\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\theaderTemplateBytes, err := ioutil.ReadAll(headerTemplateFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// --------------\n\n\t\t// ----- 共通テンプレート\n\t\tinfoTemplateFile, err := statikFs.Open(\"/information.tmpl.html\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tinfoTemplateBytes, err := ioutil.ReadAll(infoTemplateFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// --------------\n\t\ttplInformation := template.Must(template.New(\"information\").Funcs(funcs).Parse(string(infoTemplateBytes)))\n\t\ttplHeader := template.Must(template.New(\"information\").Funcs(funcs).Parse(string(headerTemplateBytes)))\n\t\ttpl.AddParseTree(\"information\", tplInformation.Tree)\n\t\ttpl.AddParseTree(\"header\", tplHeader.Tree)\n\t}\n\n\tinfo := map[string]interface{}{\n\t\t\"createdDate\": time.Now().Format(\"2006-01-02 15:04:05\"),\n\t}\n\td := map[string]interface{}{\n\t\t\"Data\": data,\n\t\t\"Info\": info,\n\t}\n\n\tif err = tpl.ExecuteTemplate(file, templateName, d); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func genFile(filePath, fileText string) error {\n\tfw, err := os.OpenFile(filePath, syscall.O_CREAT, 0644)\n\tdefer fw.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = fw.Write([]byte(fileText))\n\treturn err\n}", "func (m mockServicesGenerator) GenerateFileContent() {\n\tif len(m.file.Services) == 0 {\n\t\treturn\n\t}\n\tfor _, service := range m.file.Services {\n\t\tm.genService(service)\n\t}\n}", "func GenerateCppRandom(conf config.Conf, num int, outdir string) {\n\n\t// Get other files in output directory\n\tpaths := utils.FindDiff(utils.ListDir(conf.Root, false, true), conf.Files)\n\n\t// TODO if we generate multiple, can eventually use co-routine or channels?\n\tfor i := 0; i < num; i++ {\n\n\t\t// Generate functions with params to render (eventually can add more types)\n\t\tfuncs := map[string]Function{}\n\n\t\tfor name, entry := range conf.Renders {\n\t\t\tswitch entry.Type {\n\t\t\tcase \"function\":\n\t\t\t\tfuncs[name] = GenerateFunction(name, entry)\n\t\t\t}\n\t\t}\n\n\t\t// If we don't have an output directory, make it (start at 1, not 0)\n\t\toutsubdir := filepath.Join(outdir, fmt.Sprintf(\"%x\", i+1))\n\t\tif outdir != \"\" {\n\t\t\tos.MkdirAll(outsubdir, os.ModePerm)\n\t\t}\n\n\t\t// For each file, read it in...\n\t\tfor i, templateName := range conf.Files {\n\n\t\t\tfile := filepath.Join(conf.Root, templateName)\n\n\t\t\t// Create a new template from the file content\n\t\t\tt := template.Must(template.New(templateName).Funcs(templateHelpers).ParseFiles(file))\n\n\t\t\t// And render the functions into it\n\t\t\tif outdir != \"\" {\n\t\t\t\tfmt.Printf(\"// Writing [%x:%s]\\n\", i, templateName)\n\t\t\t\tWriteTemplate(filepath.Join(outsubdir, templateName), t, &funcs)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"// Printing [%x:%s]\\n\", i, templateName)\n\t\t\t\tt.Execute(os.Stdout, funcs)\n\t\t\t\t// To prevent from printint to the screen, t.Execute(ioutil.Discard, funcs)\n\t\t\t}\n\t\t}\n\n\t\t// Copy the remaining files there\n\t\tif outdir != \"\" {\n\t\t\tfor _, path := range paths {\n\t\t\t\tutils.CopyFile(filepath.Join(conf.Root, path), filepath.Join(outsubdir, path))\n\t\t\t}\n\n\t\t\t// Save json for functions\n\t\t\toutput, _ := json.MarshalIndent(funcs, \"\", \" \")\n\t\t\t_ = ioutil.WriteFile(filepath.Join(outsubdir, \"codegen.json\"), output, 0644)\n\n\t\t\t// If not writing to file, only allow printing one\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n}", "func (g *Generator) Generate() ([]byte, error) {\n\tm := g.PHPModels()\n\tfuncMap := template.FuncMap{\n\t\t\"now\": time.Now,\n\t}\n\ttmpl, err := template.New(\"test\").Funcs(funcMap).Parse(phpTpl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// compile template\n\tvar buf bytes.Buffer\n\tif err := tmpl.Execute(&buf, m); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func generateGoSampleFile(schema map[string]interface{}, config Config) {\r\n var obj map[string]interface{}\r\n var samples = make(map[string]interface{})\r\n var outString = \"package main\\n\\nvar samples = `\\n\"\r\n\r\n var filename = config.Samples.GoSampleFilename\r\n var elementNames = config.Samples.GoSampleElements\r\n\r\n fmt.Printf(\"Generate Go SAMPLE file %s for: \\n %s\\n\", filename, elementNames)\r\n\r\n for i := range elementNames {\r\n elementName := elementNames[i]\r\n if elementName == \"schema\" {\r\n // sample of the entire schema, can it even work?\r\n obj = schema\r\n } else {\r\n // use the schema subset\r\n obj = getObject(schema, elementName)\r\n if obj == nil {\r\n fmt.Printf(\"** WARN ** %s returned nil from getObject\\n\", elementName)\r\n return\r\n }\r\n }\r\n samples[elementName] = sampleType(obj, elementName) \r\n }\r\n samplesOut, err := json.MarshalIndent(&samples, \"\", \" \")\r\n if err != nil {\r\n fmt.Println(\"** ERR ** cannot marshal sample file output for writing\")\r\n return\r\n }\r\n outString += string(samplesOut) + \"`\"\r\n ioutil.WriteFile(filename, []byte(outString), 0644)\r\n}", "func (s *Service) Generate(dir, filename string) error {\n\terr := makeDirIfNotExists(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(path.Join(dir, filename))\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.generator.Execute(f, s.tmpl)\n}", "func createFile(t *testing.T, content string) string {\n\ttmpfile, err := ioutil.TempFile(\"\", \"example\")\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error creating temporary file: %s\", err)\n\t}\n\n\t_, err = tmpfile.Write([]byte(content))\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error writing to temporary file: %s\", err)\n\t}\n\n\terr = tmpfile.Close()\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error closing temporary file: %s\", err)\n\t}\n\n\treturn tmpfile.Name()\n}", "func createNewTemplate(name string, namespace string, expose bool, clusterDomain string, kube kube.KymaKube) error {\n\tparams := TemplateParameters{\n\t\tName: name,\n\t\tExpose: expose,\n\t\tNamespace: namespace,\n\t\tClusterDomain: clusterDomain,\n\t}\n\n\tcurrentDir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check if folder exists\n\toutputPath := filepath.Join(currentDir, name)\n\terr = dev.EnsureDir(outputPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// iterate through files of template and create files based on parameters\n\tvar files []string\n\terr = filepath.Walk(templateFolder, func(path string, info os.FileInfo, err error) error {\n\t\tfiles = append(files, path)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not generate lambda\")\n\t}\n\tfor _, file := range files {\n\t\tif file != templateFolder {\n\t\t\tdev.ProcessTemplateFile(outputPath, templateFolder, file, params)\n\t\t}\n\t}\n\treturn nil\n}", "func createProfileFile(templateToFile string) error {\r\n\ttempPath := os.Getenv(\"tmp\")\r\n\t// create and open file\r\n\tprofileFilePath := tempPath + \"\\\\\" + \"template-out.xml\"\r\n\tprofileFile, err := os.Create(profileFilePath)\r\n\tif err != nil {\r\n\t\tos.Remove(\"profile.xml\")\r\n\t\treturn err\r\n\t}\r\n\t// close file\r\n\tdefer profileFile.Close()\r\n\t// write the template into the new file\r\n\t_, err = io.Copy(profileFile, strings.NewReader(templateToFile))\r\n\tif err != nil {\r\n\t\tos.Remove(\"profile.xml\")\r\n\t\tos.Remove(profileFilePath)\r\n\t\treturn err\r\n\t}\r\n\r\n\tos.Remove(\"profile.xml\")\r\n\treturn nil\r\n}", "func CreateFile(c *gin.Context) {\n\t// Function to generate random string to write into the file\n\ttextToWrite := GenerateRandomString()\n\tlog.Println(textToWrite)\n\twriteErr := ioutil.WriteFile(\"/serverdata/randomFile.txt\", []byte(textToWrite), 0644)\n\tif writeErr != nil {\n\t\tlog.Print(\"Error while writing data to file\", writeErr)\n\t\tc.JSON(417, gin.H{\"message\": \"Error while writing to file\"})\n\t}\n\t// reading file passing the path after writing the random text\n\tfiledata, readErr := ioutil.ReadFile(\"/serverdata/randomFile.txt\")\n\tif readErr != nil {\n\t\tlog.Fatal(\"Error while reading file\")\n\t\tc.JSON(417, gin.H{\"message\": \"Error while reading file\"})\n\t}\n\t// Checksum generation of file\n\tchecksum := GenerateCheckSum(filedata)\n\tResponseData.CheckSum = checksum\n\tResponseData.FileData = filedata\n\tc.JSON(200, ResponseData)\n}", "func InstallGenfile(mode string, currentDir string, subProcessDir string, logName string) {\n genfile_file, err := os.Create(currentDir+\"/data/output\"+subProcessDir+\"/sys/0x0000000000base/genfile/tasks/main.yml\") \n CheckErr(err,currentDir,logName,mode)\n defer genfile_file.Close() \n genfile_file.WriteString(\"- name: 1.Create {{software_home}} directory\\n file:\\n path: \\\"{{software_home}}\\\"\\n state: directory\\n- file:\\n path: \\\"/tmp/.kubeinstalltemp/data\"+subProcessDir+\"/pkg/\\\"\\n state: directory\\n- name: 2.Distributing deployment files to target host, please wait...\\n copy:\\n src: \\\"\"+currentDir+\"/pkg/{{ostype}}\\\"\\n dest: \\\"/tmp/.kubeinstalltemp/data\"+subProcessDir+\"/pkg/\\\"\\n- copy:\\n src: \\\"\"+currentDir+\"/sys\\\"\\n dest: \\\"/tmp/.kubeinstalltemp/data\"+subProcessDir+\"/\\\"\\n\")\n\n}", "func getOutputPath(t string) (*os.File, error) {\n\n\t_ = os.Mkdir(config.Vars.CucumberDir, 0755)\n\n\t//filename is test name (supplied) + .json\n\tfn := t + \".json\"\n\treturn os.Create(filepath.Join(config.Vars.CucumberDir, fn))\n}", "func writeTemplate(path string, lines []string) {\n delErr := os.Remove(path)\n checkErr(delErr)\n f, crtErr := os.Create(path)\n checkErr(crtErr)\n\n for _, line := range lines {\n fmt.Fprintln(f, line)\n }\n}", "func generateFromString(fullpath, src string) {\n\tfullpath = filepath.FromSlash(fullpath)\n\tfile, err := os.Create(fullpath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: cannot generate file from string %s.\\n\"+\n\t\t\t\"The error is: %v\", fullpath, err)\n\t}\n\n\t_, err = file.WriteString(src)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: cannot write from string %s.\\n\"+\n\t\t\t\"The error is: %v\", fullpath, err)\n\t}\n\n\tlog.Successf(\"Created %v\\n\", fullpath)\n}", "func generateAction(c *cli.Context) error {\n\tif c.NArg() != 1 {\n\t\treturn cli.NewExitError(fmt.Sprintf(\"%v %v requires exactly 1 argument\", c.App.Name, c.Command.Name), 1)\n\t}\n\n\tfilename, err := builder.CreateSkeletonFile(c.Args().First())\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\n\tfmt.Printf(\"successfully created template file %v\\n\", filename)\n\n\treturn nil\n}", "func main(){\n\tcfg := setup()\n\n\t// Just output the template.\n\ttemplate, _ := ioutil.ReadAll(cfg.Template)\n\tfmt.Println(string(template))\n}", "func (test *targetTest) generateCode(t *testing.T) {\n\tstdout := test.runOpts.Stdout\n\tif stdout == nil {\n\t\tstdout = os.Stdout\n\t}\n\tfmt.Fprintf(stdout, \"running `terraform init`...\\n\")\n\n\t// Run \"terraform init\".\n\tcmd := exec.Command(\"terraform\", \"init\")\n\tcmd.Dir = test.runOpts.Dir\n\tif out, cmdErr := cmd.CombinedOutput(); cmdErr != nil {\n\t\tt.Fatalf(\"'terraform init' failed (%v): %v\", cmdErr, string(out))\n\t}\n\n\tfmt.Fprintf(stdout, \"running `tf2pulumi`...\\n\")\n\n\t// Generate an index.ts file using `tf2pulumi`.\n\tindexTS, err := os.Create(filepath.Join(test.runOpts.Dir, test.targetFile()))\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create index.ts: %v\", err)\n\t}\n\tdefer contract.IgnoreClose(indexTS)\n\n\tvar args []string\n\tif test.convertOpts.FilterName != \"\" {\n\t\targs = append(args, \"--filter-resource-names=\"+test.convertOpts.FilterName)\n\t}\n\targs = append(args, \"--target-language=\"+test.language)\n\targs = append(args, \"--record-locations\")\n\n\tvar stderr bytes.Buffer\n\tcmd = exec.Command(\"tf2pulumi\", args...)\n\tcmd.Dir = test.runOpts.Dir\n\tcmd.Stdout, cmd.Stderr = indexTS, &stderr\n\tif err = cmd.Run(); err != nil {\n\t\tt.Fatalf(\"failed to generate Pulumi program (%v):\\n%v\", err, stderr.String())\n\t}\n}", "func Template(tempName string, templatePath string, replacings ...Replacement) *os.File {\n\treplacedFile, err := ioutil.TempFile(\"/tmp\", tempName+\"-*.yaml\")\n\tExpect(err).ToNot(HaveOccurred())\n\n\ttemplateContent, err := ioutil.ReadFile(templatePath)\n\tExpect(err).ToNot(HaveOccurred())\n\n\treplacedStr := \"\"\n\tfor _, rep := range replacings {\n\t\tcontent := \"\"\n\t\tif replacedStr == \"\" {\n\t\t\tcontent = string(templateContent)\n\t\t} else {\n\t\t\tcontent = replacedStr\n\t\t}\n\t\treplacedStr = strings.ReplaceAll(content, rep.Old, rep.New)\n\t}\n\n\terr = ioutil.WriteFile(replacedFile.Name(), []byte(replacedStr), 0644)\n\tExpect(err).ToNot(HaveOccurred())\n\n\treturn replacedFile\n}", "func setupTestFiles(baseLoc vfs.Location) {\n\n\t// setup \"test_files\" dir\n\tcreateDir(baseLoc, \"test_files\")\n\n\t// setup \"test_files/test.txt\"\n\twriteStringFile(baseLoc, \"test_files/empty.txt\", ``)\n\n\t// setup \"test_files/test.txt\"\n\twriteStringFile(baseLoc, \"test_files/prefix-file.txt\", `hello, Dave`)\n\n\t// setup \"test_files/test.txt\"\n\twriteStringFile(baseLoc, \"test_files/test.txt\", `hello world`)\n\n\t// setup \"test_files/subdir\" dir\n\tcreateDir(baseLoc, \"test_files/subdir\")\n\n\t// setup \"test_files/subdir/test.txt\"\n\twriteStringFile(baseLoc, \"test_files/subdir/test.txt\", `hello world too`)\n}", "func (s *Static) GenerateStaticTemplates() (fNames []string, err error) {\n\n\t// begin of new part\n\ttmlFiles, err := glob(s.SrcDir, \"*\"+\".gotmpl\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// end of new part\n\n\tfor _, f := range tmlFiles {\n\n\t\t// start of new part\n\t\tfi, err := pkger.Stat(f)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Stat: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttf, err := pkger.Open(f)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Open: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer tf.Close()\n\n\t\t// read the template source from pkger\n\t\tbuf := make([]byte, fi.Size())\n\t\t_, err = tf.Read(buf)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Unable to read template: %s %v\\n\", f, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tst := template.Must(template.New(\"Static template\").Parse(string(buf)))\n\t\tif st == nil {\n\t\t\tlog.Printf(\"Parse error: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\t// end of new part\n\n\t\t// create the file-path if required\n\t\t_, err = os.Stat(s.DstDir)\n\t\tif err != nil {\n\t\t\tos.Mkdir(s.DstDir, 0755)\n\t\t}\n\n\t\t// create the static source file\n\t\tfileName := filepath.Base(f)\n\t\tfileName = strings.TrimSuffix(fileName, \"tmpl\")\n\t\tf, err := os.Create(s.DstDir + \"/\" + fileName)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"generateStaticTemplates: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer f.Close()\n\n\t\t// set permissions\n\t\terr = f.Chmod(0755)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"generateStaticTemplates: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// execute the template using the new controller file as a target\n\t\terr = st.Execute(f, s)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"generateStaticTemplates: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tfName := s.DstDir + \"/\" + fileName\n\t\tfNames = append(fNames, fName)\n\t\tlog.Println(\"generated:\", fName)\n\t\tf.Close()\n\t}\n\treturn fNames, nil\n}", "func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {\n\tif !file.Generate {\n\t\treturn nil\n\t}\n\tif len(file.Services) == 0 {\n\t\treturn nil\n\t}\n\t// fmt.Println(\"FILENAME \", file.GeneratedFilenamePrefix)\n\tfilename := file.GeneratedFilenamePrefix + \".mock.pb.go\"\n\tg := gen.NewGeneratedFile(filename, file.GoImportPath)\n\tmockGenerator := mockServicesGenerator{\n\t\tgen: gen,\n\t\tfile: file,\n\t\tg: g,\n\t}\n\tmockGenerator.genHeader(string(file.GoPackageName))\n\tmockGenerator.GenerateFileContent()\n\treturn g\n}", "func TestTemplate(t *testing.T) {\n\trc, _ := vcrTestClient(t, t.Name())\n\tctx := testCtx()\n\tlog := zerolog.Ctx(ctx)\n\n\torg, err := rc.GetOrganization(ctx)\n\trequire.NoError(t, err)\n\n\tlog.Debug().Str(\"org\", org.GetDisplayName())\n}", "func Generate(dir string, varConfName string) {\n\tt, dirPath := gatherVars(dir, varConfName)\n\toutput(t, dirPath)\n}", "func ZDTestTemplate(t *testing.T, F func(t2 *testing.T, e *ZeroDowntimeEnv), name string) {\n\n\tenv := SetupZD()\n\tenv.Wg.Add(2)\n\tt.Run(\"Rolling Upgrade\", func(t1 *testing.T) {\n\t\tt1.Parallel()\n\t\tRollingUpgrade(t1, env)\n\t})\n\tt.Run(\"API\", func(t1 *testing.T) {\n\t\tt1.Parallel()\n\t\tAPIs(t1, env)\n\t\tenv.Wg.Done()\n\t})\n\tt.Run(name, func(t1 *testing.T) {\n\t\tt1.Parallel()\n\t\tF(t1, env)\n\t\t// The test summary should be printed after the tests have finished and before the test suite returns\n\t\t// to avoid failure due to test context expired\n\t\tt.Run(\"Summary\", func(t *testing.T) {\n\t\t\tt.Log(\"Test results for \", name)\n\t\t\tPrintSequencesResults(env)\n\t\t\tPrintAPIresults(env)\n\t\t\tenv.Wg.Done()\n\t\t})\n\t})\n\n}", "func TestGen(t *testing.T) {\n\tgenutils.Asset = Asset\n\tgenutils.SetValues(map[string]interface{}{\n\t\t\"RootPath\": \"./\",\n\t})\n\torm.Gen(\"config.yaml\",\"init\",\"\")\n}", "func createFile(words []string) error {\n\tf, err := os.Create(\"ipsum/dictionary.go\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tfor _, v := range []string{\n\t\t\"package ipsum\\n\",\n\t\t\"\\n\",\n\t\t\"// Code generated by gen.go. DO NOT EDIT.\\n\",\n\t\tfmt.Sprintf(\"// Word count: %d\\n\", len(words)),\n\t\tfmt.Sprintf(\"// Timestamp: %s\\n\", time.Now().UTC()),\n\t\t\"\\n\",\n\t\t\"var dictionary = []string{\\n\",\n\t} {\n\t\t_, err := f.WriteString(v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, v := range words {\n\t\t_, err := f.WriteString(fmt.Sprintf(\"\\t%q,\\n\", v))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t_, err = f.WriteString(\"}\\n\")\n\treturn err\n}", "func setUpFile(t *testing.T, data string, mode os.FileMode) (td, fn string) {\n\ttd = testutil.TempDir(t)\n\tfn = filepath.Join(td, \"src.txt\")\n\tif err := ioutil.WriteFile(fn, []byte(data), mode); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.Chmod(fn, mode); err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn td, fn\n}", "func TemplateFile(src string, outBuf *bytes.Buffer, vars map[string]interface{}) error {\n\n\t// verify that the input template exists\n\tif _, err := os.Stat(src); err != nil {\n\t\treturn errors.Wrapf(err, \"Source template '%s' doesn't exist\", src)\n\t}\n\n\tsrcTemplate, err := ioutil.ReadFile(src)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Error reading source template file %s\", src)\n\t}\n\n\treturn TemplateString(string(srcTemplate[:]), outBuf, vars)\n}", "func genSource(dir, filename, templateSource string, args map[string]interface{}) {\n\tsourceCode := revel.ExecuteTemplate(\n\t\ttemplate.Must(template.New(\"\").Parse(templateSource)),\n\t\targs)\n\n\t// Create a fresh dir.\n\ttmpPath := path.Join(revel.AppPath, dir)\n\terr := os.RemoveAll(tmpPath)\n\tif err != nil {\n\t\trevel.ERROR.Println(\"Failed to remove dir:\", err)\n\t}\n\terr = os.Mkdir(tmpPath, 0777)\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to make tmp directory: %v\", err)\n\t}\n\n\t// Create the file\n\tfile, err := os.Create(path.Join(tmpPath, filename))\n\tdefer file.Close()\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to create file: %v\", err)\n\t}\n\t_, err = file.WriteString(sourceCode)\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to write to file: %v\", err)\n\t}\n}", "func (t *Twinner) Generate() error {\n\n\tif _, err := os.Stat(t.outputFolder); os.IsNotExist(err) {\n\t\tos.Mkdir(t.outputFolder, 0755)\n\t}\n\n\tc := NewTemplateModel()\n\tc.TwinName = strings.Title(t.Twin.Result.Tags[0])\n\tc.LCaseTwinName = strings.ToLower(t.Twin.Result.Tags[0])\n\tc.Visibility = t.Twin.Twin.Visibility\n\tc.Feeds = []FeedTmpl{}\n\tc.Comments = []CommentsTmpl{}\n\tc.Properties = []PropertiesTmpl{}\n\tc.Labels = []LabelsTmpl{}\n\tc.Tags = []string{}\n\tfor _, v := range t.Twin.Result.Tags {\n\t\tc.Tags = append(c.Tags, v)\n\t}\n\tfor _, v := range t.Twin.Result.Labels {\n\t\tc.Labels = append(c.Labels, LabelsTmpl{\n\t\t\tValue: v.Value,\n\t\t\tLang: v.Lang,\n\t\t})\n\t}\n\tfor _, v := range t.Twin.Result.Comments {\n\t\tc.Comments = append(c.Comments, CommentsTmpl{\n\t\t\tValue: v.Value,\n\t\t\tLang: v.Lang,\n\t\t})\n\t}\n\tfor _, v := range t.Twin.Result.Properties {\n\t\tc.Properties = append(c.Properties, PropertiesTmpl{\n\t\t\tValue: v.StringLiteralValue.Value,\n\t\t\tKey: v.Key,\n\t\t})\n\t}\n\tfor _, v := range t.Twin.Result.Feeds {\n\n\t\tfeed := t.GetFeedByName(v.FeedId.Value)\n\t\tfv := []FeedValuesTmpl{}\n\t\tfc := []FeedCommentsTmpl{}\n\t\tfl := []FeedLabelsTmpl{}\n\t\tft := []string{}\n\t\tfor _, v := range feed.Result.Values {\n\t\t\ti := FeedValuesTmpl{\n\t\t\t\tDataType: v.DataType,\n\t\t\t\tComment: v.Comment,\n\t\t\t\tUnit: v.Unit,\n\t\t\t\tLabel: v.Label,\n\t\t\t}\n\t\t\t// workout types here\n\t\t\ti.GoDataType = v.DataType\n\t\t\tswitch v.DataType {\n\t\t\tcase \"decimal\":\n\t\t\t\ti.GoDataType = \"float32\"\n\t\t\tcase \"float\":\n\t\t\t\ti.GoDataType = \"float32\"\n\t\t\tcase \"int\":\n\t\t\t\ti.GoDataType = \"int\"\n\t\t\tcase \"integer\":\n\t\t\t\ti.GoDataType = \"int\"\n\t\t\tcase \"string\":\n\t\t\t\ti.GoDataType = \"string\"\n\t\t\tcase \"boolean\":\n\t\t\t\ti.GoDataType = \"bool\"\n\t\t\tdefault:\n\t\t\t\ti.GoDataType = fmt.Sprintf(\"not found datatype %s \", v.DataType)\n\t\t\t}\n\t\t\ti.LCaseLabel = strings.ToLower(v.Label)\n\t\t\tfv = append(fv, i)\n\t\t}\n\t\tfor _, v := range feed.Result.Comments {\n\t\t\tfc = append(fc, FeedCommentsTmpl{\n\t\t\t\tLang: v.Lang,\n\t\t\t\tValue: v.Value,\n\t\t\t})\n\t\t}\n\t\tfor _, v := range feed.Result.Labels {\n\t\t\tfl = append(fl, FeedLabelsTmpl{\n\t\t\t\tLang: v.Lang,\n\t\t\t\tValue: v.Value,\n\t\t\t})\n\t\t}\n\t\tfor _, v := range feed.Result.Tags {\n\t\t\tft = append(ft, v)\n\t\t}\n\t\tc.Feeds = append(c.Feeds, FeedTmpl{\n\t\t\tFeedName: strings.Title(v.FeedId.Value),\n\t\t\tFeedID: v.FeedId.Value,\n\t\t\tFeedStructName: fmt.Sprintf(\"Feed%s\", strings.Title(v.FeedId.Value)),\n\t\t\tFeedStructNameLCase: fmt.Sprintf(\"Feed%s\", strings.ToLower(v.FeedId.Value)),\n\t\t\tFeedValues: fv,\n\t\t\tFeedTags: ft,\n\t\t\tFeedComments: fc,\n\t\t\tFeedLabels: fl,\n\t\t})\n\t}\n\n\terr := t.render(\"./templates/library.go.tmpl\", \"library\", fmt.Sprintf(\"%s/library.go\", t.outputFolder), c)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = t.render(\"./templates/main.go.tmpl\", \"main\", fmt.Sprintf(\"%s/main.go\", t.outputFolder), c)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = t.render(\"./templates/go.mod.tmpl\", \"mod\", fmt.Sprintf(\"%s/go.mod\", t.outputFolder), c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func genSource(dir, filename, templateSource string, args map[string]interface{}) {\n\tsourceCode := revel.ExecuteTemplate(\n\t\ttemplate.Must(template.New(\"\").Parse(templateSource)),\n\t\targs)\n\n\t// Create a fresh dir.\n\t// tmpPath := path.Join(revel.AppPath, dir)\n\n\t// Create the file\n\tfile, err := os.Create(path.Join(dir, filename))\n\tdefer file.Close()\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to create file: %v\", err)\n\t}\n\t_, err = file.WriteString(sourceCode)\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to write to file: %v\", err)\n\t}\n}", "func Generate(fileSet *token.FileSet, pkgs map[string]*ast.Package, pkgPath string, typeName string) *ast.File {\n\tpkg, spec, zeroValue, values, valueStrings, _ := findDefinitions(fileSet, pkgs, typeName)\n\treturn generateFile(pkg, spec, zeroValue, values, valueStrings)\n}", "func setUp() {\n\tdefaultData := map[string]string{\n\t\t\"key1\": \"value1\",\n\t\t\"key2\": \"value2\",\n\t\t\"key3\": \"value3\",\n\t}\n\tjsonData, _ := json.Marshal(defaultData)\n\terr := ioutil.WriteFile(JsonTestPath, jsonData, 0644)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func GenerateTemplate(params cloudformation.GenerateParams) {\n\toutput, _ := GenerateYamlTemplate(params)\n\tprepareOutputDir(params.Directory)\n\tif params.WriteParams {\n\t\twriteParamMap(params.Filename, params.Directory, params.ParamMap)\n\t}\n\twriteOutput(params.Filename, params.Directory, output)\n}", "func RenderTemplate(tmpfile string, pairs map[string]interface{}) (string, error) {\n\n\tfile, err := os.Open(tmpfile)\n\tif err != nil {\n\t\tLogWarning.Println(err)\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\t//var srcContent string\n\tvar srcContent bytes.Buffer\n\tfor scanner.Scan() {\n\t\tt := fmt.Sprintln(scanner.Text())\n\t\tif strings.Index(t, \"<%file:\") > -1 {\n\t\t\tLogDebug.Println(\"Including file external file\")\n\t\t\tif strings.Index(t, \"%>\") > -1 {\n\t\t\t\tre := regexp.MustCompile(\"\\\\<\\\\%file:(.*?)\\\\%\\\\>\")\n\t\t\t\tmatch := re.FindStringSubmatch(t)\n\t\t\t\tif len(match) == 0 {\n\t\t\t\t\tLogError.Println(\"invalid file: syntax \", t)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tincludeFileName := fmt.Sprintf(\"%s/%s\", path.Dir(tmpfile), match[1])\n\t\t\t\tincludeContent, err := ioutil.ReadFile(includeFileName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tLogWarning.Println(err)\n\t\t\t\t}\n\t\t\t\tLogInfo.Println(\"including file :\", includeFileName)\n\t\t\t\tLogDebug.Println(\"includeContent\", string(includeContent))\n\t\t\t\tsrcContent.WriteString(string(includeContent))\n\t\t\t} else {\n\t\t\t\tLogWarning.Println(\"Found incomplete tag in include from file \", tmpfile)\n\t\t\t}\n\t\t} else if strings.Index(t, \"<%LookupFile:\") > -1 {\n\t\t\tLogDebug.Println(\"Rendering LookupFile\")\n\t\t\tvar lookup LookupList\n\t\t\tre := regexp.MustCompile(\"\\\\<\\\\%LookupFile:(.*?),(.*?),(.*?),(.*?)\\\\%\\\\>\")\n\n\t\t\t/*\n\t\t\t\t//\n\t\t\t\t// Fist we need to find if there is a template within the lookup definition\n\t\t\t\tt := fasttemplate.New(t, \"{{\", \"}}\")\n\t\t\t\ts := t.ExecuteString(pairs)\n\t\t\t*/\n\t\t\t//var tmpl = template.Must(template.ParseFiles(t))\n\t\t\t// Create a new template and parse the letter into it.\n\t\t\t// Get the Sprig function map.\n\t\t\tfmap := sprig.TxtFuncMap()\n\t\t\tvar tmpl = template.Must(template.New(\"LookupFile\").Funcs(fmap).Parse(t))\n\n\t\t\tvar bytes bytes.Buffer\n\t\t\twriter := bufio.NewWriter(&bytes)\n\n\t\t\terr = tmpl.Execute(writer, pairs)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\terr = writer.Flush()\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tLogDebug.Println(bytes.String())\n\n\t\t\tmatch := re.FindStringSubmatch(bytes.String())\n\n\t\t\tif len(match) == 0 {\n\t\t\t\tLogError.Println(\"invalid LookupFile: syntax \", t)\n\t\t\t\t//BUG/FIX: Should push up a error to rest calling function\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tLogDebug.Println(\"LookupFile: \", match[LookupFile])\n\t\t\tLogDebug.Println(\"LookupKey: \", match[LookupKey])\n\t\t\tLogDebug.Println(\"LookupSubkey: \", match[LookupSubkey])\n\t\t\tLogDebug.Println(\"LookupDefaultValue: \", match[LookupDefaultValue])\n\n\t\t\tyamlFile, err := ioutil.ReadFile(fmt.Sprintf(match[LookupFile]))\n\t\t\tif err != nil {\n\t\t\t\tLogError.Println(\"reading LookupFile \", match[LookupFile])\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\terr = yaml.Unmarshal(yamlFile, &lookup)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tvar lookupvalue string\n\t\t\tvar ok bool\n\t\t\tLogDebug.Println(lookup.Lookup)\n\t\t\tif lookupvalue, ok = lookup.Lookup[match[LookupKey]][match[LookupSubkey]]; ok {\n\t\t\t\tLogDebug.Println(\"Found lookup value in file :\", lookupvalue)\n\t\t\t} else {\n\t\t\t\tlookupvalue = match[LookupDefaultValue]\n\t\t\t\tLogDebug.Println(\"Using default lookup Value :\", lookupvalue)\n\t\t\t}\n\n\t\t\tsrcContent.WriteString(re.ReplaceAllString(bytes.String(), lookupvalue))\n\n\t\t} else {\n\t\t\tsrcContent.WriteString(t)\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tLogWarning.Println(err)\n\t}\n\n\t//var tmpl = template.Must(template.ParseFiles(tmpl_file))\n\t// Get the Sprig function map.\n\tfmap := sprig.TxtFuncMap()\n\tvar tmpl = template.Must(template.New(\"rendered_template\").Funcs(fmap).Parse(srcContent.String()))\n\n\tvar bytes bytes.Buffer\n\twriter := bufio.NewWriter(&bytes)\n\n\terr = tmpl.Execute(writer, pairs)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = writer.Flush()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tLogDebug.Println(bytes.String())\n\n\treturn bytes.String(), nil\n\n}", "func (gc *Client) generateClientFile(dir string) error {\n\tfileName := filepath.Join(dir, \"/client_\"+strings.ToLower(gc.Name)+\".go\")\n\treturn commons.GenerateFile(gc, \"./templates/client_go.tmpl\", \"client_go\", fileName, false)\n}", "func WriteTargetFileFromTemplate(targetFile string, tmpl []byte, envs *utils.MainConfig) error {\n\tt, err := template.New(\"\").Parse(string(tmpl))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(targetFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\terr = t.Execute(f, envs.Environments)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func renderFileFromTemplate(basePath string, templateInstance *template.Template, renderConfig rt.RenderConfig, config *rt.Config, fromTo rt.FromTo) error {\n\trelativeDestPath := path.Join(basePath, fromTo.To)\n\n\tdestDir := path.Dir(relativeDestPath)\n\terr := os.MkdirAll(destDir, os.ModePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdestFile, err := os.Create(relativeDestPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := addAutogeneratedHeader(destFile); err != nil {\n\t\treturn err\n\t}\n\n\tvalues := map[string]interface{}{\"Values\": renderConfig.Values, \"Global\": config.Global}\n\n\treturn templateInstance.Execute(destFile, values)\n}", "func main() {\n out, _ := os.Create(\"error-template.go\")\n out.Write([]byte(\"// generated by go run scripts/embed-template.go; DO NOT EDIT\\n\\n\"))\n out.Write([]byte(\"package main\\n\\nconst (\\n\"))\n out.Write([]byte(\"errorTemplate = `\"))\n f, _ := os.Open(\"error-template.html\")\n io.Copy(out, f)\n out.Write([]byte(\"`\\n\"))\n out.Write([]byte(\")\\n\"))\n}", "func (f *CalendarProperties) Generate(tempType string) ([]byte, error) {\n\tif f.BinPath == \"\" {\n\t\tpath, _ := filepath.Abs(os.Args[0])\n\t\tf.BinPath = path\n\t}\n\n\treturn createFromTemplate(fmt.Sprintf(\"templates/%s.plist\", tempType), *f)\n}", "func TestGenerateComposefileBuild(t *testing.T) {\n\tt.Parallel()\n\tcomposefile := filepath.Join(generateComposeBaseDir, \"build\", \"docker-compose.yml\")\n\tdockerfile := filepath.ToSlash(filepath.Join(generateComposeBaseDir, \"build\", \"build\", \"Dockerfile\"))\n\tflags := []string{fmt.Sprintf(\"--compose-files=%s\", composefile)}\n\ttOs := []generateTestObject{\n\t\t{\n\t\t\tfilePath: filepath.ToSlash(composefile),\n\t\t\twantImages: []generate.ComposefileImage{\n\t\t\t\t{Image: generate.Image{Name: \"busybox\", Tag: \"latest\"}, ServiceName: \"svc\", Dockerfile: dockerfile},\n\t\t\t},\n\t\t\ttestFn: checkGenerateComposefile,\n\t\t},\n\t}\n\ttestGenerate(t, flags, tOs)\n}", "func GenerateMainfile(binaryName, path string, info *parse.PkgInfo) error {\n\tdebug.Println(\"Creating mainfile at\", path)\n\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating generated mainfile: %v\", err)\n\t}\n\tdefer f.Close()\n\tdata := mainfileTemplateData{\n\t\tDescription: info.Description,\n\t\tFuncs: info.Funcs,\n\t\tAliases: info.Aliases,\n\t\tImports: info.Imports,\n\t\tBinaryName: binaryName,\n\t}\n\n\tif info.DefaultFunc != nil {\n\t\tdata.DefaultFunc = *info.DefaultFunc\n\t}\n\n\tdebug.Println(\"writing new file at\", path)\n\tif err := mainfileTemplate.Execute(f, data); err != nil {\n\t\treturn fmt.Errorf(\"can't execute mainfile template: %v\", err)\n\t}\n\tif err := f.Close(); err != nil {\n\t\treturn fmt.Errorf(\"error closing generated mainfile: %v\", err)\n\t}\n\t// we set an old modtime on the generated mainfile so that the go tool\n\t// won't think it has changed more recently than the compiled binary.\n\tlongAgo := time.Now().Add(-time.Hour * 24 * 365 * 10)\n\tif err := os.Chtimes(path, longAgo, longAgo); err != nil {\n\t\treturn fmt.Errorf(\"error setting old modtime on generated mainfile: %v\", err)\n\t}\n\treturn nil\n}", "func TestCreate(t *testing.T) {\n\n}", "func (g Generator) Generate() error {\n\tdefaultSchema := \"public\"\n\tif g.DefaultSchema != \"\" {\n\t\tdefaultSchema = g.DefaultSchema\n\t}\n\n\ttableFiles, err := listYamlFiles(\"tables\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tviewFiles, err := listYamlFiles(\"views\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttableSpecs, err := createTableSpecs(tableFiles, defaultSchema)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tviewSpecs, err := createViewSpecs(viewFiles, defaultSchema)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trootDir := \".\"\n\tif g.RootDir != \"\" {\n\t\trootDir = g.RootDir\n\t}\n\n\ti, err := interpolation.NewInterpolator(g.BaseImportPath, rootDir, defaultSchema, tableSpecs, viewSpecs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = i.Interpolate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ti.DisplayTargets()\n\n\terr = g.generateCommons(i)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.generateTables(i.TablesData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = g.generateViews(i.ViewsData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func generateRandUrlFile(output string, baseUrl string, count int) error {\n\tfile, err := os.Create(output)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tnow := time.Now().Unix()\n\tfor i := 0; i < count; i++ {\n\t\tfile.WriteString(fmt.Sprintf(\"%s/%d_%s\\n\", baseUrl, now, randString(16)))\n\t}\n\n\treturn nil\n}", "func (g *CodeGenerator) Generate() error {\n\tif len(g.opts.FilePath) == 0 {\n\t\treturn errors.New(\"invalid file path\")\n\t}\n\n\tif len(g.opts.PackageName) == 0 {\n\t\treturn errors.New(\"invalid package name\")\n\t}\n\n\t// generate package\n\tg.P(\"package \", g.opts.PackageName)\n\tg.P()\n\n\t// generate import path\n\tg.P(\"import (\")\n\tfor _, path := range g.opts.ImportPath {\n\t\tg.P(\"\\t\\\"\", path, \"\\\"\")\n\t}\n\tg.P(\")\")\n\tg.P()\n\n\t// generate variables\n\tfor _, v := range g.opts.Variables {\n\t\tvariableLine := fmt.Sprintf(\"var\\t%-15s\\t%-15s\\t//%-15s\", v.name, v.tp, v.comment)\n\t\tg.P(variableLine)\n\t\tg.P()\n\t}\n\n\t// generate structs\n\tfor _, s := range g.opts.Structs {\n\t\t// struct comment\n\t\tif len(s.comment) > 0 {\n\t\t\tg.P(\"// \", s.comment)\n\t\t}\n\n\t\t// struct begin\n\t\tg.P(\"type \", s.name, \" struct {\")\n\n\t\t// struct fields\n\t\tfieldLines := make([]string, s.fieldRaw.Size())\n\t\tit := s.fieldRaw.Iterator()\n\t\tfor it.Next() {\n\t\t\tfieldRaw := it.Value().(*ExcelFieldRaw)\n\n\t\t\t// don't need import\n\t\t\tif !fieldRaw.imp {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfieldLine := fmt.Sprintf(\"\\t%-15s\\t%-20s\\t%-20s\\t//%-10s\", it.Key(), fieldRaw.tp, fieldRaw.tag, fieldRaw.desc)\n\t\t\tfieldLines[fieldRaw.idx] = fieldLine\n\t\t}\n\n\t\t// print struct field in sort\n\t\tfor _, v := range fieldLines {\n\t\t\tif len(v) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tg.P(v)\n\t\t}\n\n\t\t// struct end\n\t\tg.P(\"}\")\n\t\tg.P()\n\t}\n\n\t// generate functions\n\tfor _, f := range g.opts.Functions {\n\t\t// function comment\n\t\tif len(f.comment) > 0 {\n\t\t\tg.P(\"// \", f.comment)\n\t\t}\n\n\t\t// function receiver\n\t\tvar receiver string\n\t\tif len(f.receiver) > 0 {\n\t\t\treceiver = fmt.Sprintf(\"(e *%s)\", f.receiver)\n\t\t}\n\n\t\t// function parameters\n\t\tparameters := strings.Join(f.parameters, \", \")\n\n\t\t// function begin\n\t\tg.P(\"func \", receiver, \" \", f.name, \"(\", parameters, \") \", f.retType, \" {\")\n\n\t\t// function body\n\t\tg.P(\"\\t\", f.body)\n\n\t\t// function end\n\t\tg.P(\"}\")\n\t\tg.P()\n\t}\n\n\treturn ioutil.WriteFile(g.opts.FilePath, g.buf.Bytes(), 0666)\n}", "func (c *Client) Template(sourceFilePath, destinationFilePath string, perms os.FileMode, appendMap, envMap map[string]string) error {\n\ttemplateText, err := readTemplate(sourceFilePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttemplateResultBuffer, err := c.renderTemplate(templateText, appendMap, envMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn writeTemplateResults(destinationFilePath, templateResultBuffer, perms)\n}", "func (c *Config) createConfigFile(filename chezmoi.RelPath, data []byte) ([]byte, error) {\n\tfuncMap := make(template.FuncMap)\n\tchezmoi.RecursiveMerge(funcMap, c.templateFuncs)\n\tchezmoi.RecursiveMerge(funcMap, map[string]interface{}{\n\t\t\"promptBool\": c.promptBool,\n\t\t\"promptInt\": c.promptInt,\n\t\t\"promptString\": c.promptString,\n\t\t\"stdinIsATTY\": c.stdinIsATTY,\n\t\t\"writeToStdout\": c.writeToStdout,\n\t})\n\n\tt, err := template.New(string(filename)).Funcs(funcMap).Parse(string(data))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsb := strings.Builder{}\n\ttemplateData := c.defaultTemplateData()\n\tif c.init.data {\n\t\tchezmoi.RecursiveMerge(templateData, c.Data)\n\t}\n\tif err = t.Execute(&sb, templateData); err != nil {\n\t\treturn nil, err\n\t}\n\treturn []byte(sb.String()), nil\n}", "func ProcessTemplate(templateFile string, values interface{}) (string, []byte, error) {\n\tname := path.Base(templateFile)\n\tt := template.New(name).Funcs(map[string]interface{}{\n\t\t\"addURIAndSha\": func(url, tag string) string {\n\t\t\tt := struct {\n\t\t\t\tTagName string\n\t\t\t}{\n\t\t\t\tTagName: tag,\n\t\t\t}\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\ttemp, err := template.New(\"url\").Parse(url)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\terr = temp.Execute(buf, t)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tlogrus.Infof(\"getting sha256 for %s\", buf.String())\n\t\t\tsha256, err := getSha256ForAsset(buf.String())\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\treturn fmt.Sprintf(`uri: %s\n sha256: %s`, buf.String(), sha256)\n\t\t},\n\t})\n\n\ttemplateObject, err := t.ParseFiles(templateFile)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\terr = templateObject.Execute(buf, values)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tkrewFile, err := ioutil.TempFile(\"\", \"krew-\")\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\terr = ioutil.WriteFile(krewFile.Name(), buf.Bytes(), 0644)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tprocessedTemplate := buf.Bytes()\n\tpluginName, err := krew.GetPluginName(krewFile.Name())\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\treturn pluginName, processedTemplate, nil\n}", "func TestHashTemplate(t *testing.T) {\n\ttempl := gameMainfileTplString\n\tdefer func() { gameMainfileTplString = templ }()\n\tname, err := ExeName(\"go\", mg.CacheDir(), []string{\"testdata/func.go\", \"testdata/command.go\"})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgameMainfileTplString = \"some other template\"\n\tchanged, err := ExeName(\"go\", mg.CacheDir(), []string{\"testdata/func.go\", \"testdata/command.go\"})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif changed == name {\n\t\tt.Fatal(\"expected executable name to chage if template changed\")\n\t}\n}", "func generateResponseFile(templFP string, data *gengokit.Data, prevFile io.Reader) (io.Reader, error) {\n\tvar genCode io.Reader\n\tvar err error\n\n\t// Get the actual path to the file rather than the template file path\n\tactualFP := templatePathToActual(templFP, data.Service.Name)\n\n\tswitch templFP {\n\tcase service.ServicePath:\n\t\th, err := service.NewService(data.Service, prevFile)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot parse previous handler: %q\", actualFP)\n\t\t}\n\n\t\tif genCode, err = h.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render service template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(h, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.ServiceWrapperPath:\n\t\tw := service.NewServiceWrapper(prevFile)\n\t\tif genCode, err = w.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render middleware template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(w, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.CmdServerPath:\n\t\tr := service.NewCmdServer(prevFile)\n\t\tif genCode, err = r.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render cmd server template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(r, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.CmdClientPath:\n\t\tif data.Config.GenClient {\n\t\t\tr := service.NewCmdClient(prevFile)\n\t\t\tif genCode, err = r.Render(templFP, data); err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"cannot render cmd client template: %s\", templFP)\n\t\t\t}\n\t\t\tresponseInfo(r, filepath.Join(data.Config.ServicePath, actualFP))\n\t\t} else {\n\t\t\treturn nil, ErrGenIgnored\n\t\t}\n\tcase service.ServerPath:\n\t\tr := service.NewServer(nil) // override server.go\n\t\tif genCode, err = r.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render server template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(nil, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.ServerEndpointsPath:\n\t\tedp := service.NewServerEndpoints(prevFile)\n\t\tif genCode, err = edp.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render endpoints template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(edp, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.ServerInterruptPath:\n\t\tintrpt := service.NewServerInterrupt(prevFile)\n\t\tif genCode, err = intrpt.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render interrupt template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(intrpt, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.ServerWrapperPath:\n\t\tr := service.NewServerWrapper(prevFile)\n\t\tif genCode, err = r.Render(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render server template: %s\", templFP)\n\t\t}\n\t\tresponseInfo(r, filepath.Join(data.Config.ServicePath, actualFP))\n\tcase service.BaronPath:\n\t\tif genCode, err = applyTemplateFromPath(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render baron template: %s\", templFP)\n\t\t}\n\t\tactualFP = strings.TrimPrefix(actualFP, \"baron\")\n\t\tactualFP = filepath.Join(data.Config.PBPath, actualFP)\n\t\tresponseInfo(nil, actualFP)\n\tdefault:\n\t\tif genCode, err = applyTemplateFromPath(templFP, data); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"cannot render template: %s\", templFP)\n\t\t}\n\t\tactualFP = filepath.Join(data.Config.ServicePath, actualFP)\n\t\tresponseInfo(nil, actualFP)\n\t}\n\n\tcodeBytes, err := ioutil.ReadAll(genCode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// ignore error as we want to write the code either way to inspect after\n\t// writing to disk\n\tformattedCode := formatCode(codeBytes)\n\n\treturn bytes.NewReader(formattedCode), nil\n}", "func generateDummyFiles(ctx *Context) (err error) {\n\terr = ioutil.WriteFile(filepath.Join(ctx.CGenDir, \"_dummy.h\"), []byte(\"// Dummy File\"), 0755)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = ioutil.WriteFile(filepath.Join(ctx.CPPGenDir, \"_dummy.h\"), []byte(\"// Dummy File\"), 0755)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = ioutil.WriteFile(filepath.Join(ctx.CPPGenDir, \"_dummy.cpp\"), []byte(\"// Dummy File\"), 0755)\n\treturn\n}", "func writeFile(tmplStr, suffix string, spec *vfsSpec) error {\n\n\terrFmt := \"write file: %v\\n\"\n\n\tif suffix != \"\" {\n\t\tsuffix = \"_\" + suffix\n\t}\n\n\tfilename := fmt.Sprintf(\"%s/%s%s.go\", spec.Package, spec.Package, suffix)\n\n\tout, err := os.Create(filename)\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\tdefer out.Close()\n\n\ttmpl, err := template.New(\"\").Funcs(fnMap).Parse(tmplStr)\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\ttmpl, err = tmpl.Parse(publicInterfaceTmplStr)\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\tbuf := new(bytes.Buffer)\n\terr = tmpl.Execute(buf, spec)\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\tdata, err := format.Source(buf.Bytes())\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\tif err := ioutil.WriteFile(filename, data, os.FileMode(0644)); err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\tpwd, err := filepath.Abs(\".\")\n\tif err != nil {\n\t\treturn fmt.Errorf(errFmt, err)\n\t}\n\n\tfmt.Printf(\"ESSENCE: file written: %s/%s\\n\", pwd, filename)\n\n\treturn nil\n}" ]
[ "0.70075065", "0.69138515", "0.6506305", "0.6493352", "0.63416076", "0.62526804", "0.61998314", "0.61942375", "0.61715287", "0.61503637", "0.61255413", "0.6116449", "0.61051226", "0.6090384", "0.60783386", "0.60713553", "0.60068524", "0.6002592", "0.5948072", "0.59080184", "0.5894047", "0.586763", "0.5856691", "0.5833046", "0.5793992", "0.5785252", "0.578482", "0.5741295", "0.5739606", "0.5729693", "0.57025665", "0.56719154", "0.56698686", "0.5651671", "0.5650378", "0.5624055", "0.5618455", "0.5615844", "0.5612254", "0.5595586", "0.55706584", "0.5567416", "0.55557114", "0.5541376", "0.55355245", "0.55330676", "0.55046034", "0.5496454", "0.54926676", "0.5491044", "0.54872596", "0.5477635", "0.5468243", "0.54651356", "0.54501706", "0.54443276", "0.54308236", "0.54282707", "0.5425211", "0.5420813", "0.54143745", "0.5413963", "0.5408634", "0.5400825", "0.5397112", "0.5378526", "0.5378376", "0.5377021", "0.53695655", "0.5367667", "0.53643024", "0.53532106", "0.5351556", "0.53472096", "0.53423", "0.5329052", "0.532306", "0.53182775", "0.5310875", "0.5301499", "0.52889264", "0.52867204", "0.5282901", "0.5280618", "0.52701265", "0.52650535", "0.52526546", "0.5249786", "0.5249259", "0.5248752", "0.5243435", "0.5230657", "0.5225211", "0.5221617", "0.5213818", "0.52090955", "0.5204364", "0.52013206", "0.5201156", "0.51984906" ]
0.7975928
0
ParseFunctions parses a file and returns information about its HTTP handlers
func ParseFunctions(filePath string) *TemplateValues { fset := token.NewFileSet() f, err := parser.ParseFile(fset, filePath, nil, parser.ParseComments) if err != nil { log.Fatal(err) } var funcInfos []FunctionInfo packageName := fmt.Sprint(f.Name) containsMux := false for _, decl := range f.Decls { switch t := decl.(type) { case *ast.FuncDecl: responseWriterParamExists := false requestParamExists := false for _, param := range t.Type.Params.List { switch t2 := param.Type.(type) { case *ast.SelectorExpr: paramName := fmt.Sprint(t2.Sel.Name) if paramName == "ResponseWriter" { responseWriterParamExists = true } case *ast.StarExpr: paramName := fmt.Sprint(t2.X) if paramName == "&{http Request}" { requestParamExists = true } } } if responseWriterParamExists && requestParamExists { muxVars := getMuxVars(t) if len(muxVars) > 0 { containsMux = true } funcInfo := FunctionInfo{ Name: fmt.Sprint(t.Name), MuxVars: muxVars, } funcInfos = append(funcInfos, funcInfo) } } } templateValues := TemplateValues{ FuncInfo: funcInfos, PackageName: packageName, ContainsMux: containsMux, } return &templateValues }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Parse(urlStr string, key ...interface{}) (func(http.Handler) http.Handler,\n\terror) {\n\n\tu, err := mgourl.Parse(urlStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts, err := mgo.Dial(u.ShortString())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tk := getkey(key...)\n\tif k == nil {\n\t\tk = u.Database()\n\t}\n\n\treturn Handler(s, u.Database(), k), nil\n}", "func main() {\n\tparse(read_file(\"test.txt\"))\n\n}", "func (i Interface) parseFunctions(contentLines []string) []Function {\n\tvar functions []Function\n\tfor _, line := range contentLines {\n\t\tif isPureVirtualDefinition(line) {\n\t\t\tnewFunction := NewFunction(line)\n\t\t\tfunctions = append(functions, *newFunction)\n\t\t}\n\t}\n\treturn functions\n}", "func (c *Config) ParseFunction(path string) string {\n\tpath = strings.TrimPrefix(path, c.Path)\n\tpos := strings.Index(path, \"?\")\n\tif pos > -1 {\n\t\tpath = path[:pos]\n\t}\n\tpos = strings.Index(path, \"#\")\n\tif pos > -1 {\n\t\tpath = path[:pos]\n\t}\n\n\treturn strings.Split(path, \"/\")[0]\n}", "func FileParse(c *gin.Context) {\n\tvar m models.PubSubMessage\n\n\ttimeNow := time.Now().In(utils.ConvertUTCtoIST())\n\n\tbody, err := ioutil.ReadAll(c.Request.Body)\n\tif err != nil {\n\t\tLogResponceEvent(\"Ede1: Reading data error: \"+err.Error(), http.StatusBadRequest, 0, timeNow)\n\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t}\n\n\tif err := json.Unmarshal(body, &m); err != nil {\n\t\tLogResponceEvent(\"Ede1: Error while UnMarshaling error:\"+err.Error(), http.StatusBadRequest, 0, timeNow)\n\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t}\n\n\terr = parsers.Worker(m)\n\tif err != nil {\n\t\tc.JSON(http.StatusOK, \"\")\n\t} else {\n\t\tc.JSON(http.StatusOK, \"done\")\n\t}\n}", "func walkFunc(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {\n\tlog.Printf(\"method: %s - - route: %s\\n\", method, route)\n\treturn nil\n}", "func Parser() {\n\tif err = conf.Parse(configLocation); err != nil {\n\t\tlogger.Logger.Panicln(err)\n\t}\n\n\tparseHTTP()\n\n}", "func ParseFile(filename string) []interface{} {\n content, _ := ioutil.ReadFile(filename)\n return ParseText(content)\n}", "func parseFunction(function *ast.FuncDecl, fileContext *fileContext) {\n\tfunctionName := addFunctionNode(function, fileContext)\n\n\tparseParameterTypes(function, functionName, fileContext)\n\n\tparseResultTypes(function, functionName, fileContext)\n}", "func Parser() {\n\tif err = conf.Parse(configLocation); err != nil {\n\t\tlogger.Logger.Panicln(err)\n\t}\n\n\tparseMysql()\n\tparseGrpc()\n\tparseHTTP()\n\tparseVolumeHandle()\n}", "func (h *handler) Parse(host core.Host, method uint8, decoder *scale.Decoder) (core.ParseOutput, error) {\n\treturn core.ParseOutput{}, nil\n}", "func (r *Router) ParseHandler(w http.ResponseWriter, req *http.Request) {\n\tparams := req.URL.Query()\n\tif len(params) > 0 {\n\t\tw.WriteHeader(200)\n\t\ts := fmt.Sprintf(\"%v\", params)\n\t\tw.Write([]byte(s))\n\t\treturn\n\t}\n}", "func init() {\n\thttp.HandleFunc(taskRootPath, listTasks)\n\thttp.HandleFunc(taskPostPath, postTaks)\n\thttp.HandleFunc(\"/parse/\", parameterTest())\n}", "func (node *Node) GET(functions ...interface{}) *Handler {\n\n\thandler := &Handler{}\n\n\tif len(functions) > 0 { handler.function = functions[0].(func (req web.RequestInterface) *web.ResponseStatus) }\n\n\tnode.addHandler(\"GET\", handler)\n\n\treturn handler\n}", "func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {\n\n\tvar m Middleware\n\terr := m.UnmarshalCaddyfile(h.Dispenser)\n\treturn m, err\n}", "func parseFile(p string) {\n\tif path.Ext(p) != \".json\" {\n\t\treturn\n\t}\n\n\tf, err := os.Open(p)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\t_ = f.Close()\n\t}()\n\n\tvar messages []Message\n\terr = json.NewDecoder(f).Decode(&messages)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar urls []string\n\tfor _, m := range messages {\n\t\tif m.Type != \"message\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, f := range m.Files {\n\t\t\turls = append(urls, f.URL)\n\t\t}\n\t}\n\tdownloadFiles(urls)\n}", "func ParseEventHandler(conf *config.Config) handlers.Handler {\n\n\tvar eventHandler handlers.Handler\n\n\teventHandler = new(handlers.HandlerConfig)\n\tif err := eventHandler.Init(conf); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn eventHandler\n}", "func Parser() {\n\tif err = conf.Parse(configLocation); err != nil {\n\t\tlogger.Logger.Panicln(err)\n\t}\n\n\tparseMysql()\n\tparseHTTP()\n\tparseIpmi()\n\tparseWOL()\n}", "func Handle(manipulatorFn func([][]string) string) http.Handler {\n return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n // Allow only POST request as we are accepting a file\n if r.Method != http.MethodPost {\n w.WriteHeader(http.StatusMethodNotAllowed)\n w.Write([]byte(\"Method not Allowed\"))\n return\n }\n records, err := ParseFile(r)\n if err != nil {\n w.WriteHeader(http.StatusUnprocessableEntity)\n w.Write([]byte(fmt.Sprintf(\"error %s\", err.Error())))\n return\n }\n w.Write([]byte(manipulatorFn(records)))\n })\n}", "func initHTTPHandlers() {\n\thttp.Handle(\"/\", handlerWrapper(handleMain))\n\thttp.Handle(\"/bug\", handlerWrapper(handleBug))\n\thttp.Handle(\"/text\", handlerWrapper(handleText))\n\thttp.Handle(\"/admin\", handlerWrapper(handleAdmin))\n\thttp.Handle(\"/x/.config\", handlerWrapper(handleTextX(textKernelConfig)))\n\thttp.Handle(\"/x/log.txt\", handlerWrapper(handleTextX(textCrashLog)))\n\thttp.Handle(\"/x/report.txt\", handlerWrapper(handleTextX(textCrashReport)))\n\thttp.Handle(\"/x/repro.syz\", handlerWrapper(handleTextX(textReproSyz)))\n\thttp.Handle(\"/x/repro.c\", handlerWrapper(handleTextX(textReproC)))\n\thttp.Handle(\"/x/patch.diff\", handlerWrapper(handleTextX(textPatch)))\n\thttp.Handle(\"/x/bisect.txt\", handlerWrapper(handleTextX(textLog)))\n\thttp.Handle(\"/x/error.txt\", handlerWrapper(handleTextX(textError)))\n\thttp.Handle(\"/x/minfo.txt\", handlerWrapper(handleTextX(textMachineInfo)))\n\tfor ns := range config.Namespaces {\n\t\thttp.Handle(\"/\"+ns, handlerWrapper(handleMain))\n\t\thttp.Handle(\"/\"+ns+\"/fixed\", handlerWrapper(handleFixed))\n\t\thttp.Handle(\"/\"+ns+\"/invalid\", handlerWrapper(handleInvalid))\n\t\thttp.Handle(\"/\"+ns+\"/graph/bugs\", handlerWrapper(handleKernelHealthGraph))\n\t\thttp.Handle(\"/\"+ns+\"/graph/lifetimes\", handlerWrapper(handleGraphLifetimes))\n\t\thttp.Handle(\"/\"+ns+\"/graph/fuzzing\", handlerWrapper(handleGraphFuzzing))\n\t\thttp.Handle(\"/\"+ns+\"/graph/crashes\", handlerWrapper(handleGraphCrashes))\n\t\thttp.Handle(\"/\"+ns+\"/repos\", handlerWrapper(handleRepos))\n\t\thttp.Handle(\"/\"+ns+\"/bug-stats\", handlerWrapper(handleBugStats))\n\t\thttp.Handle(\"/\"+ns+\"/subsystems\", handlerWrapper(handleSubsystemsList))\n\t\thttp.Handle(\"/\"+ns+\"/s/\", handlerWrapper(handleSubsystemPage))\n\t}\n\thttp.HandleFunc(\"/cron/cache_update\", cacheUpdate)\n\thttp.HandleFunc(\"/cron/deprecate_assets\", handleDeprecateAssets)\n\thttp.HandleFunc(\"/cron/refresh_subsystems\", handleRefreshSubsystems)\n\thttp.HandleFunc(\"/cron/subsystem_reports\", handleSubsystemReports)\n}", "func Parse(f *os.File) (*Code, error) {\n\tlanguage, err := detectLanguage(f)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error detecting language: %v\", err)\n\t}\n\tparserMap := map[string]Parser{\n\t\tgolang: &GoParser{},\n\t}\n\treturn parserMap[language].Parse(f)\n}", "func parseTargets(file string, in inputs.Handler) error {\n\t// Open the file and if there's an error, return it\n\tinFile, err := os.Open(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer inFile.Close()\n\n\t// Setup a scanner to read the file line by line\n\tscanner := bufio.NewScanner(inFile)\n\tfor scanner.Scan() {\n\t\t// Get the line from the scanner and add it\n\t\tin.AddTarget(scanner.Text())\n\t}\n\n\t// When we're done with the file, return that we're complete.\n\treturn nil\n}", "func parseHttpRequestFromHttpTextFile(keptnEvent BaseKeptnEvent, httpfile string) (genericHttpRequest, error) {\n\tvar returnRequest genericHttpRequest\n\n\tcontent, err := ioutil.ReadFile(httpfile)\n\tif err != nil {\n\t\treturn returnRequest, err\n\t}\n\n\treturn parseHttpRequestFromString(string(content), keptnEvent)\n}", "func ParseGo(code string) (functions map[uint64]*function.Function) {\n\n\tcodeLines := strings.Split(code, \"\\n\")\n\n\tfunctions = make(map[uint64]*function.Function)\n\n\tvar (\n\t\tstartLine uint64\n\t\tendLine uint64\n\t\tcomment string\n\t\tfunctionContent string\n\t\tstate = commentSearch\n\t)\n\n\tfor idx, line := range codeLines {\n\t\tlineIdx := uint64(idx + 1)\n\t\t// Searching for comment or \"func\"/\"type\" keywords\n\t\tstrings.ReplaceAll(line, \"\\r\", \"\")\n\n\t\t// We found a comment. Transition state to commentStart\n\t\tif strings.HasPrefix(line, \"//\") && state != commentStart {\n\t\t\tstate = commentStart\n\t\t\tstartLine = lineIdx\n\n\t\t} else if strings.Contains(line, \"func\") || strings.Contains(line, \"type\") {\n\n\t\t\t// we found the function keyword so we transition to funcStart state\n\t\t\tif state == commentSearch {\n\t\t\t\t// If we're coming from commentSearch, that means that we didn't have a comment so we set startLine to idx\n\t\t\t\tstartLine = lineIdx\n\n\t\t\t}\n\t\t\t// otherwise, we're coming from commentStart, that means that we had a comment so we leave startLine as it is\n\t\t\tstate = funcStart\n\t\t} else if strings.HasPrefix(line, \"}\") {\n\t\t\tstate = funcEnd\n\t\t\tendLine = lineIdx\n\n\t\t} else if !(strings.HasPrefix(line, \"//\")) && state != funcStart {\n\t\t\tstate = commentSearch\n\t\t\tcomment = \"\"\n\t\t\tstartLine = 0\n\t\t\tendLine = 0\n\n\t\t}\n\n\t\tswitch state {\n\t\tcase commentSearch:\n\t\t\tcontinue\n\t\tcase commentStart:\n\t\t\tcomment += fmt.Sprintf(\"%v\\n\", line)\n\t\tcase funcStart:\n\t\t\tfunctionContent += fmt.Sprintf(\"%v\\n\", line)\n\n\t\tcase funcEnd:\n\t\t\t// add the closing brace\n\t\t\tfunctionContent += fmt.Sprintf(\"%v\\n\", line)\n\t\t\tendLine = uint64(idx)\n\n\t\t\t// create a new function object with the information we got\n\t\t\tf := function.NewFunction(comment, functionContent, \"noNameYet\", 0, startLine, endLine)\n\n\t\t\t// add that to our map\n\t\t\tfunctions[uint64(f.FuncID)] = f\n\n\t\t\t// reset our state machine\n\t\t\tstartLine = 0\n\t\t\tcomment = \"\"\n\t\t\tfunctionContent = \"\"\n\t\t\tstate = commentSearch\n\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\n\t}\n\n\treturn\n}", "func (app *APP) Parse() error {\n\tdataHandlers := map[string]dataHandler{\n\t\tOrganisationsKey: app.LoadOrganisationsFromJSON,\n\t\tUsersKey: app.LoadUsersFromJSON,\n\t\tTicketsKey: app.LoadTicketsFromJSON,\n\t}\n\n\tfor dataType, dataHandler := range dataHandlers {\n\t\terr := dataHandler(app.jsonContents[dataType])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to read %s data file with error: %s\", dataType, err.Error())\n\t\t}\n\t}\n\treturn nil\n}", "func handleParse(h Handler, content string) ([]string, error) {\n\tvar (\n\t\tp CmdParser\n\t\tok bool\n\t)\n\tif p, ok = h.(CmdParser); !ok {\n\t\treturn cmdParserDefault(content), nil\n\t}\n\n\treturn p.Parse(content)\n}", "func (h *notificationPostHandler) Parse(ctx context.Context, r *http.Request) error {\n\tt := gimlet.GetVars(r)[\"type\"]\n\tswitch t {\n\tcase \"jira_comment\":\n\t\th.handler = makeJiraCommentNotification(h.environment)\n\tcase \"jira_issue\":\n\t\th.handler = makeJiraIssueNotification(h.environment)\n\tcase \"slack\":\n\t\th.handler = makeSlackNotification(h.environment)\n\tcase \"email\":\n\t\th.handler = makeEmailNotification(h.environment)\n\tdefault:\n\t\treturn errors.Errorf(\"'%s' is not a supported {type}\", t)\n\t}\n\n\treturn h.handler.Parse(ctx, r)\n}", "func ParsingMainPage(){\n\tcurPath:=currentPath()\n\t_ = os.MkdirAll(curPath+\"/pars_result/\"+mainPagesParsResultDir, 0777)\n\t_ = os.MkdirAll(curPath+\"/pars_result/\"+linksParsResultDir, 0777)\n\tresultMainPagePars:=curPath+\"/pars_result/MainPageInformation.json\"\n\tmainPageFileTemp,_:=os.Create(resultMainPagePars)\n\tdefer mainPageFileTemp.Close()\n\tparser.MainPageParser(resultMainPagePars)\n\tmainPageFileSave:=curPath+\"/pars_result/\"+mainPagesParsResultDir+\"/\"+time.Now().Format(\"2006-1-2\")+\".json\"\n\t_ = CopyData(mainPageFileSave, resultMainPagePars)\n\tdefer RemoveFile(resultMainPagePars)\n\n\tvar mainPages models.MainPages\n\t_ = os.MkdirAll(curPath+\"/pars_result/\"+linksParsResultDir+\"/\"+time.Now().Format(\"2006-1-2\"), 0777)\n\tsN:=\"https://domain-status.com/archives/\"+time.Now().AddDate(0,0,-1).Format(\"2006-1-2\")+\"/\"\n\n\tfor _,i:=range OpenAndRead(resultMainPagePars,mainPages){\n\t\tnameOfFile:=strings.Replace(i,sN,time.Now().Format(\"2006-1-2\")+\"_\",1)\n\t\tnameOfFile=strings.Replace(nameOfFile,\"/1\",\".json\",1)\n\t\tnameOfFile=strings.ReplaceAll(nameOfFile,\"/\",\"_\")\n\t\t_ = CreateFile(curPath + \"/pars_result/\" + linksParsResultDir + \"/\" + time.Now().Format(\"2006-1-2\") + \"/\" + nameOfFile)\n\t\tstartUrlArray:=strings.Fields(i)\n\t\tparser.PageParser(curPath+\"/pars_result/\"+linksParsResultDir+\"/\"+time.Now().Format(\"2006-1-2\")+\"/\"+nameOfFile,startUrlArray,100)\n\t}\n}", "func analyzeHandler(body []ast.Stmt, pkg *types.Package) gents.Contrat {\n\tvar out gents.Contrat\n\tfor _, stmt := range body {\n\t\tswitch stmt := stmt.(type) {\n\t\tcase *ast.ReturnStmt:\n\t\t\tif len(stmt.Results) != 1 { // should not happend : the method return error\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif call, ok := stmt.Results[0].(*ast.CallExpr); ok {\n\t\t\t\tif method, ok := call.Fun.(*ast.SelectorExpr); ok {\n\t\t\t\t\tif method.Sel.Name == \"JSON\" || method.Sel.Name == \"JSONPretty\" {\n\t\t\t\t\t\tif len(call.Args) >= 2 {\n\t\t\t\t\t\t\toutput := call.Args[1] // c.JSON(200, output)\n\t\t\t\t\t\t\tswitch output := output.(type) {\n\t\t\t\t\t\t\tcase *ast.Ident:\n\t\t\t\t\t\t\t\tout.Return = resolveLocalType(output, pkg)\n\t\t\t\t\t\t\tcase *ast.CompositeLit:\n\t\t\t\t\t\t\t\tout.Return = parseCompositeLit(output, pkg)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase *ast.AssignStmt:\n\t\t\tparseAssignments(stmt.Rhs, pkg, &out)\n\t\tcase *ast.IfStmt:\n\t\t\tif assign, ok := stmt.Init.(*ast.AssignStmt); ok {\n\t\t\t\tparseAssignments(assign.Rhs, pkg, &out)\n\t\t\t}\n\t\t}\n\t}\n\treturn out\n}", "func Parser() {\n\tif err = conf.Parse(configLocation); err != nil {\n\t\tlogger.Logger.Panicln(err)\n\t}\n\n\tparseHTTP()\n\tparseFlute()\n\tparseCello()\n\tparseHarp()\n\tparseViola()\n\tparseViolin()\n\tparseViolinNoVnc()\n\tparsePiano()\n}", "func ParseLinksFunc(host string) LinkParser {\n\tvalidLink := regexp.MustCompile(`(http|ftp|https)://(` + host + `)([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?`)\n\treturn func(host, body string) []string {\n\t\treturn validLink.FindAllString(body, -1)\n\t\t// TODO: handle relative links and make more sophisticated\n\t}\n}", "func ParseFile(r *http.Request) (records [][]string, err error) {\n file, fileHeader, err := r.FormFile(\"file\")\n // Validate file\n if file == nil {\n return nil, errors.New(\"A CSV File is required\")\n }\n if err != nil {\n return nil, err\n }\n defer file.Close()\n fileNames := strings.Split(fileHeader.Filename, \".\")\n fileExtension := strings.ToLower(fileNames[len(fileNames) -1])\n // Validate file format\n if fileExtension != \"csv\" {\n return nil, errors.New(\"A CSV File is required\")\n }\n\n return csv.NewReader(file).ReadAll()\n}", "func ParseFile(path string) (Result, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\tdefer file.Close()\n\treturn Parse(file)\n}", "func (p *ParserGo) Parse(filepath string) ([]string, error) {\n\treader, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open file %q: %s\", filepath, err)\n\t}\n\n\tdefer reader.Close()\n\n\tp.init()\n\tdefer p.init()\n\n\tdata, err := ioutil.ReadAll(reader)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read from reader: %s\", err)\n\t}\n\n\titer, err := g.Go.Tokenise(nil, string(data))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to tokenize file content: %s\", err)\n\t}\n\n\tfor _, token := range iter.Tokens() {\n\t\tp.processToken(token)\n\t}\n\n\treturn p.Output, nil\n}", "func Parse(filename string, r io.Reader, handler *reporter.Handler) (*ast.FileNode, error) {\n\tlx, err := newLexer(r, filename, handler)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tprotoParse(lx)\n\tif lx.res == nil {\n\t\t// nil AST means there was an error that prevented any parsing\n\t\t// or the file was empty; synthesize empty non-nil AST\n\t\tlx.res = ast.NewEmptyFileNode(filename)\n\t}\n\treturn lx.res, handler.Error()\n}", "func ParseFile(filename string, cb SaxCallbacks) error {\n\tvar cfilename *C.char = C.CString(filename)\n\tdefer C.free(unsafe.Pointer(cfilename))\n\n\t// newHandlerStruct zeroes out all the pointers; we assign only those that\n\t// are passed as non-nil in SaxCallbacks.\n\tSAXhandler := C.newHandlerStruct()\n\n\tif cb.StartDocument != nil {\n\t\tSAXhandler.startDocument = C.startDocumentSAXFunc(C.startDocumentCgo)\n\t}\n\n\tif cb.EndDocument != nil {\n\t\tSAXhandler.endDocument = C.endDocumentSAXFunc(C.endDocumentCgo)\n\t}\n\n\tif cb.StartElement != nil {\n\t\tSAXhandler.startElement = C.startElementSAXFunc(C.startElementCgo)\n\t}\n\t// StartElementNoAttr overrides StartElement\n\tif cb.StartElementNoAttr != nil {\n\t\tSAXhandler.startElement = C.startElementSAXFunc(C.startElementNoAttrCgo)\n\t}\n\n\tif cb.EndElement != nil {\n\t\tSAXhandler.endElement = C.endElementSAXFunc(C.endElementCgo)\n\t}\n\n\tif cb.Characters != nil {\n\t\tSAXhandler.characters = C.charactersSAXFunc(C.charactersCgo)\n\t}\n\t// CharactersRaw overrides Characters\n\tif cb.CharactersRaw != nil {\n\t\tSAXhandler.characters = C.charactersSAXFunc(C.charactersRawCgo)\n\t}\n\n\t// Pack the callbacks structure into an opaque unsafe.Pointer which we'll\n\t// pass to C as user_data, and C will pass it back to our Go callbacks.\n\tuser_data := pointer.Save(&cb)\n\tdefer pointer.Unref(user_data)\n\n\trc := C.xmlSAXUserParseFile(&SAXhandler, user_data, cfilename)\n\tif rc != 0 {\n\t\txmlErr := C.getLastError()\n\t\tmsg := strings.TrimSpace(C.GoString(xmlErr.message))\n\t\treturn fmt.Errorf(\"line %v: error: %v\", xmlErr.line, msg)\n\t}\n\n\treturn nil\n}", "func ParseFile(filename string) (*APIFile, error) {\n\tbytes, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent := string(bytes)\n\ttopMatches := apiFileTopRegex.FindAllStringSubmatch(content, -1)\n\tif len(topMatches) != 1 {\n\t\tif len(topMatches) == 0 {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, errors.New(\"Multiple APIs found in one file\")\n\t}\n\ttop := apiFileCommentStart.ReplaceAllLiteralString(topMatches[0][2], \"\")\n\tmodelIdxs := apiFileModelStart.FindAllStringIndex(top, -1)\n\tmodels := make([]string, len(modelIdxs))\n\tmodelIdxs = append(modelIdxs, []int{len(top)})\n\tfor i := range models {\n\t\tmodels[i] = strings.TrimSpace(top[modelIdxs[i][0]:modelIdxs[i+1][0]])\n\t}\n\tmethodComments := apiFileMethodStart.FindAllStringSubmatch(topMatches[0][3], -1)\n\tmethods := make([]string, len(methodComments))\n\tfor i, m := range methodComments {\n\t\tmethods[i] = strings.TrimSpace(apiFileCommentStart.ReplaceAllLiteralString(m[1], \"\"))\n\t}\n\treturn &APIFile{\n\t\tTopic: strings.TrimSpace(topMatches[0][1]),\n\t\tDescription: strings.TrimSpace(apiFileLineTrim.ReplaceAllLiteralString(top[0:modelIdxs[0][0]], \" \")),\n\t\tModelComments: models,\n\t\tMethodComments: methods,\n\t}, nil\n}", "func parseRoutesFile(routesPath, joinedPath string, validate bool) ([]*Route, *Error) {\n\tcontentBytes, err := ioutil.ReadFile(routesPath)\n\tif err != nil {\n\t\treturn nil, &Error{\n\t\t\tTitle: \"Failed to load routes file\",\n\t\t\tDescription: err.Error(),\n\t\t}\n\t}\n\treturn parseRoutes(routesPath, joinedPath, string(contentBytes), validate)\n}", "func (function *Function) Parse() (err error) {\n\tsignatureFinder := regexp.MustCompile(`(?is)CREATE(?:\\s+OR\\s+REPLACE)?\\s+FUNCTION\\s+(\\S+?)\\((.*?)\\)`)\n\tsubMatches := signatureFinder.FindStringSubmatch(function.Definition)\n\n\tif len(subMatches) < 3 {\n\t\treturn fmt.Errorf(\"Can't find a function in %s\", function.Path)\n\t}\n\n\tfunction.Name = subMatches[1]\n\n\tif function.ParseSignature {\n\t\tfunction.Signature = subMatches[2]\n\t} else {\n\t\tfunction.Signature, function.PreviousExists, err = function.previousSignature()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = function.removeDefaultFromSignature()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func Parse(f *os.File) (Source, error) {\n\tvar s scanner.Scanner\n\tvar src Source\n\ts.Init(f)\n\tfor tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {\n\t\tswitch s.TokenText() {\n\t\tcase \"!\": // macros have completely unpredictable structure, so we need\n\t\t\t// to zip past them for sanity.\n\t\t\tcollapseMacro(&s)\n\t\tcase \"#\": // attribute\n\t\t\tattName := \"#\"\n\t\t\tfor {\n\t\t\t\tc := s.Next()\n\t\t\t\tattName += string(c)\n\t\t\t\tif c == ']' {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch attName {\n\t\t\tcase \"#[cfg(test)]\":\n\t\t\t\tsrc.TestBlock = s.Pos().Line\n\t\t\tcase \"#[test]\":\n\t\t\t\tt := capTest(&s)\n\t\t\t\tsrc.Tests = append(src.Tests, t)\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\t\t// Detect trait and impl first because they can encapsulate other blocks\n\t\tcase \"trait\":\n\t\t\tsrc.Traits = append(src.Traits, capTrait(&s))\n\t\tcase \"impl\":\n\t\t\tcapImpl(&src, &s)\n\t\tcase \"enum\":\n\t\t\tsrc.Enums = append(src.Enums, capEnum(&s))\n\t\tcase \"struct\":\n\t\t\tsrc.RsStructs = append(src.RsStructs, capStruct(&s))\n\t\tcase \"fn\":\n\t\t\tfn, ubs := capFn(&s)\n\t\t\tsrc.Funcs = append(src.Funcs, fn)\n\t\t\tif len(ubs) > 0 {\n\t\t\t\tsrc.UB = append(src.UB, ubs...)\n\t\t\t}\n\t\tcase \"unsafe\":\n\t\t\tsrc.UB = append(src.UB, capUB(&s))\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn src, nil\n}", "func parseFile(file string) (data *ParseData, err error) {\n\t// Open the post file\n\tinput, openError := os.Open(file)\n\tif openError != nil {\n\t\treturn nil, openError\n\t}\n\tdefer input.Close()\n\n\t// Scan all input lines\n\tinputScanner := bufio.NewScanner(input)\n\tinputScanner.Split(bufio.ScanLines)\n\n\theader, body, headerIndex := \"\", \"\", 0\n\tfor inputScanner.Scan() {\n\t\tline := inputScanner.Text()\n\t\tswitch headerIndex {\n\t\tcase 0:\n\t\t\tif line == \"---\" {\n\t\t\t\theaderIndex = 1\n\t\t\t}\n\t\tcase 1:\n\t\t\tif line == \"---\" {\n\t\t\t\theaderIndex = 2\n\t\t\t} else {\n\t\t\t\theader += line + \"\\n\"\n\t\t\t}\n\t\tcase 2:\n\t\t\tbody += line + \"\\n\"\n\t\t}\n\t}\n\n\tdata = new(ParseData)\n\tdata.SetContent(body)\n\n\t// Decode JSON header\n\tif err := yaml.Unmarshal([]byte(header), &data); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Generate slug from file name if needed\n\tif len(data.Slug) == 0 {\n\t\tdata.Slug = strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))\n\t}\n\tdata.Slug = strings.ToLower(data.Slug)\n\treturn data, nil\n}", "func (mf Func) Process(h http.Handler) http.Handler {\n\treturn mf(h)\n}", "func OpenFileAndParse(filePath string) (*Output, error) {\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstat, err := file.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbyteCode := make([]byte, stat.Size())\n\t_, err = file.Read(byteCode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcode := string(byteCode)\n\toutput := Parse(code)\n\n\treturn output, nil\n}", "func ParseURLs(content string) []string { return parseURLsMax(content, -1) }", "func (p *Parser) Parse(ctx context.Context, url string, body io.Reader) (urls []string, errs []error) {\n\tb, err := ioutil.ReadAll(body)\n\tif err != nil {\n\t\treturn nil, []error{err}\n\t}\n\tresult, ok := p.Results[string(b)]\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\tfor _, e := range result.Errs {\n\t\terrs = append(errs, errors.New(e))\n\t}\n\treturn result.Urls, errs\n}", "func MakeFunctionReader() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tlog.Info(\"read request\")\n\t\tfunctions, err := readServices()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error getting service list: %s\\n\", err.Error())\n\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Write([]byte(err.Error()))\n\t\t\treturn\n\t\t}\n\n\t\tfunctionBytes, _ := json.Marshal(functions)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write(functionBytes)\n\t}\n}", "func ParseFile(path string) (Queries, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\treturn parseBuffer(file)\n}", "func Parse(Includes, Excludes [][]string) []byte {\n\tvar host, scheme, port, path string\n\tvar cludes [][][]string\n\n\tcludes = append(cludes, Includes)\n\tcludes = append(cludes, Excludes)\n\n\t// file containing servicenames and ports\n\tfr := File.ReadFromRoot(\"configs/known-ports.txt\", \"pkg\")\n\n\tfor i, clude := range cludes {\n\t\tfor _, item := range clude {\n\t\t\tip := regexp.MustCompile(`\\d+\\.\\d+\\.\\d+\\.\\d+`)\n\n\t\t\tif ip.MatchString(item[0]) {\n\t\t\t\tfor _, ip := range item {\n\t\t\t\t\thost := parseHost(ip)\n\t\t\t\t\tscheme = \"Any\"\n\t\t\t\t\tif i == 0 {\n\t\t\t\t\t\tadd(scheme, host, \"^(80|443)$\", path, false)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tadd(scheme, host, \"^(80|443)$\", path, true)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tscheme = strings.TrimRight(item[1], \"://\")\n\t\t\t\thost = item[2] + item[3] + item[4]\n\t\t\t\tport = strings.TrimLeft(item[6], \":\")\n\t\t\t\tpath = item[7]\n\n\t\t\t\t//fmt.Println(\"S:\" + scheme + \"H:\" + host + \"PO:\" + port + \"PA:\" + path)\n\t\t\t\tscheme, port = parseSchemeAndPort(fr, scheme, port)\n\n\t\t\t\thost = parseHost(host)\n\t\t\t\tpath = parseFile(path)\n\n\t\t\t\tif i == 0 {\n\t\t\t\t\tadd(scheme, host, port, path, false)\n\t\t\t\t} else {\n\t\t\t\t\tadd(scheme, host, port, path, true)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// scope object\n\tscope := Scope{}\n\tscope.Target.Scope.AdvancedMode = true\n\t// add include/exclude slices\n\tscope.Target.Scope.Include = incslice.Include\n\tscope.Target.Scope.Exclude = exslice.Exclude\n\n\t// parse pretty json\n\tjson, err := json.MarshalIndent(scope, \"\", \" \")\n\tif err != nil {\n\t\tfmt.Println(\"json err:\", err)\n\t}\n\treturn json\n}", "func Parse(f io.Reader) (Sections, error) {\n\ttree, err := ParseAST(f)\n\tif err != nil {\n\t\treturn Sections{}, err\n\t}\n\n\tv := NewDefaultVisitor()\n\tif err = Walk(tree, v); err != nil {\n\t\treturn Sections{}, err\n\t}\n\n\treturn v.Sections, nil\n}", "func Parse(f io.Reader) (Sections, error) {\n\ttree, err := ParseAST(f)\n\tif err != nil {\n\t\treturn Sections{}, err\n\t}\n\n\tv := NewDefaultVisitor()\n\tif err = Walk(tree, v); err != nil {\n\t\treturn Sections{}, err\n\t}\n\n\treturn v.Sections, nil\n}", "func flowFunctionRequestHandle(w http.ResponseWriter, function string) {\n\tw.Header().Set(\"Content-Type\", jsonType)\n\tfunctions, err := listFunction()\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"failed to handle request, error: %v\", err), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tfor _, functionObj := range functions {\n\t\tif functionObj.Name == function {\n\t\t\tdog, derr := getDag(function)\n\t\t\tif derr != nil {\n\t\t\t\thttp.Error(w, fmt.Sprintf(\"failed to handle request, %v\", derr), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfunctionObj.Dag = dog\n\t\t\tdata, _ := json.Marshal(functionObj)\n\t\t\tw.Write(data)\n\t\t\treturn\n\t\t}\n\t}\n\thttp.Error(w, fmt.Sprintf(\"failed to handle request, function not found\"), http.StatusInternalServerError)\n}", "func ProcessFile(readFile []string) {\n\tfor _, value := range readFile {\n\t\tinputLine := strings.Split(value, \"\\n\")\n\t\tif len(inputLine) > 0 {\n\t\t\tilString := inputLine[0]\n\t\t\twords := strings.Fields(ilString)\n\t\t\terr := processCommands(words)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"%v\\n\", err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (node *Node) HEAD(functions ...interface{}) *Handler {\n\n\thandler := &Handler{}\n\n\tif len(functions) > 0 { handler.function = functions[0].(func (req web.RequestInterface) *web.ResponseStatus) }\n\n\tnode.addHandler(\"HEAD\", handler)\n\n\treturn handler\n}", "func HandleFunc(c Checker, pattern string, h http.HandlerFunc) {\n\thttp.HandleFunc(pattern, HandlerFunc(c, h))\n}", "func (function *function) parse() (err error) {\n\tsignatureFinder := regexp.MustCompile(`(?is)CREATE(?:\\s+OR\\s+REPLACE)?\\s+FUNCTION\\s+(\\S+?)\\((.*?)\\)`)\n\tsubMatches := signatureFinder.FindStringSubmatch(function.definition)\n\n\tif len(subMatches) < 3 {\n\t\treturn fmt.Errorf(\"Can't find a function in %s\", function.path)\n\t}\n\n\tfunction.name = subMatches[1]\n\n\tif function.parseSignature {\n\t\tfunction.signature = subMatches[2]\n\t} else {\n\t\tfunction.signature, function.previousExists, err = function.previousSignature()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = function.removeDefaultFromSignature()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func ParseC(code string) (functions map[uint64]*function.Function) {\n\n\tcodeLines := strings.Split(code, \"\\n\")\n\tfunctions = make(map[uint64]*function.Function)\n\n\tvar (\n\t\tstartLine uint64\n\t\tendLine uint64\n\t\tcomment string\n\t\tfunctionContent string\n\t\tstate = commentSearch\n\t)\n\n\tfor idx, line := range codeLines {\n\t\tif strings.HasPrefix(line, \"//\") {\n\t\t\tstate = commentStart\n\t\t} else if cFuncMatch.MatchString(line) ||\n\t\t\t(strings.Contains(line, \"template\") && strings.Contains(line, \"typename\")) {\n\t\t\tif state == commentSearch {\n\t\t\t\t// If we're coming from commentSearch, that means that we didn't have a comment so we set startLine to idx\n\t\t\t\tstartLine = uint64(idx + 1)\n\t\t\t}\n\t\t\tstate = funcStart\n\t\t} else if strings.Contains(line, \"struct\") && strings.Contains(line, \"{\") {\n\t\t\tif state == commentSearch {\n\t\t\t\tstartLine = uint64(idx + 1)\n\t\t\t}\n\t\t\tstate = funcStart\n\t\t} else if strings.HasPrefix(line, \"}\") {\n\t\t\tstate = funcEnd\n\t\t} else if !(strings.HasPrefix(line, \"//\")) && state != funcStart {\n\t\t\tstate = commentSearch\n\t\t\tcomment = \"\"\n\t\t}\n\n\t\tswitch state {\n\t\tcase commentSearch:\n\t\t\tcontinue\n\t\tcase commentStart:\n\t\t\tstartLine = uint64(idx + 1)\n\t\t\tcomment += fmt.Sprintf(\"%s\\n\", line)\n\t\tcase funcStart:\n\t\t\tfunctionContent += fmt.Sprintf(\"%v\\n\", line)\n\t\tcase funcEnd:\n\t\t\tendLine = uint64(idx + 1)\n\t\t\t// add the closing brace\n\t\t\tfunctionContent += fmt.Sprintf(\"%v\\n\", line)\n\t\t\t// create a new function object with the information we got\n\t\t\tf := function.NewFunction(comment, functionContent, \"noNameYet\", 0, startLine, endLine)\n\t\t\t// add that to our map\n\t\t\tfunctions[uint64(f.FuncID)] = f\n\t\t\t// reset our state machine\n\t\t\tstartLine = 0\n\t\t\tcomment = \"\"\n\t\t\tfunctionContent = \"\"\n\t\t\tstate = commentSearch\n\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn\n}", "func (hook Webhook) Parse(r *http.Request, events ...Event) (interface{}, error) {\n\tdefer func() {\n\t\t_, _ = io.Copy(ioutil.Discard, r.Body)\n\t\t_ = r.Body.Close()\n\t}()\n\n\tif len(events) == 0 {\n\t\treturn nil, ErrEventNotSpecifiedToParse\n\t}\n\tif r.Method != http.MethodPost {\n\t\treturn nil, ErrInvalidHTTPMethod\n\t}\n\n\t// If we have a Secret set, we should check the MAC\n\tif len(hook.secret) > 0 {\n\t\tsignature := r.Header.Get(\"X-Gitlab-Token\")\n\t\tif signature != hook.secret {\n\t\t\treturn nil, ErrGitLabTokenVerificationFailed\n\t\t}\n\t}\n\n\tevent := r.Header.Get(\"X-Gitlab-Event\")\n\tif len(event) == 0 {\n\t\treturn nil, ErrMissingGitLabEventHeader\n\t}\n\n\tgitLabEvent := Event(event)\n\n\tpayload, err := ioutil.ReadAll(r.Body)\n\tif err != nil || len(payload) == 0 {\n\t\treturn nil, ErrParsingPayload\n\t}\n\n\treturn eventParsing(gitLabEvent, events, payload)\n}", "func (t *Target) parse(fn string) error {\n\tdata, err := ioutil.ReadFile(fn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconnections := connectionset{}\n\txml.Unmarshal(data, &connections)\n\tfor _, conn := range connections.Conns {\n\t\tif conn.Id == t.Name {\n\t\t\tt.dest = strings.Replace(conn.URI, \"ipbusudp-2.0://\", \"\", 1)\n\t\t\t//ns := nodes{}\n\t\t\taddr := strings.Replace(conn.Address, \"file://\", \"\", 1)\n\t\t\tif err := t.parseregfile(addr, \"\", uint32(0)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn error(nil)\n}", "func parseFile(path string) ([]Hday, error) {\n\t// load file content\n\tc, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar data []Hday\n\ts := bufio.NewScanner(bytes.NewReader(c))\n\tfor s.Scan() {\n\t\th, err := NewHday(s.Text())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdata = append(data, h)\n\t}\n\treturn data, s.Err()\n}", "func parseFile(filename string, src []byte, searchpos int) (func(*token.FileSet, string) (*ast.File, error), chan ast.Node) {\n\tfstat, fstatErr := os.Stat(filename)\n\tresult := make(chan ast.Node, 1)\n\treturn func(fset *token.FileSet, fname string) (*ast.File, error) {\n\t\tvar filedata []byte\n\t\tisInputFile := false\n\t\tif filename == fname {\n\t\t\tisInputFile = true\n\t\t} else if fstatErr != nil {\n\t\t\tisInputFile = false\n\t\t} else if s, err := os.Stat(fname); err == nil {\n\t\t\tisInputFile = os.SameFile(fstat, s)\n\t\t}\n\t\tif isInputFile && src != nil {\n\t\t\tfiledata = src\n\t\t} else {\n\t\t\tvar err error\n\t\t\tif filedata, err = ioutil.ReadFile(fname); err != nil {\n\t\t\t\tfail(\"cannot read %s: %v\", fname, err)\n\t\t\t}\n\t\t}\n\t\tfile, err := parser.ParseFile(fset, fname, filedata, 0)\n\t\tif file == nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar keepFunc *ast.FuncDecl\n\t\tif isInputFile {\n\t\t\tpos := file.Pos() + token.Pos(searchpos)\n\t\t\tif pos > file.End() {\n\t\t\t\treturn file, fmt.Errorf(\"cursor %d is beyond end of file %s (%d)\", searchpos, fname, file.End()-file.Pos())\n\t\t\t}\n\t\t\tpath, _ := astutil.PathEnclosingInterval(file, pos, pos)\n\t\t\tif len(path) < 1 {\n\t\t\t\treturn nil, fmt.Errorf(\"Offest was not a valid token\")\n\t\t\t}\n\t\t\t// report the base node we matched\n\t\t\tresult <- path[0]\n\t\t\t// if we are inside a function, we need to retain that function body\n\t\t\t// start from the top not the bottom\n\t\t\tfor i := len(path) - 1; i >= 0; i-- {\n\t\t\t\tif f, ok := path[i].(*ast.FuncDecl); ok {\n\t\t\t\t\tkeepFunc = f\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// and drop all function bodies that are not relevant so they don't get\n\t\t// type checked\n\t\tfor _, decl := range file.Decls {\n\t\t\tif f, ok := decl.(*ast.FuncDecl); ok && f != keepFunc {\n\t\t\t\tf.Body = nil\n\t\t\t}\n\t\t}\n\t\treturn file, err\n\t}, result\n}", "func ParseEndpointFile() (*Service, error) {\n\tfile := defaultEndpointFile()\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar s Service\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &s, nil\n}", "func hookParseType(target string) string {\n\tif strings.HasPrefix(target, \"http\") {\n\t\treturn \"web\"\n\t} else {\n\t\treturn \"script\"\n\t}\n}", "func MapHandler(pathsToUrls map[string]string) func(string) (string, bool) {\n\treturn func(path string) (string, bool) {\n\t\turl, exists := pathsToUrls[path]\n\t\tfmt.Println(pathsToUrls[path])\n\t\treturn url, exists\n\t}\n}", "func ParseFile(filename string) (interface{}, error) {\n\tvar (\n\t\tbytes []byte\n\t\terr error\n\t)\n\tif bytes, err = ioutil.ReadFile(filename); err != nil {\n\t\treturn nil, err\n\t}\n\treturn Parse(bytes)\n}", "func ParseFile(filePath string) (b []byte, result map[string]interface{}) {\n\tb, _ = ioutil.ReadFile(filePath)\n\t_ = json.Unmarshal([]byte(b), &result)\n\treturn b, result\n}", "func parseLib(ctx *checkContext, apiName, apiVersion string) error {\n\tfname := filepath.Join(ctx.libDir, clientLibAPIRoot, apiName+\"_\"+strings.Replace(apiVersion, \".\", \"_\", -1), \"service.rb\")\n\tfile, err := ctx.fs.ReadFile(fname)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar currentParams []langutil.MethodParam\n\n\t// Parse the function comment and definition, which looks like:\n\t//\n\t// # Sets the access control policy on the specified resource. Replaces any\n\t// # existing policy.\n\t// # @param [String] resource\n\t// # REQUIRED: The resource for which the policy is being specified. `resource` is\n\t// # usually specified as a path, such as `projects/*project*/zones/*zone*/disks/*\n\t// # disk*`. The format for the path specified in this value is resource specific\n\t// # and is specified in the `setIamPolicy` documentation.\n\t// # @param [Google::Apis::PubsubV1::SetIamPolicyRequest] set_iam_policy_request_object\n\t// # @param [String] fields\n\t// # Selector specifying which fields to include in a partial response.\n\t// # @param [String] quota_user\n\t// # Available to use for quota purposes for server-side applications. Can be any\n\t// # arbitrary string assigned to a user, but should not exceed 40 characters.\n\t// # @param [Google::Apis::RequestOptions] options\n\t// # Request-specific options\n\t// #\n\t// # @yield [result, err] Result & error if block supplied\n\t// # @yieldparam result [Google::Apis::PubsubV1::Policy] parsed result object\n\t// # @yieldparam err [StandardError] error object if request failed\n\t// #\n\t// # @return [Google::Apis::PubsubV1::Policy]\n\t// #\n\t// # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried\n\t// # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification\n\t// # @raise [Google::Apis::AuthorizationError] Authorization is required\n\t// def set_topic_iam_policy(resource, set_iam_policy_request_object = nil, fields: nil, quota_user: nil, options: nil, &block)\n\tfor len(file) > 0 {\n\t\tif match := paramRegexp.FindSubmatch(file); len(match) > 0 {\n\t\t\tcurrentParams = append(currentParams, langutil.MethodParam{\n\t\t\t\tName: string(match[2]),\n\t\t\t\tType: string(genericRegexp.ReplaceAll(match[1], nil)),\n\t\t\t})\n\t\t\tfile = file[len(match[0]):]\n\t\t} else if match = methodRegexp.FindSubmatch(file); len(match) > 0 && !bytes.Equal(match[1], skipMethodName) {\n\t\t\tposParams, err := positionalParams(string(match[2]), currentParams)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfriendlyID := langutil.MethodID{\n\t\t\t\tAPIName: apiName, APIVersion: apiVersion, FragmentName: string(match[1]),\n\t\t\t}\n\t\t\tdiscoID, ok := ctx.methodRename[friendlyID]\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"rename not found: %v\", friendlyID)\n\t\t\t}\n\t\t\tctx.MethodParamSets[discoID] = posParams\n\t\t\tcurrentParams = currentParams[:0]\n\t\t\tfile = file[len(match[0]):]\n\t\t}\n\t\tif p := bytes.IndexRune(file, '\\n'); p >= 0 {\n\t\t\tfile = file[p+1:]\n\t\t} else {\n\t\t\tfile = nil\n\t\t}\n\t\tfile = bytes.TrimLeftFunc(file, unicode.IsSpace)\n\t}\n\treturn nil\n}", "func (ri *Interpreter) Parse(r io.ReadSeeker, scriptIdentifer string) (*parser.File, error) {\n\tfile := parser.NewFile(scriptIdentifer, ri.job)\n\tif err := file.Parse(r); err != nil {\n\t\treturn nil, err\n\t}\n\tif ri.job.RunOptions.Debug == ui.DebugAll {\n\t\tri.job.UI.Logf(\"***Parsing finished: %d table(s) found\\n\", file.TableCount())\n\t\tfor i, t := range file.Tables() {\n\t\t\tri.job.UI.Logf(\"****Contents of table %d\\n%v\\n\", i+1, t)\n\t\t}\n\t}\n\treturn file, nil\n}", "func NewHandler(f func(*Message), path string, description ...string) *Handler {\n\thandler := &Handler{f: f}\n\thandler.variables, handler.pattern = parse(path)\n\tif len(description) > 0 {\n\t\thandler.description = description[0]\n\t}\n\treturn handler\n}", "func ParseFile(path string) (*ParsedFile, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\treturn Parse(file)\n}", "func ExampleParseFile() {\n\tsessions, err := parser.ParseFile(\"foo.saz\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"%d network sessions found.\", len(sessions))\n\t// Output: 42 network sessions found.\n}", "func (r *namespaceImpl) Handlers(p schema.NamespaceHandlersFieldResolverParams) (interface{}, error) {\n\tres := newOffsetContainer(p.Args.Offset, p.Args.Limit)\n\tnsp := p.Source.(*corev3.Namespace)\n\n\t// finds all records\n\tresults, err := loadHandlers(p.Context, nsp.Metadata.Name)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\n\t// filter\n\tmatches, err := filter.Compile(p.Args.Filters, HandlerFilters(), corev3.HandlerFields)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\tfilteredResults := make([]*corev2.Handler, 0, len(results))\n\tfor i := range results {\n\t\tif matches(results[i]) {\n\t\t\tfilteredResults = append(filteredResults, results[i])\n\t\t}\n\t}\n\n\t// sort\n\tsort.Sort(corev2.SortHandlersByName(\n\t\tfilteredResults,\n\t\tp.Args.OrderBy == schema.HandlerListOrders.NAME,\n\t))\n\n\t// paginate\n\tl, h := clampSlice(p.Args.Offset, p.Args.Offset+p.Args.Limit, len(filteredResults))\n\tres.Nodes = filteredResults[l:h]\n\tres.PageInfo.totalCount = len(filteredResults)\n\treturn res, nil\n}", "func (parser *SourcePathParser) Parse(request *http.Request, parameters imageserver.Parameters) error {\n\tparameters.Set(\"source\", request.URL.Path)\n\treturn nil\n}", "func (p *Parser) Parse(srcPath string, files []models.Path) (*Result, error) {\n\tb, err := p.readFile(srcPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfset := token.NewFileSet()\n\tf, err := p.parseFile(fset, srcPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfs, err := p.parseFiles(fset, f, files)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Result{\n\t\tHeader: &models.Header{\n\t\t\tComments: parseComment(f, f.Package),\n\t\t\tPackage: f.Name.String(),\n\t\t\tImports: parseImports(f.Imports),\n\t\t\tCode: goCode(b, f),\n\t\t},\n\t\tFuncs: p.parseFunctions(fset, f, fs),\n\t}, nil\n}", "func GetPublicFunctions(pkg, filePath string) ([]*types.Type, error) {\n\tbuilder := go2idlparser.New()\n\tdata, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := builder.AddFile(pkg, filePath, data); err != nil {\n\t\treturn nil, err\n\t}\n\tuniverse, err := builder.FindTypes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar functions []*types.Type\n\n\t// Create the AST by parsing src.\n\tfset := token.NewFileSet() // positions are relative to fset\n\tf, err := parser.ParseFile(fset, filePath, nil, 0)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed parse file to list functions: %v\", err)\n\t}\n\n\t// Inspect the AST and print all identifiers and literals.\n\tast.Inspect(f, func(n ast.Node) bool {\n\t\tvar s string\n\t\tswitch x := n.(type) {\n\t\tcase *ast.FuncDecl:\n\t\t\ts = x.Name.Name\n\t\t\t// It's a function (not method), and is public, record it.\n\t\t\tif x.Recv == nil && isPublic(s) {\n\t\t\t\tfunctions = append(functions, universe[pkg].Function(x.Name.Name))\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\treturn functions, nil\n}", "func GetFileHandler(w http.ResponseWriter, r *http.Request) {\n\thttpSession, _ := session.HTTPSession.Get(r, session.CookieName)\n\tif httpSession.IsNew {\n\t\thttp.Error(w, \"Forbidden\", http.StatusForbidden)\n\n\t\treturn\n\t}\n\tuid := httpSession.Values[\"uid\"].(string)\n\n\tresult := gulu.Ret.NewResult()\n\tdefer gulu.Ret.RetResult(w, r, result)\n\n\tvar args map[string]interface{}\n\n\tif err := json.NewDecoder(r.Body).Decode(&args); err != nil {\n\t\tlogger.Error(err)\n\t\tresult.Code = -1\n\n\t\treturn\n\t}\n\n\tpath := args[\"path\"].(string)\n\n\tif !gulu.Go.IsAPI(path) && !session.CanAccess(uid, path) {\n\t\thttp.Error(w, \"Forbidden\", http.StatusForbidden)\n\n\t\treturn\n\t}\n\n\tsize := gulu.File.GetFileSize(path)\n\tif size > 5242880 { // 5M\n\t\tresult.Code = -1\n\t\tresult.Msg = \"This file is too large to open :(\"\n\n\t\treturn\n\t}\n\n\tdata := map[string]interface{}{}\n\tresult.Data = &data\n\n\tbuf, _ := ioutil.ReadFile(path)\n\n\textension := filepath.Ext(path)\n\n\tif gulu.File.IsImg(extension) {\n\t\t// image file will be open in a browser tab\n\n\t\tdata[\"mode\"] = \"img\"\n\n\t\tuserId := conf.GetOwner(path)\n\t\tif \"\" == userId {\n\t\t\tlogger.Warnf(\"The path [%s] has no owner\", path)\n\t\t\tdata[\"path\"] = \"\"\n\n\t\t\treturn\n\t\t}\n\n\t\tuser := conf.GetUser(uid)\n\n\t\tdata[\"path\"] = \"/workspace/\" + user.Name + \"/\" + strings.Replace(path, user.WorkspacePath(), \"\", 1)\n\n\t\treturn\n\t}\n\n\tcontent := string(buf)\n\n\tif gulu.File.IsBinary(content) {\n\t\tresult.Code = -1\n\t\tresult.Msg = \"Can't open a binary file :(\"\n\t} else {\n\t\tdata[\"content\"] = content\n\t\tdata[\"path\"] = path\n\t}\n}", "func parseFile(t *testing.T, f string, s interface{}) {\n\tread, err := os.Open(f)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = json.NewDecoder(read).Decode(&s)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = read.Close()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func ParseFile(file string) (*StateMachine, error) {\n\traw, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tjson_sm, err := FromJSON(raw)\n\treturn json_sm, err\n}", "func (node *Node) GET(functionKeys ...string) *Handler {\n\n\th := &Handler{}\n\t\n\tif len(functionKeys) > 0 {\n\t\th.functionKey = functionKeys[0]\n\t}\n\n\tnode.addHandler(\"GET\", h)\n\n\treturn h\n}", "func Parse(file string) error {\n\tonce.Do(func() {\n\t\t// Reading the flags\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error in ReadFile:\", err)\n\t\t}\n\t\tif err := json.Unmarshal(data, &Cfg); err != nil {\n\t\t\tlog.Println(\"Error in Unmarshal:\", err)\n\t\t}\n\t})\n\treturn nil\n}", "func (s *HTTPServer) handler(enableDebug bool) http.Handler {\n\tmux := http.NewServeMux()\n\n\t// handleFuncMetrics takes the given pattern and handler and wraps to produce\n\t// metrics based on the pattern and request.\n\thandleFuncMetrics := func(pattern string, handler http.HandlerFunc) {\n\t\t// Get the parts of the pattern. We omit any initial empty for the\n\t\t// leading slash, and put an underscore as a \"thing\" placeholder if we\n\t\t// see a trailing slash, which means the part after is parsed. This lets\n\t\t// us distinguish from things like /v1/query and /v1/query/<query id>.\n\t\tvar parts []string\n\t\tfor i, part := range strings.Split(pattern, \"/\") {\n\t\t\tif part == \"\" {\n\t\t\t\tif i == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tpart = \"_\"\n\t\t\t}\n\t\t\tparts = append(parts, part)\n\t\t}\n\n\t\t// Register the wrapper, which will close over the expensive-to-compute\n\t\t// parts from above.\n\t\t// TODO (kyhavlov): Convert this to utilize metric labels in a major release\n\t\twrapper := func(resp http.ResponseWriter, req *http.Request) {\n\t\t\tstart := time.Now()\n\t\t\thandler(resp, req)\n\t\t\tkey := append([]string{\"http\", req.Method}, parts...)\n\t\t\tmetrics.MeasureSince(key, start)\n\t\t}\n\n\t\tgzipWrapper, _ := gziphandler.GzipHandlerWithOpts(gziphandler.MinSize(0))\n\t\tgzipHandler := gzipWrapper(http.HandlerFunc(wrapper))\n\t\tmux.Handle(pattern, gzipHandler)\n\t}\n\n\t// handlePProf takes the given pattern and pprof handler\n\t// and wraps it to add authorization and metrics\n\thandlePProf := func(pattern string, handler http.HandlerFunc) {\n\t\twrapper := func(resp http.ResponseWriter, req *http.Request) {\n\t\t\tvar token string\n\t\t\ts.parseToken(req, &token)\n\n\t\t\trule, err := s.agent.resolveToken(token)\n\t\t\tif err != nil {\n\t\t\t\tresp.WriteHeader(http.StatusForbidden)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// If enableDebug is not set, and ACLs are disabled, write\n\t\t\t// an unauthorized response\n\t\t\tif !enableDebug {\n\t\t\t\tif s.checkACLDisabled(resp, req) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If the token provided does not have the necessary permissions,\n\t\t\t// write a forbidden response\n\t\t\tif rule != nil && !rule.OperatorRead() {\n\t\t\t\tresp.WriteHeader(http.StatusForbidden)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Call the pprof handler\n\t\t\thandler(resp, req)\n\t\t}\n\n\t\thandleFuncMetrics(pattern, http.HandlerFunc(wrapper))\n\t}\n\n\tmux.HandleFunc(\"/\", s.Index)\n\tfor pattern, fn := range endpoints {\n\t\tthisFn := fn\n\t\tmethods, _ := allowedMethods[pattern]\n\t\tbound := func(resp http.ResponseWriter, req *http.Request) (interface{}, error) {\n\t\t\treturn thisFn(s, resp, req)\n\t\t}\n\t\thandleFuncMetrics(pattern, s.wrap(bound, methods))\n\t}\n\n\t// Register wrapped pprof handlers\n\thandlePProf(\"/debug/pprof/\", pprof.Index)\n\thandlePProf(\"/debug/pprof/cmdline\", pprof.Cmdline)\n\thandlePProf(\"/debug/pprof/profile\", pprof.Profile)\n\thandlePProf(\"/debug/pprof/symbol\", pprof.Symbol)\n\thandlePProf(\"/debug/pprof/trace\", pprof.Trace)\n\n\tif s.IsUIEnabled() {\n\t\tlegacy_ui, err := strconv.ParseBool(os.Getenv(\"CONSUL_UI_LEGACY\"))\n\t\tif err != nil {\n\t\t\tlegacy_ui = false\n\t\t}\n\t\tvar uifs http.FileSystem\n\n\t\t// Use the custom UI dir if provided.\n\t\tif s.agent.config.UIDir != \"\" {\n\t\t\tuifs = http.Dir(s.agent.config.UIDir)\n\t\t} else {\n\t\t\tfs := assetFS()\n\n\t\t\tif legacy_ui {\n\t\t\t\tfs.Prefix += \"/v1/\"\n\t\t\t} else {\n\t\t\t\tfs.Prefix += \"/v2/\"\n\t\t\t}\n\t\t\tuifs = fs\n\t\t}\n\n\t\tif !legacy_ui {\n\t\t\tuifs = &redirectFS{fs: uifs}\n\t\t}\n\n\t\tmux.Handle(\"/robots.txt\", http.FileServer(uifs))\n\t\tmux.Handle(\"/ui/\", http.StripPrefix(\"/ui/\", http.FileServer(uifs)))\n\t}\n\n\t// Wrap the whole mux with a handler that bans URLs with non-printable\n\t// characters, unless disabled explicitly to deal with old keys that fail this\n\t// check.\n\th := cleanhttp.PrintablePathCheckHandler(mux, nil)\n\tif s.agent.config.DisableHTTPUnprintableCharFilter {\n\t\th = mux\n\t}\n\treturn &wrappedMux{\n\t\tmux: mux,\n\t\thandler: h,\n\t}\n}", "func ParseFunction(s string) (prefix string, funcname string, f []string, r []string, err error) {\n\tdefer func() {\n\t\tif len(f) == 1 && f[0] == \"void\" {\n\t\t\tf = nil\n\t\t}\n\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"cannot parse function '%s' : %v\", s, err)\n\t\t} else {\n\t\t\tprefix = strings.TrimSpace(prefix)\n\t\t\tfuncname = strings.TrimSpace(funcname)\n\t\t\tfor i := range r {\n\t\t\t\tr[i] = strings.TrimSpace(r[i])\n\t\t\t}\n\t\t\tfor i := range f {\n\t\t\t\tf[i] = strings.TrimSpace(f[i])\n\t\t\t}\n\t\t}\n\t}()\n\n\t// remove specific attribute for function longjmp\n\ts = strings.Replace(s, \"__attribute__((noreturn))\", \"\", -1)\n\n\ts = strings.TrimSpace(s)\n\tif !IsFunction(s) {\n\t\terr = fmt.Errorf(\"is not function : %s\", s)\n\t\treturn\n\t}\n\tvar returns string\n\tvar arguments string\n\t{\n\t\t// Example of function types :\n\t\t// int (*)(int, float)\n\t\t// int (int, float)\n\t\t// int (*)(int (*)(int))\n\t\t// void (*(*)(int *, void *, const char *))(void)\n\t\tif s[len(s)-1] != ')' {\n\t\t\terr = fmt.Errorf(\"function type |%s| haven't last symbol ')'\", s)\n\t\t\treturn\n\t\t}\n\t\tcounter := 1\n\t\tvar pos int\n\t\tfor i := len(s) - 2; i >= 0; i-- {\n\t\t\tif i == 0 {\n\t\t\t\terr = fmt.Errorf(\"don't found '(' in type : %s\", s)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif s[i] == ')' {\n\t\t\t\tcounter++\n\t\t\t}\n\t\t\tif s[i] == '(' {\n\t\t\t\tcounter--\n\t\t\t}\n\t\t\tif counter == 0 {\n\t\t\t\tpos = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// s[:pos] = `speed_t cfgetospeed`\n\t\tif unicode.IsNumber(rune(s[pos-1])) || unicode.IsLetter(rune(s[pos-1])) {\n\t\t\tfor i := pos - 1; i >= 0; i-- {\n\t\t\t\tif s[i] == ' ' {\n\t\t\t\t\tfuncname = s[i+1 : pos]\n\t\t\t\t\treturns = strings.TrimSpace(s[:i])\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturns = strings.TrimSpace(s[:pos])\n\t\t}\n\t\targuments = strings.TrimSpace(s[pos:])\n\t}\n\tif arguments == \"\" {\n\t\terr = fmt.Errorf(\"cannot parse (right part is nil) : %v\", s)\n\t\treturn\n\t}\n\t// separate fields of arguments\n\t{\n\t\tpos := 1\n\t\tcounter := 0\n\t\tfor i := 1; i < len(arguments)-1; i++ {\n\t\t\tif arguments[i] == '(' {\n\t\t\t\tcounter++\n\t\t\t}\n\t\t\tif arguments[i] == ')' {\n\t\t\t\tcounter--\n\t\t\t}\n\t\t\tif counter == 0 && arguments[i] == ',' {\n\t\t\t\tf = append(f, strings.TrimSpace(arguments[pos:i]))\n\t\t\t\tpos = i + 1\n\t\t\t}\n\t\t}\n\t\tf = append(f, strings.TrimSpace(arguments[pos:len(arguments)-1]))\n\t}\n\n\t// returns\n\t// Example: __ssize_t\n\tif returns[len(returns)-1] != ')' {\n\t\tr = append(r, returns)\n\t\treturn\n\t}\n\n\t// Example: void ( *(*)(int *, void *, char *))\n\t// ------- --------------------------- return type\n\t// == prefix\n\t// ++++++++++++++++++++++++++++++ block\n\t// return type : void (*)(int *, void *, char *)\n\t// prefix : *\n\t// Find the block\n\tvar counter int\n\tvar position int\n\tfor i := len(returns) - 1; i >= 0; i-- {\n\t\tif returns[i] == ')' {\n\t\t\tcounter++\n\t\t}\n\t\tif returns[i] == '(' {\n\t\t\tcounter--\n\t\t}\n\t\tif counter == 0 {\n\t\t\tposition = i\n\t\t\tbreak\n\t\t}\n\t}\n\tblock := string([]byte(returns[position:]))\n\treturns = returns[:position]\n\n\t// Examples returns:\n\t// int (*)\n\t// char *(*)\n\t// block is : (*)\n\tif block == \"(*)\" {\n\t\tr = append(r, returns)\n\t\treturn\n\t}\n\n\tindex := strings.Index(block, \"(*)\")\n\tif index < 0 {\n\t\tif strings.Count(block, \"(\") == 1 {\n\t\t\t// Examples returns:\n\t\t\t// int ( * [2])\n\t\t\t// ------ return type\n\t\t\t// ====== prefix\n\t\t\t// ++++++++ block\n\t\t\tbBlock := []byte(block)\n\t\t\tfor i := 0; i < len(bBlock); i++ {\n\t\t\t\tswitch bBlock[i] {\n\t\t\t\tcase '(', ')':\n\t\t\t\t\tbBlock[i] = ' '\n\t\t\t\t}\n\t\t\t}\n\t\t\tbBlock = bytes.Replace(bBlock, []byte(\"*\"), []byte(\"\"), 1)\n\t\t\tprefix = string(bBlock)\n\t\t\tr = append(r, returns)\n\t\t\treturn\n\t\t}\n\t\t// void (*(int *, void *, const char *))\n\t\t// ++++++++++++++++++++++++++++++++ block\n\t\tblock = block[1 : len(block)-1]\n\t\tindex := strings.Index(block, \"(\")\n\t\tif index < 0 {\n\t\t\terr = fmt.Errorf(\"cannot found '(' in block\")\n\t\t\treturn\n\t\t}\n\t\treturns = returns + block[index:]\n\t\tprefix = block[:index]\n\t\tif strings.Contains(prefix, \"*\") {\n\t\t\tprefix = strings.Replace(prefix, \"*\", \"\", 1)\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"undefined situation\")\n\t\t\treturn\n\t\t}\n\t\tr = append(r, returns)\n\t\treturn\n\t}\n\tif len(block)-1 > index+3 && block[index+3] == '(' {\n\t\t// Examples returns:\n\t\t// void ( *(*)(int *, void *, char *))\n\t\t// ++++++++++++++++++++++++++++++ block\n\t\t// ^^ check this\n\t\tblock = strings.Replace(block, \"(*)\", \"\", 1)\n\t\tblock = block[1 : len(block)-1]\n\t\tindex := strings.Index(block, \"(\")\n\t\tif index < 0 {\n\t\t\terr = fmt.Errorf(\"cannot found '(' in block\")\n\t\t\treturn\n\t\t}\n\n\t\treturns = returns + block[index:]\n\t\t// example of block[:index]\n\t\t// `*signal`\n\t\t// `* signal`\n\t\tif pr := strings.TrimSpace(block[:index]); unicode.IsLetter(rune(pr[len(pr)-1])) ||\n\t\t\tunicode.IsNumber(rune(pr[len(pr)-1])) {\n\t\t\tpr = strings.Replace(pr, \"*\", \" * \", -1)\n\t\t\tfor i := len(pr) - 1; i >= 0; i-- {\n\t\t\t\tif unicode.IsLetter(rune(pr[i])) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif unicode.IsNumber(rune(pr[i])) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tprefix = pr[:i]\n\t\t\t\tfuncname = pr[i:]\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\tprefix = block[:index]\n\t\t}\n\n\t\tr = append(r, returns)\n\t\treturn\n\t}\n\n\t// Examples returns:\n\t// int ( *( *(*)))\n\t// ----- return type\n\t// ========= prefix\n\t// +++++++++++ block\n\tbBlock := []byte(block)\n\tfor i := 0; i < len(bBlock); i++ {\n\t\tswitch bBlock[i] {\n\t\tcase '(', ')':\n\t\t\tbBlock[i] = ' '\n\t\t}\n\t}\n\tbBlock = bytes.Replace(bBlock, []byte(\"*\"), []byte(\"\"), 1)\n\tprefix = string(bBlock)\n\tr = append(r, returns)\n\n\treturn\n}", "func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))", "func ParseAndCallUpdateFunc(ctx context.Context, filePath string, updateFunc createOrUpdateFunc) error {\n\tjsonFile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not open file\")\n\t}\n\tdefer func() {\n\t\terr := jsonFile.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(errors.Wrap(err, \"could not close the file\"))\n\t\t}\n\t}()\n\n\tdecoder := json.NewDecoder(jsonFile)\n\tt, err := decoder.Token()\n\tif delim, ok := t.(json.Delim); !ok || delim != '{' {\n\t\treturn errors.New(fmt.Sprintf(\"expected first token to be \\\"{\\\", got %s \", delim))\n\t}\n\tfor decoder.More() {\n\t\ttoken, err := decoder.Token()\n\t\ttokenStr, ok := token.(string)\n\t\tif !ok && tokenStr != strings.ToUpper(tokenStr) {\n\t\t\treturn errors.New(\"token must be an uppercase string\")\n\t\t}\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to get json token\")\n\t\t}\n\n\t\tfor decoder.More() {\n\t\t\tport := &pb.Port{}\n\t\t\terr = decoder.Decode(port)\n\t\t\tif err != nil {\n\t\t\t\tif err.Error() == \"not at beginning of value\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\treturn errors.Wrap(err, \"could not decode data\")\n\t\t\t}\n\t\t\t_, err := updateFunc(ctx, port)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to call updateFunc\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (trh *taskRestartHandler) Parse(ctx context.Context, r *http.Request) error {\n\tprojCtx := MustHaveProjectContext(ctx)\n\tif projCtx.Task == nil {\n\t\treturn gimlet.ErrorResponse{\n\t\t\tMessage: \"task not found\",\n\t\t\tStatusCode: http.StatusNotFound,\n\t\t}\n\t}\n\tif projCtx.ProjectRef == nil {\n\t\treturn gimlet.ErrorResponse{\n\t\t\tMessage: \"project not found\",\n\t\t\tStatusCode: http.StatusNotFound,\n\t\t}\n\t}\n\ttrh.taskId = projCtx.Task.Id\n\tu := MustHaveUser(ctx)\n\ttrh.username = u.DisplayName()\n\n\tb, err := io.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"reading body\")\n\t}\n\tif len(b) > 0 {\n\t\tif err := json.Unmarshal(b, trh); err != nil {\n\t\t\treturn errors.Wrapf(err, \"parsing request's body as JSON for following task ID: '%s'.\", trh.taskId)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (p *Proxy) Handler() http.Handler {\n\tmux := goji.NewMux()\n\n\tmux.HandleFuncC(pat.Get(\"/healthcheck\"), func(c context.Context, w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"ok\\n\"))\n\t})\n\n\tmux.Handle(pat.Post(\"/import\"), handleProxy(p))\n\n\tmux.Handle(pat.Get(\"/debug/pprof/cmdline\"), http.HandlerFunc(pprof.Cmdline))\n\tmux.Handle(pat.Get(\"/debug/pprof/profile\"), http.HandlerFunc(pprof.Profile))\n\tmux.Handle(pat.Get(\"/debug/pprof/symbol\"), http.HandlerFunc(pprof.Symbol))\n\tmux.Handle(pat.Get(\"/debug/pprof/trace\"), http.HandlerFunc(pprof.Trace))\n\t// TODO match without trailing slash as well\n\tmux.Handle(pat.Get(\"/debug/pprof/*\"), http.HandlerFunc(pprof.Index))\n\n\treturn mux\n}", "func HttpHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hi there, I love %s!\", r.URL.Path[1:])\n\tlog.Printf(\"handling... %s\", r.URL.Path[1:])\n}", "func (m* Manager) GetHandler(w http.ResponseWriter, r *http.Request) {\n\tr.ParseForm()\n\tfuncName := r.FormValue(\"funcName\")\n\n\tres, err := m.platformManager.GetFunction(funcName)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tjsonRet, err := json.Marshal(res)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tw.Header().Add(\"Content-Type\", \"application/json;charset=utf-8\")\n\tw.Write(jsonRet)\n\treturn\n}", "func ParseFile(fpath string) (*ast.Table, error) {\n\tcontents, err := ioutil.ReadFile(fpath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn toml.Parse(contents)\n}", "func parseFile(path string, data []byte) []*resource {\n\tchunks := bytes.Split(data, []byte(\"\\n---\\n\"))\n\tresources := make([]*resource, 0, len(chunks))\n\tfor i, chunk := range chunks {\n\t\tchunk = bytes.TrimSpace(chunk)\n\t\tif len(chunk) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tr, err := ParseChunk(chunk)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error processing %s[%d]: %v\", path, i, err)\n\t\t\tcontinue\n\t\t}\n\t\tif r == nil {\n\t\t\tcontinue\n\t\t}\n\t\tresources = append(resources, &resource{BackEndResource: r, sha: sha1.Sum(chunk)})\n\t}\n\treturn resources\n}", "func setuphandlers() {\n\thttp.HandleFunc(\"/\", rootHandler)\n\thttp.HandleFunc(\"/status\", statusHandler)\n\thttp.HandleFunc(\"/stats\", statsHandler)\n\thttp.HandleFunc(\"/request\", requestHandler)\n}", "func (p *Parser) ParseFile(file string) ([]builder.APITest, error) {\n\ttests := []builder.APITest{}\n\n\tcontents, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn tests, err\n\t}\n\n\t// TODO: It would be cool if we could detect extra fields and warn the user about them\n\terr = json.Unmarshal(contents, &tests)\n\tif err != nil {\n\t\treturn tests, err\n\t}\n\n\tfor i, test := range tests {\n\t\tif tests[i], err = p.validate(test); err != nil {\n\t\t\treturn tests, fmt.Errorf(\"error in test #%v: %v\", i+1, err)\n\t\t}\n\t}\n\n\treturn tests, nil\n}", "func (h *distroIDGetSetupHandler) Parse(ctx context.Context, r *http.Request) error {\n\th.distroID = gimlet.GetVars(r)[\"distro_id\"]\n\n\treturn nil\n}", "func Parse(filename string) error {\n\n\tf, err := os.Open(filename)\n\n\tif err != nil {\n\t\treturn err\n\n\t}\n\n\tin := bufio.NewReader(f)\n\n\tvar l Lex\n\tl.in = in\n\tl.LineNumber = 0\n\tl.ColNumber = 1\n\n\tparser := parser{filename: filename, lex: &l}\n\n\t//\tl.error = parser.error\n\n\treturn parser.parse()\n\n}", "func (cb *Callback) Parse(req *http.Request) error {\n\tnumMediaString := req.PostFormValue(\"NumMedia\")\n\tnumMedia, err := strconv.Atoi(numMediaString)\n\tif err != nil && numMediaString != \"\" {\n\t\treturn fmt.Errorf(\"Error parsing NumMedia => %s\", err.Error())\n\t}\n\n\t// creates an array of MediaReference Contents (typically empty)\n\tmediaArray := make([]MediaReference, numMedia)\n\tfor i := 0; i < numMedia; i++ {\n\t\tmediaArray[i] = MediaReference{\n\t\t\tContentType: req.PostFormValue(fmt.Sprintf(\"MediaContentType%d\", i)),\n\t\t\tURL: req.PostFormValue(fmt.Sprintf(\"MediaURL%d\", i)),\n\t\t}\n\t}\n\n\t*cb = Callback{\n\t\tMessageSid: req.PostFormValue(\"MessageSid\"),\n\t\tSmsSid: req.PostFormValue(\"SmsSid\"),\n\t\tBody: req.PostFormValue(\"Body\"),\n\t\tNumMedia: numMedia,\n\t\tMessageStatus: req.PostFormValue(\"MessageStatus\"),\n\t\tErrorCode: req.PostFormValue(\"ErrorCode\"),\n\t\tMediaList: mediaArray,\n\t\tStandardRequest: common.ParseStandardRequest(req),\n\t}\n\treturn nil\n}", "func (h *distroIDGetHandler) Parse(ctx context.Context, r *http.Request) error {\n\th.distroID = gimlet.GetVars(r)[\"distro_id\"]\n\n\treturn nil\n}", "func (f *FastURL) Parse(url []byte) error {\n\treturn Parse(f, url)\n}", "func svcHandler()", "func HandleFunc(dir string) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tlocale, err := FromFiles(dir, router.Param(r, \"locale\"))\n\t\tif err != nil {\n\t\t\trender.Error(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tj, err := locale.JSON()\n\t\tif err != nil {\n\t\t\trender.Error(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(200)\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t_, _ = fmt.Fprint(w, j)\n\t}\n}", "func clinicaltrialsParse(w http.ResponseWriter, r *http.Request) {\n\tclinicaltrials.Parse(currentFileName)\n}", "func FileHandler(mongodbOperator mongodb.MongoOperator) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\ttoken := strings.TrimSuffix(c.Param(\"key\"), \".yaml\")\n\n\t\tinfraId, err := chaos_infrastructure.InfraValidateJWT(token)\n\t\tif err != nil {\n\t\t\tlogrus.Error(err)\n\t\t\tutils.WriteHeaders(&c.Writer, 500)\n\t\t\tc.Writer.Write([]byte(err.Error()))\n\t\t}\n\n\t\tinfra, err := dbChaosInfra.NewInfrastructureOperator(mongodbOperator).GetInfra(infraId)\n\t\tif err != nil {\n\t\t\tlogrus.Error(err)\n\t\t\tutils.WriteHeaders(&c.Writer, 500)\n\t\t\tc.Writer.Write([]byte(err.Error()))\n\t\t}\n\t\tresponse, err := chaos_infrastructure.GetK8sInfraYaml(infra)\n\t\tif err != nil {\n\t\t\tlogrus.Error(err)\n\t\t\tutils.WriteHeaders(&c.Writer, 500)\n\t\t\tc.Writer.Write([]byte(err.Error()))\n\t\t}\n\n\t\tutils.WriteHeaders(&c.Writer, 200)\n\t\tc.Writer.Write(response)\n\t}\n}" ]
[ "0.5851756", "0.55637133", "0.5446869", "0.5426128", "0.5401849", "0.5366215", "0.5277472", "0.5260335", "0.5241706", "0.5218871", "0.5167705", "0.5111928", "0.5108268", "0.5103671", "0.509329", "0.50905794", "0.50709957", "0.5070622", "0.5024615", "0.5015144", "0.4993361", "0.49878728", "0.49868757", "0.49814504", "0.49795747", "0.49647945", "0.49576148", "0.4952181", "0.49312985", "0.4914485", "0.4911066", "0.4896247", "0.4888011", "0.4884218", "0.48827004", "0.4864958", "0.48639464", "0.48380217", "0.48363402", "0.48351103", "0.48192728", "0.47987908", "0.47971004", "0.47892296", "0.4787018", "0.4785168", "0.4777627", "0.47658196", "0.4754777", "0.4754777", "0.4753415", "0.47494602", "0.4740145", "0.47375208", "0.4737068", "0.4724567", "0.4722338", "0.47219005", "0.47129405", "0.4668991", "0.46648467", "0.46635225", "0.46572214", "0.465595", "0.46546733", "0.46517545", "0.4643903", "0.4643179", "0.4639236", "0.46369225", "0.46310815", "0.46283573", "0.46274", "0.4624989", "0.462183", "0.46210498", "0.46174356", "0.4616701", "0.4615872", "0.46109653", "0.46104014", "0.4608518", "0.46030617", "0.46020615", "0.46016163", "0.45992783", "0.45841584", "0.45787394", "0.45681304", "0.45677367", "0.45650414", "0.4555798", "0.4554216", "0.4554109", "0.4553245", "0.45531663", "0.45507708", "0.45497862", "0.45497274", "0.4544271" ]
0.60943615
0
/ The src value will be of one of the following types: int64 float64 bool []byte string time.Time nil for NULL values
func (bs *basicScanner) Scan(srcIfc interface{}) error { if srcIfc == nil { // if src is null, should set dest to it's zero value. // eg. when dest is int, should set it to 0. bs.dest.Set(reflect.Zero(bs.dest.Type())) return nil } if scanner := getScanner(bs.dest.Addr()); scanner != nil { return scanner.Scan(srcIfc) } switch src := srcIfc.(type) { case int64: return scanInt(src, getRealDest(bs.dest)) case float64: return scanFloat(src, getRealDest(bs.dest)) case bool: return scanBool(src, getRealDest(bs.dest)) case []byte: return scanBytes(src, getRealDest(bs.dest)) case string: return scanString(src, getRealDest(bs.dest)) case time.Time: return scanTime(src, getRealDest(bs.dest)) default: return fmt.Errorf("bsql basicScanner unexpected src: %T(%v)", src, src) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func parseNullableFloat64(content []byte, aggErr *AggregateError) *float64 {\n if len(content) == 0 {\n return nil\n }\n result := parseFloat64(content, aggErr)\n return &result\n}", "func ConvertDataNull() time.Time {\n\tDtIni, _ := time.Parse(longForm, dataSpedMysql(\"01011960\"))\n\treturn DtIni\n}", "func Null() Value {\n\treturn Value{v: reflect.ValueOf((*byte)(nil))}\n}", "func LoadRawData(raw interface{}) (f Float64Data) {\n\tvar r []interface{}\n\tvar s Float64Data\n\n\tswitch t := raw.(type) {\n\tcase []interface{}:\n\t\tr = t\n\tcase []uint:\n\t\tfor _, v := range t {\n\t\t\ts = append(s, float64(v))\n\t\t}\n\t\treturn s\n\tcase []uint8:\n\t\tfor _, v := range t {\n\t\t\ts = append(s, float64(v))\n\t\t}\n\t\treturn s\n\tcase []uint16:\n\t\tfor _, v := range t {\n\t\t\ts = append(s, float64(v))\n\t\t}\n\t\treturn s\n\tcase []uint32:\n\t\tfor _, v := range t {\n\t\t\ts = append(s, float64(v))\n\t\t}\n\t\treturn s\n\tcase []uint64:\n\t\tfor _, v := range t {\n\t\t\ts = append(s, float64(v))\n\t\t}\n\t\treturn s\n\tcase []bool:\n\t\tfor _, v := range t {\n\t\t\tif v == true {\n\t\t\t\ts = append(s, 1.0)\n\t\t\t} else {\n\t\t\t\ts = append(s, 0.0)\n\t\t\t}\n\t\t}\n\t\treturn s\n\tcase []float64:\n\t\treturn Float64Data(t)\n\tcase []int:\n\t\tfor _, v := range t {\n\t\t\ts = append(s, float64(v))\n\t\t}\n\t\treturn s\n\tcase []int8:\n\t\tfor _, v := range t {\n\t\t\ts = append(s, float64(v))\n\t\t}\n\t\treturn s\n\tcase []int16:\n\t\tfor _, v := range t {\n\t\t\ts = append(s, float64(v))\n\t\t}\n\t\treturn s\n\tcase []int32:\n\t\tfor _, v := range t {\n\t\t\ts = append(s, float64(v))\n\t\t}\n\t\treturn s\n\tcase []int64:\n\t\tfor _, v := range t {\n\t\t\ts = append(s, float64(v))\n\t\t}\n\t\treturn s\n\tcase []string:\n\t\tfor _, v := range t {\n\t\t\tr = append(r, v)\n\t\t}\n\tcase []time.Duration:\n\t\tfor _, v := range t {\n\t\t\tr = append(r, v)\n\t\t}\n\tcase map[int]int:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\ts = append(s, float64(t[i]))\n\t\t}\n\t\treturn s\n\tcase map[int]int8:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\ts = append(s, float64(t[i]))\n\t\t}\n\t\treturn s\n\tcase map[int]int16:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\ts = append(s, float64(t[i]))\n\t\t}\n\t\treturn s\n\tcase map[int]int32:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\ts = append(s, float64(t[i]))\n\t\t}\n\t\treturn s\n\tcase map[int]int64:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\ts = append(s, float64(t[i]))\n\t\t}\n\t\treturn s\n\tcase map[int]string:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\tr = append(r, t[i])\n\t\t}\n\tcase map[int]uint:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\ts = append(s, float64(t[i]))\n\t\t}\n\t\treturn s\n\tcase map[int]uint8:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\ts = append(s, float64(t[i]))\n\t\t}\n\t\treturn s\n\tcase map[int]uint16:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\ts = append(s, float64(t[i]))\n\t\t}\n\t\treturn s\n\tcase map[int]uint32:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\ts = append(s, float64(t[i]))\n\t\t}\n\t\treturn s\n\tcase map[int]uint64:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\ts = append(s, float64(t[i]))\n\t\t}\n\t\treturn s\n\tcase map[int]bool:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\tif t[i] == true {\n\t\t\t\ts = append(s, 1.0)\n\t\t\t} else {\n\t\t\t\ts = append(s, 0.0)\n\t\t\t}\n\t\t}\n\t\treturn s\n\tcase map[int]float64:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\ts = append(s, t[i])\n\t\t}\n\t\treturn s\n\tcase map[int]time.Duration:\n\t\tfor i := 0; i < len(t); i++ {\n\t\t\tr = append(r, t[i])\n\t\t}\n\t}\n\n\tfor _, v := range r {\n\t\tswitch t := v.(type) {\n\t\tcase int:\n\t\t\ta := float64(t)\n\t\t\tf = append(f, a)\n\t\tcase uint:\n\t\t\tf = append(f, float64(t))\n\t\tcase float64:\n\t\t\tf = append(f, t)\n\t\tcase string:\n\t\t\tfl, err := strconv.ParseFloat(t, 64)\n\t\t\tif err == nil {\n\t\t\t\tf = append(f, fl)\n\t\t\t}\n\t\tcase bool:\n\t\t\tif t == true {\n\t\t\t\tf = append(f, 1.0)\n\t\t\t} else {\n\t\t\t\tf = append(f, 0.0)\n\t\t\t}\n\t\tcase time.Duration:\n\t\t\tf = append(f, float64(t))\n\t\t}\n\t}\n\treturn f\n}", "func (p *IPPacket) Src() [4]byte {\n\treturn [4]byte{(*p)[12], (*p)[13], (*p)[14], (*p)[15]}\n}", "func (sd *mono) Prepare(uint64) {}", "func parseNullableFloat64FromString(content string, aggErr *AggregateError) *float64 {\n if len(content) == 0 {\n return nil\n }\n result := parseFloat64FromString(content, aggErr)\n return &result\n}", "func (n *NullFloat) Scan(src interface{}) error {\n\tif src != nil {\n\t\tv, ok := src.(int64)\n\t\tif !ok {\n\t\t\treturn errors.New(\"bad []byte type assertion\")\n\t\t}\n\n\t\t*n = NullFloat(v)\n\t\treturn nil\n\t}\n\t*n = NullFloat(0)\n\treturn nil\n}", "func SourceNotNil() predicate.Media {\n\treturn predicate.Media(sql.FieldNotNull(FieldSource))\n}", "func parseHeader(header []byte, frame *MP3Frame) bool {\n\n // MPEG version. (2 bits)\n frame.MPEGVersion = (header[1] & 0x18) >> 3\n if frame.MPEGVersion == MPEGVersionReserved {\n return false\n }\n\n // MPEG layer. (2 bits.)\n frame.MPEGLayer = (header[1] & 0x06) >> 1\n if frame.MPEGLayer == MPEGLayerReserved {\n return false\n }\n\n // CRC (cyclic redundency check) protection. (1 bit.)\n frame.CrcProtection = (header[1] & 0x01) == 0x00\n\n // Bit rate index. (4 bits.)\n bitRateIndex := (header[2] & 0xF0) >> 4\n if bitRateIndex == 0 || bitRateIndex == 15 {\n return false\n }\n\n // Bit rate.\n if frame.MPEGVersion == MPEGVersion1 {\n switch frame.MPEGLayer {\n case MPEGLayerI: frame.BitRate = v1l1_br[bitRateIndex] * 1000\n case MPEGLayerII: frame.BitRate = v1l2_br[bitRateIndex] * 1000\n case MPEGLayerIII: frame.BitRate = v1l3_br[bitRateIndex] * 1000\n }\n } else {\n switch frame.MPEGLayer {\n case MPEGLayerI: frame.BitRate = v2l1_br[bitRateIndex] * 1000\n case MPEGLayerII: frame.BitRate = v2l2_br[bitRateIndex] * 1000\n case MPEGLayerIII: frame.BitRate = v2l3_br[bitRateIndex] * 1000\n }\n }\n\n // Sampling rate index. (2 bits.)\n samplingRateIndex := (header[2] & 0x0C) >> 2\n if samplingRateIndex == 3 {\n return false\n }\n\n // Sampling rate.\n switch frame.MPEGVersion {\n case MPEGVersion1: frame.SamplingRate = v1_sr[samplingRateIndex]\n case MPEGVersion2: frame.SamplingRate = v2_sr[samplingRateIndex]\n case MPEGVersion2_5: frame.SamplingRate = v25_sr[samplingRateIndex]\n }\n\n // Padding bit. (1 bit.)\n frame.PaddingBit = (header[2] & 0x02) == 0x02\n\n // Private bit. (1 bit.)\n frame.PrivateBit = (header[2] & 0x01) == 0x01\n\n // Channel mode. (2 bits.)\n frame.ChannelMode = (header[3] & 0xC0) >> 6\n\n // Mode Extension. Valid only for Joint Stereo mode. (2 bits.)\n frame.ModeExtension = (header[3] & 0x30) >> 4\n if frame.ChannelMode != JointStereo && frame.ModeExtension != 0 {\n return false\n }\n\n // Copyright bit. (1 bit.)\n frame.CopyrightBit = (header[3] & 0x08) == 0x08\n\n // Original bit. (1 bit.)\n frame.OriginalBit = (header[3] & 0x04) == 0x04\n\n // Emphasis. (2 bits.)\n frame.Emphasis = (header[3] & 0x03)\n if frame.Emphasis == 2 {\n return false\n }\n\n // Number of samples in the frame. We need this to determine the frame size.\n if frame.MPEGVersion == MPEGVersion1 {\n switch frame.MPEGLayer {\n case MPEGLayerI: frame.SampleCount = 384\n case MPEGLayerII: frame.SampleCount = 1152\n case MPEGLayerIII: frame.SampleCount = 1152\n }\n } else {\n switch frame.MPEGLayer {\n case MPEGLayerI: frame.SampleCount = 384\n case MPEGLayerII: frame.SampleCount = 1152\n case MPEGLayerIII: frame.SampleCount = 576\n }\n }\n\n // If the padding bit is set we add an extra 'slot' to the frame length.\n // A layer I slot is 4 bytes long; layer II and III slots are 1 byte long.\n var padding int = 0\n\n if frame.PaddingBit {\n if frame.MPEGLayer == MPEGLayerI {\n padding = 4\n } else {\n padding = 1\n }\n }\n\n // Calculate the frame length in bytes. There's a lot of confusion online\n // about how to do this and definitive documentation is hard to find as\n // the official MP3 specification is not publicly available. The\n // basic formula seems to boil down to:\n //\n // bytes_per_sample = (bit_rate / sampling_rate) / 8\n // frame_length = sample_count * bytes_per_sample + padding\n //\n // In practice we need to rearrange this formula to avoid rounding errors.\n //\n // I can't find any definitive statement on whether this length is\n // supposed to include the 4-byte header and the optional 2-byte CRC.\n // Experimentation on mp3 files captured from the wild indicates that it\n // includes the header at least.\n frame.FrameLength =\n (frame.SampleCount / 8) * frame.BitRate / frame.SamplingRate + padding\n\n return true\n}", "func (b IPv4Header) Src() net.IP {\n\treturn net.IP(b[12:16])\n}", "func AppendNull(dst []byte) []byte {\n\treturn append(dst, byte(majorTypeSimpleAndFloat|additionalTypeNull))\n}", "func parseNullableBool(content []byte, aggErr *AggregateError) *bool {\n if len(content) == 0 {\n return nil\n }\n result := parseBool(content, aggErr)\n return &result\n}", "func (*InstFPTrunc) isValue() {}", "func (b IPv6Header) Src() net.IP {\n\treturn net.IP(b[8:24])\n}", "func Copy(dst, src interface{}) {\n\tswitch dst := dst.(type) {\n\tcase *types.Any:\n\t\tsrc := src.(*types.Any)\n\t\tdst.TypeUrl = src.TypeUrl\n\t\tif src.Value != nil {\n\t\t\tdst.Value = make([]byte, len(src.Value))\n\t\t\tcopy(dst.Value, src.Value)\n\t\t} else {\n\t\t\tdst.Value = nil\n\t\t}\n\tcase *types.Duration:\n\t\tsrc := src.(*types.Duration)\n\t\t*dst = *src\n\tcase *time.Duration:\n\t\tsrc := src.(*time.Duration)\n\t\t*dst = *src\n\tcase *types.Timestamp:\n\t\tsrc := src.(*types.Timestamp)\n\t\t*dst = *src\n\tcase *types.BoolValue:\n\t\tsrc := src.(*types.BoolValue)\n\t\t*dst = *src\n\tcase *types.Int64Value:\n\t\tsrc := src.(*types.Int64Value)\n\t\t*dst = *src\n\tcase CopierFrom:\n\t\tdst.CopyFrom(src)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Copy for %T not implemented\", dst))\n\t}\n\n}", "func SourceURINotNil() predicate.Media {\n\treturn predicate.Media(sql.FieldNotNull(FieldSourceURI))\n}", "func JWKSByteSource(b []byte) (*jwks.DummySource, error) {\n\tvar keyset jose.JSONWebKeySet\n\tif err := json.Unmarshal(b, &keyset); err != nil {\n\t\treturn nil, err\n\t}\n\treturn jwks.NewDummySource(&keyset), nil\n}", "func (b Byte) IsNull() bool {\n\treturn !b.Valid\n}", "func (ti *TypeInfo) NodeSrc(n ast.Node) []byte {\n\tstart := n.Pos()\n\tend := n.End()\n\tstartPosition := ti.FileSet.Position(start)\n\tendPosition := ti.FileSet.Position(end)\n\treturn ti.FileBytes[startPosition.Offset:endPosition.Offset]\n}", "func SourceIsNil() predicate.Media {\n\treturn predicate.Media(sql.FieldIsNull(FieldSource))\n}", "func (enc *Encoder) SQLNullFloat64OmitEmpty(v *sql.NullFloat64) {\n\tif v != nil && v.Valid && v.Float64 != 0 {\n\t\tenc.Float64(v.Float64)\n\t}\n}", "func (o *WorkflowBuildTaskMeta) GetSrcOk() (*string, bool) {\n\tif o == nil || o.Src == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Src, true\n}", "func (me TdtypeType) IsFrame() bool { return me.String() == \"frame\" }", "func (element *Element) Src(value string) *Element {\n\treturn element.Attr(\"src\", value)\n}", "func NullValue() Value { return Value{Typ: '$', Null: true} }", "func formatFlashData(data *types.Datum, ft *types.FieldType) (interface{}, error) {\n\tif data.GetValue() == nil {\n\t\treturn nil, nil\n\t}\n\n\tswitch ft.Tp {\n\tcase mysql.TypeBit: // UInt64\n\t\tui, err := data.GetMysqlBit().ToInt(nil)\n\t\tif err != nil {\n\t\t\treturn data, errors.Trace(err)\n\t\t}\n\t\treturn ui, nil\n\tcase mysql.TypeTiny: // UInt8/Int8\n\t\tif mysql.HasUnsignedFlag(ft.Flag) {\n\t\t\treturn uint8(data.GetInt64()), nil\n\t\t}\n\t\treturn int8(data.GetInt64()), nil\n\tcase mysql.TypeShort: // UInt16/Int16\n\t\tif mysql.HasUnsignedFlag(ft.Flag) {\n\t\t\treturn uint16(data.GetInt64()), nil\n\t\t}\n\t\treturn int16(data.GetInt64()), nil\n\tcase mysql.TypeYear: // Int16\n\t\treturn int16(data.GetInt64()), nil\n\tcase mysql.TypeLong, mysql.TypeInt24: // UInt32/Int32\n\t\tif mysql.HasUnsignedFlag(ft.Flag) {\n\t\t\treturn uint32(data.GetInt64()), nil\n\t\t}\n\t\treturn int32(data.GetInt64()), nil\n\tcase mysql.TypeFloat: // Float32\n\t\treturn data.GetFloat32(), nil\n\tcase mysql.TypeDouble: // Float64\n\t\treturn data.GetFloat64(), nil\n\tcase mysql.TypeNewDecimal, mysql.TypeDecimal: // Decimal\n\t\tdec := data.GetMysqlDecimal()\n\t\tbin, err := mysqlDecimalToCHDecimalBin(ft, dec)\n\t\tif err != nil {\n\t\t\tlog.Warn(\"Corrupted decimal data, will leave it zero.\", zap.Reflect(\"data\", data.GetMysqlDecimal()))\n\t\t\tbin = make([]byte, 64)\n\t\t}\n\t\treturn bin, nil\n\tcase mysql.TypeDate, mysql.TypeNewDate: // Int64\n\t\tmysqlTime := data.GetMysqlTime()\n\t\tvar result = getUnixTimeSafe(mysqlTime, gotime.UTC)\n\t\treturn result, nil\n\tcase mysql.TypeDatetime, mysql.TypeTimestamp: // Int64\n\t\tmysqlTime := data.GetMysqlTime()\n\t\t// Need to consider timezone for DateTime and Timestamp, which are mapped to timezone-sensitive DateTime in CH.\n\t\tvar result = getUnixTimeSafe(mysqlTime, gotime.Local)\n\t\treturn result, nil\n\tcase mysql.TypeDuration: // Int64\n\t\tnum, err := data.GetMysqlDuration().ToNumber().ToInt()\n\t\tif err != nil {\n\t\t\tlog.Warn(\"Corrupted Duration data, will leave it zero.\", zap.Reflect(\"data\", data.GetMysqlDuration()))\n\t\t\tnum = 0\n\t\t}\n\t\treturn num, nil\n\tcase mysql.TypeLonglong: // UInt64/Int64\n\t\tif mysql.HasUnsignedFlag(ft.Flag) {\n\t\t\treturn data.GetUint64(), nil\n\t\t}\n\t\treturn data.GetInt64(), nil\n\tcase mysql.TypeString, mysql.TypeVarchar, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob, mysql.TypeBlob, mysql.TypeVarString: // String\n\t\treturn data.GetString(), nil\n\tcase mysql.TypeEnum: // Int16\n\t\treturn int16(data.GetMysqlEnum().Value), nil\n\tcase mysql.TypeSet: // String\n\t\treturn data.GetMysqlSet().String(), nil\n\tcase mysql.TypeJSON: // String\n\t\treturn data.GetMysqlJSON().String(), nil\n\tcase mysql.TypeGeometry:\n\t\t// TiDB doesn't have Geometry type, so put it null.\n\t\treturn nil, nil\n\t}\n\n\treturn nil, nil\n}", "func (enc *Encoder) SQLNullFloat64NullEmpty(v *sql.NullFloat64) {\n\tif v != nil && v.Valid {\n\t\tenc.Float64NullEmpty(v.Float64)\n\t}\n}", "func (v Value) Raw() []byte {\n\treturn v.val\n}", "func testNullZeroLengthBlobs(t *testing.T) {\n\tdb.tearDown()\n\tdb.mustExec(\"create table foo (id integer primary key, bar \" + db.blobType(16) + \")\")\n\tdb.mustExec(db.q(\"insert into foo (id, bar) values(?,?)\"), 0, nil)\n\tdb.mustExec(db.q(\"insert into foo (id, bar) values(?,?)\"), 1, []byte{})\n\n\tr0 := db.QueryRow(db.q(\"select bar from foo where id=0\"))\n\tvar b0 []byte\n\terr := r0.Scan(&b0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif b0 != nil {\n\t\tt.Errorf(\"for id=0, got %x; want nil\", b0)\n\t}\n\n\tr1 := db.QueryRow(db.q(\"select bar from foo where id=1\"))\n\tvar b1 []byte\n\terr = r1.Scan(&b1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif b1 == nil {\n\t\tt.Error(\"for id=1, got nil; want zero-length slice\")\n\t} else if len(b1) > 0 {\n\t\tt.Errorf(\"for id=1, got %x; want zero-length slice\", b1)\n\t}\n}", "func SourceURIGT(v string) predicate.Media {\n\treturn predicate.Media(sql.FieldGT(FieldSourceURI, v))\n}", "func (s *DatatypeGeoShape) Source(includeName bool) (interface{}, error) {\n\t// {\n\t// \t\"test\": {\n\t// \t\t\"type\": \"geo_shape\",\n\t// \t\t\"copy_to\": [\"field_1\", \"field_2\"],\n\t// \t\t\"tree\": \"quadtree\",\n\t// \t\t\"precision\": \"50m\",\n\t// \t\t\"tree_levels\": \"various\",\n\t// \t\t\"strategy\": \"recursive\",\n\t// \t\t\"distance_error_pct\": 0.0,\n\t// \t\t\"orientation\": \"ccw\",\n\t// \t\t\"points_only\": true,\n\t// \t\t\"ignore_malformed\": true,\n\t// \t\t\"ignore_z_value\": true,\n\t// \t\t\"coerce\": true\n\t// \t}\n\t// }\n\toptions := make(map[string]interface{})\n\toptions[\"type\"] = \"geo_shape\"\n\n\tif len(s.copyTo) > 0 {\n\t\tvar copyTo interface{}\n\t\tswitch {\n\t\tcase len(s.copyTo) > 1:\n\t\t\tcopyTo = s.copyTo\n\t\t\tbreak\n\t\tcase len(s.copyTo) == 1:\n\t\t\tcopyTo = s.copyTo[0]\n\t\t\tbreak\n\t\tdefault:\n\t\t\tcopyTo = \"\"\n\t\t}\n\t\toptions[\"copy_to\"] = copyTo\n\t}\n\tif s.tree != \"\" {\n\t\toptions[\"tree\"] = s.tree\n\t}\n\tif s.precision != \"\" {\n\t\toptions[\"precision\"] = s.precision\n\t}\n\tif s.treeLevels != \"\" {\n\t\toptions[\"tree_levels\"] = s.treeLevels\n\t}\n\tif s.strategy != \"\" {\n\t\toptions[\"strategy\"] = s.strategy\n\t}\n\tif s.distanceErrorPct != nil {\n\t\toptions[\"distance_error_pct\"] = s.distanceErrorPct\n\t}\n\tif s.orientation != \"\" {\n\t\toptions[\"orientation\"] = s.orientation\n\t}\n\tif s.pointsOnly != nil {\n\t\toptions[\"points_only\"] = s.pointsOnly\n\t}\n\tif s.ignoreMalformed != nil {\n\t\toptions[\"ignore_malformed\"] = s.ignoreMalformed\n\t}\n\tif s.ignoreZValue != nil {\n\t\toptions[\"ignore_z_value\"] = s.ignoreZValue\n\t}\n\tif s.coerce != nil {\n\t\toptions[\"coerce\"] = s.coerce\n\t}\n\n\tif !includeName {\n\t\treturn options, nil\n\t}\n\n\tsource := make(map[string]interface{})\n\tsource[s.name] = options\n\treturn source, nil\n}", "func parseNullableInt64(content []byte, aggErr *AggregateError) *int64 {\n if len(content) == 0 {\n return nil\n }\n result := parseInt64(content, aggErr)\n return &result\n}", "func parsePTSOrDTS(i []byte) *ClockReference {\n\treturn newClockReference(int(uint64(i[0])>>1&0x7<<30|uint64(i[1])<<22|uint64(i[2])>>1&0x7f<<15|uint64(i[3])<<7|uint64(i[4])>>1&0x7f), 0)\n}", "func (o *UiNodeImageAttributes) GetSrcOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Src, true\n}", "func readSource(filename string, src interface{}) ([]byte, error) {\n\tif src != nil {\n\t\tswitch s := src.(type) {\n\t\t\tcase string:\n\t\t\treturn []byte(s), nil\n\t\t\tcase []byte:\n\t\t\treturn s, nil\n\t\t\tcase *bytes.Buffer:\n\t\t\t// is io.Reader, but src is already available in []byte form\n\t\t\tif s != nil {\n\t\t\t\treturn s.Bytes(), nil\n\t\t\t}\n\t\t\tcase io.Reader:\n\t\t\tvar buf bytes.Buffer\n\t\t\tif _, err := io.Copy(&buf, s); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn buf.Bytes(), nil\n\t\t}\n\t\treturn nil, errors.New(\"invalid source\")\n\t}\n\treturn ioutil.ReadFile(filename)\n}", "func Null() Val { return Val{t: bsontype.Null} }", "func (o *HyperflexVmSnapshotInfoAllOf) GetSourceTimestampOk() (*int64, bool) {\n\tif o == nil || o.SourceTimestamp == nil {\n\t\treturn nil, false\n\t}\n\treturn o.SourceTimestamp, true\n}", "func (obj *BlobAttribute) IsNull() bool {\n\treturn obj.isNull()\n}", "func NaN() float32 { return Float32frombits(uvnan) }", "func (p *DatatypeGeoPoint) Source(includeName bool) (interface{}, error) {\n\t// {\n\t// \t\"test\": {\n\t// \t\t\"type\": \"geo_point\",\n\t// \t\t\"copy_to\": [\"field_1\", \"field_2\"],\n\t// \t\t\"ignore_malformed\": true,\n\t// \t\t\"ignore_z_value\": true,\n\t// \t\t\"null_value\": [ 0, 0 ]\n\t// \t}\n\t// }\n\toptions := make(map[string]interface{})\n\toptions[\"type\"] = \"geo_point\"\n\n\tif len(p.copyTo) > 0 {\n\t\tvar copyTo interface{}\n\t\tswitch {\n\t\tcase len(p.copyTo) > 1:\n\t\t\tcopyTo = p.copyTo\n\t\t\tbreak\n\t\tcase len(p.copyTo) == 1:\n\t\t\tcopyTo = p.copyTo[0]\n\t\t\tbreak\n\t\tdefault:\n\t\t\tcopyTo = \"\"\n\t\t}\n\t\toptions[\"copy_to\"] = copyTo\n\t}\n\tif p.ignoreMalformed != nil {\n\t\toptions[\"ignore_malformed\"] = p.ignoreMalformed\n\t}\n\tif p.ignoreZValue != nil {\n\t\toptions[\"ignore_z_value\"] = p.ignoreZValue\n\t}\n\tif p.nullValue != nil {\n\t\toptions[\"null_value\"] = p.nullValue\n\t}\n\n\tif !includeName {\n\t\treturn options, nil\n\t}\n\n\tsource := make(map[string]interface{})\n\tsource[p.name] = options\n\treturn source, nil\n}", "func (*InstBitCast) isValue() {}", "func (p *IPv4) Src() net.IP {\n\treturn p.src\n}", "func readSource(filename string, src interface{}) ([]byte, error) {\n\tif src != nil {\n\t\tswitch s := src.(type) {\n\t\tcase string:\n\t\t\treturn []byte(s), nil\n\t\tcase []byte:\n\t\t\treturn s, nil\n\t\tcase *bytes.Buffer:\n\t\t\tif s != nil {\n\t\t\t\treturn s.Bytes(), nil\n\t\t\t}\n\t\tcase io.Reader:\n\t\t\tvar buf bytes.Buffer\n\t\t\tif _, err := io.Copy(&buf, s); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn buf.Bytes(), nil\n\t\t}\n\t\treturn nil, errors.New(\"invalid source\")\n\t}\n\treturn ioutil.ReadFile(filename)\n}", "func (enc *Encoder) SQLNullFloat64(v *sql.NullFloat64) {\n\tenc.Float64(v.Float64)\n}", "func (v *Muxer) sampleToFlvTag(s *SrsMp4Sample) (tagType uint8, time uint32, data []byte) {\n data = []byte{}\n\n time = s.dts\n if s.handlerType == SrsMp4HandlerTypeSOUN {\n tagType = SRS_RTMP_TYPE_AUDIO\n\n // E.4.2.1 AUDIODATA, flv_v10_1.pdf, page 3\n tmp := uint8(s.codec << 4) | uint8(s.sampleRate << 2) | uint8(s.soundBits << 1) | s.channels\n data = append(data, tmp)\n if s.codec == SrsAudioCodecIdAAC {\n if s.frameTrait == SrsAudioAacFrameTraitSequenceHeader {\n data = append(data, uint8(0))\n } else {\n data = append(data, 1)\n }\n }\n data = append(data, s.sample...)\n return\n }\n\n // E.4.3.1 VIDEODATA, flv_v10_1.pdf, page 5\n tmp := uint8(s.frameType << 4 | s.codec)\n data = append(data, tmp)\n if s.codec == SrsVideoCodecIdAVC {\n tagType = SRS_RTMP_TYPE_VIDEO\n if s.frameTrait == SrsVideoAvcFrameTraitSequenceHeader {\n data = append(data, uint8(0))\n } else {\n data = append(data, uint8(1))\n }\n // cts = pts - dts, where dts = flvheader->timestamp.\n cts := s.pts - s.dts // TODO: may be cts = (s.pts - s.dts) /90;\n data = append(data, to3Bytes(cts)...)\n }\n\n data = append(data, s.sample...)\n\n return\n}", "func TestCheckBinaryExprComplexGtrNil(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `8.0i > nil`, env,\n\t\t`cannot convert nil to type complex128`,\n\t\t`invalid operation: 8i > nil (mismatched types complex128 and <T>)`,\n\t)\n\n}", "func TestJpegData(t *testing.T){\n\tsImagePath := \"./corpus/image/jpeg-sample.jpg\"\n\tsImagePath,_ = filepath.Abs(sImagePath)\n\tif oBytes, err := ioutil.ReadFile(sImagePath); err == nil{\n\t\tif bValid, oErr := IsBytesContentAValidType(oBytes, &types.JPEGType{}); bValid == false{\n\t\t\tif oErr != nil{\n\t\t\t\tt.Error(\"Image Has Less Than The Required Header Bytes\")\n\t\t\t}else{\n\t\t\t\tt.Error(\"Image Is Not A Jpeg File\")\n\t\t\t}\n\t\t}\n\t}\n}", "func (h HeaderV2) SrcAddr() net.Addr { return h.Src }", "func parseNullableBoolFromString(content string, aggErr *AggregateError) *bool {\n if len(content) == 0 {\n return nil\n }\n result := parseBoolFromString(content, aggErr)\n return &result\n}", "func (n *NullableTime) Value() time.Time {\n\treturn n.data\n}", "func (enc *Encoder) AddSQLNullFloat64(v *sql.NullFloat64) {\n\tenc.Float64(v.Float64)\n}", "func (n *NullableGeneric) Value() generic.T {\n\treturn n.data\n}", "func getTestValue(isUpdate bool, dataType string) interface{} {\n\n\tswitch dataType {\n\tcase \"string\":\n\t\tif isUpdate {\n\t\t\treturn \"string_update\"\n\t\t}\n\t\treturn \"string_value\"\n\n\tcase \"float32\":\n\t\tif isUpdate {\n\t\t\treturn cFl32Upd\n\t\t}\n\t\treturn cFl32Crt\n\tcase \"float64\":\n\t\tif isUpdate {\n\t\t\treturn cFl64Upd\n\t\t}\n\t\treturn cFl64Crt\n\tcase \"int\":\n\t\tif isUpdate {\n\t\t\treturn cIUpd\n\t\t}\n\t\treturn cICrt\n\tcase \"int8\":\n\t\tif isUpdate {\n\t\t\treturn cI8Upd\n\t\t}\n\t\treturn cI8Crt\n\tcase \"int16\":\n\t\tif isUpdate {\n\t\t\treturn cI16Upd\n\t\t}\n\t\treturn cI16Crt\n\tcase \"int32\":\n\t\tif isUpdate {\n\t\t\treturn cI32Upd\n\t\t}\n\t\treturn cI32Crt\n\tcase \"int64\":\n\t\tif isUpdate {\n\t\t\treturn cI64Upd\n\t\t}\n\t\treturn cI64Crt\n\tcase \"uint\":\n\t\tif isUpdate {\n\t\t\treturn cUUpd\n\t\t}\n\t\treturn cUCrt\n\tcase \"uint8\":\n\t\tif isUpdate {\n\t\t\treturn cU8Upd\n\t\t}\n\t\treturn cU8Crt\n\tcase \"uint16\":\n\t\tif isUpdate {\n\t\t\treturn cU16Upd\n\t\t}\n\t\treturn cU16Crt\n\tcase \"uint32\":\n\t\tif isUpdate {\n\t\t\treturn cU32Upd\n\t\t}\n\t\treturn cU32Crt\n\tcase \"uint64\":\n\t\tif isUpdate {\n\t\t\treturn cU64Upd\n\t\t}\n\t\treturn cU64Crt\n\tcase \"bool\":\n\t\tif isUpdate {\n\t\t\treturn cBoolUpd\n\t\t}\n\t\treturn cBoolCrt\n\tdefault:\n\t\tlog.Printf(\"unknown data-type %s in test generation - please add support manually\", dataType)\n\t\tos.Exit(-1)\n\t}\n\treturn nil\n}", "func (*InstTrunc) isValue() {}", "func ValueIsNil() predicate.Blob {\n\treturn predicate.Blob(\n\t\tfunc(s *sql.Selector) {\n\t\t\ts.Where(sql.IsNull(s.C(FieldValue)))\n\t\t},\n\t)\n}", "func (me TxsdAnimAdditionAttrsAccumulate) IsNone() bool { return me.String() == \"none\" }", "func (p Pinger) GetSrc() net.IP {\r\n\treturn p.src\r\n}", "func (h arrayHeader) isNull(i uint64) bool {\n\treturn h.hasNulls && ((h.nullBitmap[i/8]>>(i%8))&1) == 1\n}", "func (v *Value) Decode(ptr interface{}) {\n switch p := ptr.(type) {\n case *[]byte:\n *p = v.Bytes()\n case *string:\n *p = v.String()\n case *bool:\n *p = Util.ToBool(v.data)\n case *float32, *float64:\n fv := Util.ToFloat(v.data)\n rv := reflect.ValueOf(ptr).Elem()\n rv.Set(reflect.ValueOf(fv).Convert(rv.Type()))\n case *int, *int8, *int16, *int32, *int64:\n iv := Util.ToInt(v.data)\n rv := reflect.ValueOf(ptr).Elem()\n rv.Set(reflect.ValueOf(iv).Convert(rv.Type()))\n case *uint, *uint8, *uint16, *uint32, *uint64:\n iv := Util.ToInt(v.data)\n rv := reflect.ValueOf(ptr).Elem()\n rv.Set(reflect.ValueOf(iv).Convert(rv.Type()))\n default:\n if e := json.Unmarshal(v.Bytes(), ptr); e != nil {\n rv := reflect.ValueOf(ptr)\n if rv.Kind() != reflect.Ptr || rv.IsNil() {\n panic(\"Value.Decode: require a valid pointer\")\n }\n\n if rv = rv.Elem(); rv.Kind() == reflect.Interface {\n rv.Set(reflect.ValueOf(v.data))\n } else {\n panic(\"Value.Decode: \" + e.Error())\n }\n }\n }\n}", "func (enc *Encoder) AddSQLNullFloat64OmitEmpty(v *sql.NullFloat64) {\n\tif v != nil && v.Valid && v.Float64 != 0 {\n\t\tenc.Float64OmitEmpty(v.Float64)\n\t}\n}", "func FromNullFloat(s sql.NullFloat64) float64 {\n\tif s.Valid {\n\t\treturn s.Float64\n\t}\n\treturn 0.00\n}", "func TestSourceParseRawFailure(t *testing.T) {\n\ttype testCase struct {\n\t\tname string\n\t\tinput string\n\t\twantErr string\n\t}\n\n\ttest := func(t *testing.T, tc testCase) {\n\t\tassert.Assert(t, tc.wantErr != \"\")\n\t\tin := strings.NewReader(tc.input)\n\t\tvar source cogito.Source\n\t\tdec := json.NewDecoder(in)\n\t\tdec.DisallowUnknownFields()\n\n\t\terr := dec.Decode(&source)\n\n\t\tassert.Error(t, err, tc.wantErr)\n\t}\n\n\ttestCases := []testCase{\n\t\t{\n\t\t\tname: \"empty input\",\n\t\t\tinput: ``,\n\t\t\twantErr: `EOF`,\n\t\t},\n\t\t{\n\t\t\tname: \"malformed input\",\n\t\t\tinput: `pizza`,\n\t\t\twantErr: `invalid character 'p' looking for beginning of value`,\n\t\t},\n\t\t{\n\t\t\tname: \"JSON types validation is automatic (since Go is statically typed)\",\n\t\t\tinput: `\n{\n \"owner\": 123\n}`,\n\t\t\twantErr: `json: cannot unmarshal number into Go struct field source.owner of type string`,\n\t\t},\n\t\t{\n\t\t\tname: \"Unknown fields are caught automatically by the JSON decoder\",\n\t\t\tinput: `\n{\n \"owner\": \"the-owner\",\n \"repo\": \"the-repo\",\n \"access_token\": \"the-token\",\n \"hello\": \"I am an unknown key\"\n}`,\n\t\t\twantErr: `json: unknown field \"hello\"`,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ttest(t, tc)\n\t\t})\n\t}\n}", "func IsZeroValue(data interface{}) bool {\n\tif data == nil {\n\t\treturn true\n\t} else if value, ok := data.(string); ok {\n\t\treturn value == \"\"\n\t} else if value, ok := data.(bool); ok {\n\t\treturn value == false\n\t} else if value, ok := data.(float32); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(float64); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(int); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(int8); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(int16); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(int32); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(int64); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(uint); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(uint8); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(uint16); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(uint32); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(uint64); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(uintptr); ok {\n\t\treturn value == 0\n\t} else if value, ok := data.(complex64); ok {\n\t\tvalue128 := complex128(value)\n\t\treturn math.Float64bits(real(value128)) == 0 && math.Float64bits(imag(value128)) == 0\n\t} else if value, ok := data.(complex128); ok {\n\t\treturn math.Float64bits(real(value)) == 0 && math.Float64bits(imag(value)) == 0\n\t} else {\n\t\tif IsStructObject(data) {\n\t\t\tif IsNil(data) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tvalueOfData := reflect.ValueOf(data)\n\t\t\tfor i := 0; i < valueOfData.NumField(); i++ {\n\t\t\t\tif !IsZeroValue(valueOfData.Field(i).Interface()) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif IsNil(data) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func TestCheckBinaryExprFloatGtrNil(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `2.0 > nil`, env,\n\t\t`cannot convert nil to type float64`,\n\t\t`invalid operation: 2 > nil (mismatched types float64 and <T>)`,\n\t)\n\n}", "func isRecordFromSrc(record entities.Record) bool {\n\tsrcIEWithValue, exist := record.GetInfoElementWithValue(\"sourcePodName\")\n\tif !exist || srcIEWithValue.Value == \"\" {\n\t\treturn false\n\t}\n\tdstIEWithValue, exist := record.GetInfoElementWithValue(\"destinationPodName\")\n\tif exist && dstIEWithValue.Value != \"\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func parseNullableInt64FromString(content string, aggErr *AggregateError) *int64 {\n if len(content) == 0 {\n return nil\n }\n result := parseInt64FromString(content, aggErr)\n return &result\n}", "func readSource(filename string, src interface{}) ([]byte, error) {\n\tif src != nil {\n\t\tswitch s := src.(type) {\n\t\tcase string:\n\t\t\treturn []byte(s), nil\n\t\tcase []byte:\n\t\t\treturn s, nil\n\t\tcase *bytes.Buffer:\n\t\t\t// is io.Reader, but src is already available in []byte form\n\t\t\tif s != nil {\n\t\t\t\treturn s.Bytes(), nil\n\t\t\t}\n\t\tcase io.Reader:\n\t\t\tvar buf bytes.Buffer\n\t\t\t_, err := io.Copy(&buf, s)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn buf.Bytes(), nil\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"invalid source\")\n\t\t}\n\t}\n\n\treturn ioutil.ReadFile(filename)\n}", "func Source(i interface{}, settings map[string]interface{}) error {\n\tv := reflect.ValueOf(i)\n\tif v.Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\tif v.Kind() != reflect.Struct {\n\t\treturn errors.New(\"can only source structs\")\n\t}\n\n\tt := v.Type()\n\tfor j := 0; j < t.NumField(); j++ {\n\t\tf := t.Field(j)\n\t\ts, ok := f.Tag.Lookup(\"json\")\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tp := strings.Index(s, \",\")\n\t\tif p > -1 {\n\t\t\ts = s[:p]\n\t\t}\n\t\tsetting, ok := settings[s]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tsv := reflect.ValueOf(setting)\n\t\tswitch sv.Kind() {\n\t\tcase reflect.Slice, reflect.Array:\n\t\t\tav, e := toSpecificArray(sv, f.Type)\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\t\tv.FieldByName(f.Name).Set(av)\n\t\tdefault:\n\t\t\tif !sv.Type().AssignableTo(f.Type) {\n\t\t\t\treturn fmt.Errorf(\"found unassignable type at %s, expected %v but found %v\", f.Name, f.Type, sv.Type())\n\t\t\t}\n\t\t\tv.FieldByName(f.Name).Set(sv)\n\t\t}\n\t}\n\treturn nil\n}", "func TestCheckBinaryExprNilGtrComplex(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `nil > 8.0i`, env,\n\t\t`cannot convert nil to type complex128`,\n\t\t`invalid operation: nil > 8i (mismatched types <T> and complex128)`,\n\t)\n\n}", "func LoadValueIfFromInterface(val interface{}) (valIf ValueIf, err error) {\n\tswitch reflect.TypeOf(val).Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8,\n\t\treflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tvalIf, err = NewValueInt64(val)\n\tcase reflect.Bool:\n\t\tvalIf, err = NewValueBool(val)\n\tcase reflect.String:\n\t\tvalIf, err = NewValueString(val)\n\tcase reflect.Float32, reflect.Float64:\n\t\tvalIf, err = NewValueFloat64(val)\n\tdefault:\n\t\terr = powerr.New(powerr.ErrNotSupportValueType).StoreKV(\"Type\", reflect.TypeOf(val).Kind()).StoreStack()\n\t}\n\n\treturn valIf, err\n}", "func (p *Parser) NullFloat64(i int, context string) Float64 {\n\ts := p.String(i, context)\n\tif p.err != nil {\n\t\treturn Float64{}\n\t}\n\tif s == \"\" {\n\t\treturn Float64{}\n\t}\n\tv, err := strconv.ParseFloat(s, 64)\n\tif err != nil {\n\t\tp.SetErr(context, s)\n\t\treturn Float64{}\n\t}\n\treturn Float64{Value: v, Valid: true}\n}", "func CheckGetRaw(raw *Raw, fileLength int64) error {\n\t// if raw.Length < 0 ,read All data\n\tif raw.Offset < 0 {\n\t\treturn errors.Wrapf(cdnerrors.ErrInvalidValue, \"the offset: %d is a negative integer\", raw.Offset)\n\t}\n\tif raw.Length < 0 {\n\t\treturn errors.Wrapf(cdnerrors.ErrInvalidValue, \"the length: %d is a negative integer\", raw.Length)\n\t}\n\tif fileLength < raw.Offset {\n\t\treturn errors.Wrapf(cdnerrors.ErrInvalidValue, \"the offset: %d is lager than the file length: %d\", raw.Offset, fileLength)\n\t}\n\n\tif fileLength < (raw.Offset + raw.Length) {\n\t\treturn errors.Wrapf(cdnerrors.ErrInvalidValue, \"the offset: %d and length: %d is lager than the file length: %d\", raw.Offset, raw.Length, fileLength)\n\t}\n\treturn nil\n}", "func (cb *CompressionBounds) IsNull() bool {\n\tif cb.MinX == 0 && cb.MinY == 0 && cb.MaxX == 0 && cb.MaxY == 0 && cb.Instruction == 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (enc *Encoder) AddSQLNullFloat64NullEmpty(v *sql.NullFloat64) {\n\tif v != nil && v.Valid {\n\t\tenc.Float64NullEmpty(v.Float64)\n\t}\n}", "func (v Value) Raw() string {\n\treturn string(v.input[v.start : v.start+v.size])\n}", "func SourceURIIsNil() predicate.Media {\n\treturn predicate.Media(sql.FieldIsNull(FieldSourceURI))\n}", "func Steg3Decode(src, img image.Image) string {\n\turb := []byte{}\n\tres := []byte{}\n\tfor y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {\n\t\tfor x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {\n\t\t\tif x%2 == 0 && y < 444 && x < 444 && img.At(x, y) != src.At(x, y) {\n\t\t\t\tr, _, _, _ := img.At(x, y).RGBA()\n\t\t\t\turb = append(urb, byte(uint8(r)))\n\t\t\t}\n\n\t\t\tif y%8 == 0 && x%8 == 0 && y > 444 && x > 444 {\n\t\t\t\tr1, g1, b1, _ := img.At(x, y).RGBA()\n\t\t\t\tr2, g2, b2, _ := src.At(x, y).RGBA()\n\t\t\t\tby := byte(((uint8(r1) - uint8(r2)) % 10) + ((uint8(g1)-uint8(g2))%10)*10 + ((uint8(b1)-uint8(b2))%10)*100)\n\t\t\t\tif by == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tres = append(res, by)\n\t\t\t}\n\t\t}\n\t}\n\t// broken lmao\n\tfmt.Println(\"url:\", string(urb))\n\n\tflag := make([]byte, len(res))\n\tctr := 0\n\tfor i := 0; i < len(res)/2; i++ {\n\t\tflag[ctr] = res[i]\n\t\tctr += 2\n\t}\n\n\tctr = 1\n\tfor i := len(res) / 2; i < len(res); i++ {\n\t\tflag[ctr] = res[i]\n\t\tctr += 2\n\t}\n\n\treturn string(flag)\n}", "func TestCheckBinaryExprNilOrComplex(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `nil | 8.0i`, env,\n\t\t`cannot convert nil to type complex128`,\n\t\t`invalid operation: nil | 8i (mismatched types <T> and complex128)`,\n\t)\n\n}", "func SourceFromString(s string) *Source {\n return &Source{ Path: \"str\", Text: []byte(s) }\n}", "func (s *MetaFieldSize) Source(includeName bool) (interface{}, error) {\n\t// {\n\t// \t\"_size\": {\n\t// \t\t\"enabled\": true\n\t// \t}\n\t// }\n\toptions := make(map[string]interface{})\n\n\tif s.enabled != nil {\n\t\toptions[\"enabled\"] = s.enabled\n\t}\n\n\tif !includeName {\n\t\treturn options, nil\n\t}\n\n\tsource := make(map[string]interface{})\n\tsource[\"_size\"] = options\n\treturn source, nil\n}", "func NaN32() float32 { return Float32frombits(uvnan32) }", "func _fload(frame *runtime.Frame, index uint) {\n\tval := frame.GetFloat(index)\n\tframe.PushFloat(val)\n}", "func (n NullFloat32) Value() (driver.Value, error) {\n\tif !n.Valid {\n\t\treturn nil, nil\n\t}\n\treturn float64(n.Float32), nil\n}", "func (z *Float) GobDecode(buf []byte) error {}", "func Uint8ToStringIsNil() predicate.Conversion {\n\treturn predicate.Conversion(func(s *sql.Selector) {\n\t\ts.Where(sql.IsNull(s.C(FieldUint8ToString)))\n\t})\n}", "func parseNullableString(content []byte) *string {\n if len(content) == 0 {\n return nil\n }\n result := parseString(content)\n return &result\n}", "func TestRaw(value []byte) optic.Raw {\n\tsource := \"test1\"\n\ttags := map[string]string{\"tag1\": \"value1\"}\n\tr, _ := raw.New(\n\t\tsource,\n\t\tvalue,\n\t\ttags,\n\t\tnil,\n\t)\n\treturn r\n}", "func (s *BasePlSqlParserListener) EnterDatatype_null_enable(ctx *Datatype_null_enableContext) {}", "func TestCheckBinaryExprNilGtrFloat(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `nil > 2.0`, env,\n\t\t`cannot convert nil to type float64`,\n\t\t`invalid operation: nil > 2 (mismatched types <T> and float64)`,\n\t)\n\n}", "func SrcIP(ipnet *net.IPNet) []expr.Any {\n\treturn ip(ipnet, 12)\n}", "func (enc *Encoder) SQLNullFloat64KeyOmitEmpty(key string, v *sql.NullFloat64) {\n\tif v != nil && v.Valid && v.Float64 != 0 {\n\t\tenc.Float64KeyOmitEmpty(key, v.Float64)\n\t}\n}", "func (*InstUIToFP) isValue() {}", "func (d *Data) Raw() []byte {\n\treturn d.buf\n}", "func (o *WorkflowBuildTaskMeta) HasSrc() bool {\n\tif o != nil && o.Src != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func copyNonZeroFrom(src, dst *storeSnap) {\n\tif len(src.Architectures) > 0 {\n\t\tdst.Architectures = src.Architectures\n\t}\n\tif src.Base != \"\" {\n\t\tdst.Base = src.Base\n\t}\n\tif src.Confinement != \"\" {\n\t\tdst.Confinement = src.Confinement\n\t}\n\tif src.Contact != \"\" {\n\t\tdst.Contact = src.Contact\n\t}\n\tif src.CreatedAt != \"\" {\n\t\tdst.CreatedAt = src.CreatedAt\n\t}\n\tif src.Description.Clean() != \"\" {\n\t\tdst.Description = src.Description\n\t}\n\tif src.Download.URL != \"\" {\n\t\tdst.Download = src.Download\n\t}\n\tif src.Epoch.String() != \"0\" {\n\t\tdst.Epoch = src.Epoch\n\t}\n\tif src.License != \"\" {\n\t\tdst.License = src.License\n\t}\n\tif src.Name != \"\" {\n\t\tdst.Name = src.Name\n\t}\n\tif len(src.Prices) > 0 {\n\t\tdst.Prices = src.Prices\n\t}\n\tif src.Private {\n\t\tdst.Private = src.Private\n\t}\n\tif src.Publisher.ID != \"\" {\n\t\tdst.Publisher = src.Publisher\n\t}\n\tif src.Revision > 0 {\n\t\tdst.Revision = src.Revision\n\t}\n\tif src.SnapID != \"\" {\n\t\tdst.SnapID = src.SnapID\n\t}\n\tif src.SnapYAML != \"\" {\n\t\tdst.SnapYAML = src.SnapYAML\n\t}\n\tif src.Summary.Clean() != \"\" {\n\t\tdst.Summary = src.Summary\n\t}\n\tif src.Title.Clean() != \"\" {\n\t\tdst.Title = src.Title\n\t}\n\tif src.Type != \"\" {\n\t\tdst.Type = src.Type\n\t}\n\tif src.Version != \"\" {\n\t\tdst.Version = src.Version\n\t}\n\tif len(src.Media) > 0 {\n\t\tdst.Media = src.Media\n\t}\n\tif len(src.CommonIDs) > 0 {\n\t\tdst.CommonIDs = src.CommonIDs\n\t}\n}", "func TestCheckBinaryExprComplexOrNil(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `8.0i | nil`, env,\n\t\t`cannot convert nil to type complex128`,\n\t\t`invalid operation: 8i | nil (mismatched types complex128 and <T>)`,\n\t)\n\n}", "func TestCheckBinaryExprComplexLssNil(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `8.0i < nil`, env,\n\t\t`cannot convert nil to type complex128`,\n\t\t`invalid operation: 8i < nil (mismatched types complex128 and <T>)`,\n\t)\n\n}", "func zeroValue(t reflect.Type) string {\n\tswitch t.Kind() {\n\tcase reflect.Bool:\n\t\treturn \"false\"\n\tcase reflect.String:\n\t\treturn `\"\"`\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn \"0\"\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\treturn \"0\"\n\tcase reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:\n\t\treturn \"0\"\n\tcase reflect.Ptr, reflect.Slice, reflect.Map, reflect.Interface:\n\t\treturn \"nil\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func TestByteNull(t *testing.T) {\n\tclient := newQueriesClient(t)\n\tresult, err := client.ByteNull(context.Background(), nil)\n\trequire.NoError(t, err)\n\trequire.Zero(t, result)\n}", "func TestCheckBinaryExprFloatRhlNil(t *testing.T) {\n\tenv := MakeSimpleEnv()\n\n\texpectCheckError(t, `2.0 >> nil`, env,\n\t\t`cannot convert nil to type uint`,\n\t)\n\n}" ]
[ "0.5055043", "0.49458912", "0.49401158", "0.4929327", "0.49207103", "0.4825433", "0.48236334", "0.472747", "0.47201735", "0.46569824", "0.46504113", "0.4647044", "0.46410972", "0.4635526", "0.4630723", "0.46265224", "0.4617849", "0.45988834", "0.4591235", "0.45552418", "0.45458835", "0.4544547", "0.4538893", "0.45312497", "0.45266128", "0.44771674", "0.44495222", "0.44348955", "0.44272506", "0.4417318", "0.44124782", "0.44068173", "0.44052172", "0.4400087", "0.4398569", "0.43975797", "0.43966535", "0.43965727", "0.438758", "0.4383581", "0.4378925", "0.4371164", "0.43705434", "0.43705028", "0.4362879", "0.43603423", "0.43568915", "0.43458435", "0.43428862", "0.4340814", "0.43387404", "0.43371218", "0.4333091", "0.4323957", "0.4322338", "0.43184775", "0.43116832", "0.4296974", "0.42847002", "0.42846975", "0.4278062", "0.42697087", "0.42684433", "0.4266309", "0.4266201", "0.4260943", "0.4258054", "0.4255515", "0.4245631", "0.4243394", "0.42433476", "0.4237458", "0.42357546", "0.4228704", "0.42174765", "0.4217445", "0.42170396", "0.42160082", "0.42143202", "0.42070207", "0.42069948", "0.41999444", "0.4197022", "0.41835234", "0.41810253", "0.41809732", "0.4177209", "0.41754615", "0.41753462", "0.41740522", "0.41695285", "0.41660327", "0.41659734", "0.4165383", "0.41636062", "0.41603857", "0.4156912", "0.4156258", "0.4149669", "0.41484782", "0.41451564" ]
0.0
-1
the preceding steps ensured that dest is valid
func getRealDest(dest reflect.Value) reflect.Value { if dest.Kind() == reflect.Interface && !dest.IsNil() { dest = dest.Elem() } for dest.Kind() == reflect.Ptr { if dest.IsNil() { dest.Set(reflect.New(dest.Type().Elem())) } dest = dest.Elem() } return dest }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *copyS2SMigrationEnumeratorBase) validateDestIsService(ctx context.Context, destURL url.URL) error {\n\tswitch e.FromTo {\n\tcase common.EFromTo.BlobBlob(), common.EFromTo.FileBlob(), common.EFromTo.S3Blob():\n\t\tif e.destBlobPipeline == nil {\n\t\t\tpanic(errors.New(\"invalid state, blob type destination's pipeline is not initialized\"))\n\t\t}\n\t\tdestServiceURL := azblob.NewServiceURL(destURL, e.destBlobPipeline)\n\t\tif _, err := destServiceURL.GetProperties(ctx); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid source and destination combination for service to service copy: \"+\n\t\t\t\t\"destination must point to service account in current scenario, error when checking destination properties, %v\", err)\n\t\t}\n\tdefault:\n\t\tpanic(fmt.Errorf(\"invalid from-to pair, %v\", e.FromTo))\n\t}\n\n\treturn nil\n}", "func (opts CopyDestOptions) validate() (err error) {\n\t// Input validation.\n\tif err = s3utils.CheckValidBucketName(opts.Bucket); err != nil {\n\t\treturn err\n\t}\n\tif err = s3utils.CheckValidObjectName(opts.Object); err != nil {\n\t\treturn err\n\t}\n\tif opts.Progress != nil && opts.Size < 0 {\n\t\treturn errInvalidArgument(\"For progress bar effective size needs to be specified\")\n\t}\n\treturn nil\n}", "func (self *Argument) _sanityCheckDestination(dest Destination) error {\n\t// TODO - some sanity checks here would be great\n // TODO - if PassThrough, check that it's a slice\n\n\tptrValue := reflect.ValueOf(dest)\n\tstructValue := reflect.Indirect(ptrValue)\n\tstructType := structValue.Type()\n\n\tvar field reflect.StructField\n\tvar found bool\n\tvar needles []string\n\n\tif self.Dest != \"\" {\n\t\tfield, found = structType.FieldByName(self.Dest)\n\t\tif !found {\n\t\t\treturn errors.New(fmt.Sprintf(\"Could not find destination field for argument %s, given as %s\",\n\t\t\t\tself.prettyName(), self.Dest))\n\t\t}\n\t} else {\n\t\tif self.Short != \"\" {\n\t\t\tshortStructName := argumentVariableName(self.Short[1:len(self.Short)])\n\t\t\tneedles = append(needles, shortStructName)\n\t\t\tfield, found = structType.FieldByName(shortStructName)\n\t\t}\n\t\tif !found && self.Long != \"\" {\n\t\t\tlongStructName := argumentVariableName(self.Long[2:len(self.Long)])\n\t\t\tneedles = append(needles, longStructName)\n\t\t\tfield, found = structType.FieldByName(longStructName)\n\t\t}\n\t\tif !found && self.Name != \"\" {\n\t\t\tstructName := argumentVariableName(self.Name)\n\t\t\tneedles = append(needles, structName)\n\t\t\tfield, found = structType.FieldByName(structName)\n\t\t}\n\t\tif !found {\n\t\t\treturn errors.New(fmt.Sprintf(\"Could not find destination field for argument %s; checked %s\",\n\t\t\t\tself.prettyName(), strings.Join(needles, \",\")))\n\t\t}\n\t}\n\n\t// By using the index of the field within the struct type,\n\t// we can get the corresponding struct value\n\tself.value = structValue.FieldByIndex(field.Index)\n\tself.typeKind = field.Type.Kind()\n\tif self.typeKind == reflect.Slice {\n\t\t// Get the type of slice\n\t\tself.sliceKind = self.value.Type().Elem().Kind()\n\t}\n\t// log.Printf(\"field=%v index=%d typeKind=%v value=%v sliceKind=%v\",\n\t// field, field.Index, self.typeKind, self.value, self.sliceKind)\n\treturn nil\n}", "func ValidateDestination(ctx context.Context, dest *appv1.ApplicationDestination, clientset kubernetes.Interface, argoCDNamespace string) error {\n\tif dest.Name != \"\" {\n\t\tif dest.Server == \"\" {\n\t\t\tserver, err := getDestinationServer(ctx, dest.Name, clientset, argoCDNamespace)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to find destination server: %v\", err)\n\t\t\t}\n\t\t\tif server == \"\" {\n\t\t\t\treturn fmt.Errorf(\"application references destination cluster %s which does not exist\", dest.Name)\n\t\t\t}\n\t\t\tdest.SetInferredServer(server)\n\t\t} else {\n\t\t\tif !dest.IsServerInferred() {\n\t\t\t\treturn fmt.Errorf(\"application destination can't have both name and server defined: %s %s\", dest.Name, dest.Server)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (pf *PetsFile) NeedsCopy() PetsCause {\n\tif pf.Link || pf.Source == \"\" {\n\t\treturn NONE\n\t}\n\n\tshaSource, err := Sha256(pf.Source)\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] cannot determine sha256 of Source file %s: %v\\n\", pf.Source, err)\n\t\treturn NONE\n\t}\n\n\tshaDest, err := Sha256(pf.Dest)\n\tif os.IsNotExist(err) {\n\t\treturn CREATE\n\t} else if err != nil {\n\t\tlog.Printf(\"[ERROR] cannot determine sha256 of Dest file %s: %v\\n\", pf.Dest, err)\n\t\treturn NONE\n\t}\n\n\tif shaSource == shaDest {\n\t\tlog.Printf(\"[DEBUG] same sha256 for %s and %s: %s\\n\", pf.Source, pf.Dest, shaSource)\n\t\treturn NONE\n\t}\n\n\tlog.Printf(\"[DEBUG] sha256[%s]=%s != sha256[%s]=%s\\n\", pf.Source, shaSource, pf.Dest, shaDest)\n\treturn UPDATE\n}", "func (d *Destination) Validate(ctx context.Context) *apis.FieldError {\n\tif d == nil {\n\t\treturn nil\n\t}\n\treturn ValidateDestination(ctx, *d).ViaField(apis.CurrentField)\n}", "func SanityCheckAndCopy(ctx context.Context, src, dest *AnnotatedTable) error {\n\t// Extract the\n\tsrcParts, err := getTableParts(src.TableID())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdestParts, err := getTableParts(dest.TableID())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif destParts.yyyymmdd != srcParts.yyyymmdd {\n\t\treturn ErrMismatchedPartitions\n\t}\n\n\terr = src.checkAlmostAsBig(ctx, dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = src.checkModifiedAfter(ctx, dest)\n\tif err != nil {\n\t\t// TODO: Should we delete the source table here?\n\t\tlog.Printf(\"%s modified (%v) after %s (%v)\\n\", src.FullyQualifiedName(), src.LastModifiedTime(ctx), dest.FullyQualifiedName(), dest.LastModifiedTime(ctx))\n\t\treturn err\n\t}\n\n\tcopier := dest.Table.CopierFrom(src.Table)\n\tconfig := bqiface.CopyConfig{}\n\tconfig.WriteDisposition = bigquery.WriteTruncate\n\tconfig.Dst = dest.Table\n\tconfig.Srcs = append(config.Srcs, src.Table)\n\tcopier.SetCopyConfig(config)\n\tjob, err := copier.Run(ctx)\n\tif err != nil {\n\t\tlog.Println(\"Error Copying...\", src.TableID(), \"error:\", err)\n\t\treturn err\n\t}\n\tlog.Println(\"Start Copying...\", src.TableID(), \"JobID:\", job.ID())\n\n\terr = WaitForJob(ctx, job, 10*time.Second)\n\tif err != nil {\n\t\tlog.Println(\"Error Waiting...\", src.TableID(), \"JobID:\", job.ID(), \"error:\", err)\n\t} else {\n\t\tlog.Println(\"Done Copying...\", src.TableID(), \"JobID:\", job.ID())\n\t}\n\tlog.Println(\"SanityCheckAndCopy Done\")\n\treturn err\n}", "func (m Mux) NeedTransfer(ctx context.Context, dst, src reflow.File) (bool, error) {\n\tif src.Size != 0 && dst.Size != 0 && src.Size != dst.Size {\n\t\treturn true, nil\n\t}\n\t// An ETag mismatch doesn't necessarily mean that the objects have different\n\t// contents. E.g. the ETag of an S3 object uploaded via multipart copy is\n\t// not a digest of the object data (https://docs.aws.amazon.com/AmazonS3/latest/API/API_Object.html).\n\tif src.ETag != \"\" && src.ETag == dst.ETag {\n\t\treturn false, nil\n\t}\n\t// A zero ContentHash doesn't necessarily mean that the field is missing\n\t// from the object's metadata.\n\tif src.ContentHash.IsZero() {\n\t\tvar err error\n\t\tsrc, err = m.File(ctx, src.Source)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\tif dst.ContentHash.IsZero() {\n\t\tvar err error\n\t\tdst, err = m.File(ctx, dst.Source)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\tif !src.ContentHash.IsZero() && !dst.ContentHash.IsZero() {\n\t\treturn src.ContentHash != dst.ContentHash, nil\n\t}\n\treturn true, nil\n}", "func TestNoDest(t *testing.T) {\n\torganize.Episodes(\"testdata/config.yaml\")\n\t// Then try to move one again\n\tepisode := organize.Episode{Path: \"testdata/tmp_input/No_Dest.S07E02.mkv\", Filename: \"Foo\", Series: \"Real\", Season: \"1\"}\n\terr := organize.MoveEpisode(episode, \"/dev/null/fake\", false)\n\tif err == nil {\n\t\tlog.Println(\"MoveEpisode should have errored\")\n\t\tt.Fail()\n\t}\n}", "func (e AssignDestAddressRequestValidationError) Cause() error { return e.cause }", "func (d *Deployer) shouldOverwrite(source file, dest s3.Key) (up bool, reason string) {\n\n\tf, err := os.Open(source.absPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening file %s: %v\", source.absPath, err)\n\t}\n\tdefer f.Close()\n\n\tvar (\n\t\tsourceSize = source.size\n\t\tr io.Reader = f\n\t)\n\n\troute, err := d.findRoute(source.path)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error finding route for %s: %v\", source.absPath, err)\n\t}\n\n\tif route != nil && route.Gzip {\n\t\tvar b bytes.Buffer\n\t\tgz := gzip.NewWriter(&b)\n\t\tio.Copy(gz, f)\n\t\tgz.Close()\n\t\tr = &b\n\t\tsourceSize = int64(b.Len())\n\t}\n\n\tif sourceSize != dest.Size {\n\t\treturn true, \"file size mismatch\"\n\t}\n\n\tsourceMod := source.lastModified.UTC().Format(time.RFC3339)\n\tif sourceMod == dest.LastModified {\n\t\t// no need to upload if times match, but different times may just be drift\n\t\treturn false, \"last modified match\"\n\t}\n\n\tetag, err := calculateETag(r)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error calculating ETag for %s: %v\", source.absPath, err)\n\t}\n\tif dest.ETag == etag {\n\t\treturn false, \"etags match\"\n\t}\n\treturn true, \"etags mismatch\"\n}", "func TestSyncCompareDest(t *testing.T) {\n\tctx := context.Background()\n\tctx, ci := fs.AddConfig(ctx)\n\tr := fstest.NewRun(t)\n\n\tci.CompareDest = []string{r.FremoteName + \"/CompareDest\"}\n\n\tfdst, err := fs.NewFs(ctx, r.FremoteName+\"/dst\")\n\trequire.NoError(t, err)\n\n\t// check empty dest, empty compare\n\tfile1 := r.WriteFile(\"one\", \"one\", t1)\n\tr.CheckLocalItems(t, file1)\n\n\taccounting.GlobalStats().ResetCounters()\n\terr = Sync(ctx, fdst, r.Flocal, false)\n\trequire.NoError(t, err)\n\n\tfile1dst := file1\n\tfile1dst.Path = \"dst/one\"\n\n\tr.CheckRemoteItems(t, file1dst)\n\n\t// check old dest, empty compare\n\tfile1b := r.WriteFile(\"one\", \"onet2\", t2)\n\tr.CheckRemoteItems(t, file1dst)\n\tr.CheckLocalItems(t, file1b)\n\n\taccounting.GlobalStats().ResetCounters()\n\terr = Sync(ctx, fdst, r.Flocal, false)\n\trequire.NoError(t, err)\n\n\tfile1bdst := file1b\n\tfile1bdst.Path = \"dst/one\"\n\n\tr.CheckRemoteItems(t, file1bdst)\n\n\t// check old dest, new compare\n\tfile3 := r.WriteObject(ctx, \"dst/one\", \"one\", t1)\n\tfile2 := r.WriteObject(ctx, \"CompareDest/one\", \"onet2\", t2)\n\tfile1c := r.WriteFile(\"one\", \"onet2\", t2)\n\tr.CheckRemoteItems(t, file2, file3)\n\tr.CheckLocalItems(t, file1c)\n\n\taccounting.GlobalStats().ResetCounters()\n\terr = Sync(ctx, fdst, r.Flocal, false)\n\trequire.NoError(t, err)\n\n\tr.CheckRemoteItems(t, file2, file3)\n\n\t// check empty dest, new compare\n\tfile4 := r.WriteObject(ctx, \"CompareDest/two\", \"two\", t2)\n\tfile5 := r.WriteFile(\"two\", \"two\", t2)\n\tr.CheckRemoteItems(t, file2, file3, file4)\n\tr.CheckLocalItems(t, file1c, file5)\n\n\taccounting.GlobalStats().ResetCounters()\n\terr = Sync(ctx, fdst, r.Flocal, false)\n\trequire.NoError(t, err)\n\n\tr.CheckRemoteItems(t, file2, file3, file4)\n\n\t// check new dest, new compare\n\taccounting.GlobalStats().ResetCounters()\n\terr = Sync(ctx, fdst, r.Flocal, false)\n\trequire.NoError(t, err)\n\n\tr.CheckRemoteItems(t, file2, file3, file4)\n\n\t// Work out if we actually have hashes for uploaded files\n\thaveHash := false\n\tif ht := fdst.Hashes().GetOne(); ht != hash.None {\n\t\tfile2obj, err := fdst.NewObject(ctx, \"one\")\n\t\tif err == nil {\n\t\t\tfile2objHash, err := file2obj.Hash(ctx, ht)\n\t\t\tif err == nil {\n\t\t\t\thaveHash = file2objHash != \"\"\n\t\t\t}\n\t\t}\n\t}\n\n\t// check new dest, new compare, src timestamp differs\n\t//\n\t// we only check this if we the file we uploaded previously\n\t// actually has a hash otherwise the differing timestamp is\n\t// always copied.\n\tif haveHash {\n\t\tfile5b := r.WriteFile(\"two\", \"two\", t3)\n\t\tr.CheckLocalItems(t, file1c, file5b)\n\n\t\taccounting.GlobalStats().ResetCounters()\n\t\terr = Sync(ctx, fdst, r.Flocal, false)\n\t\trequire.NoError(t, err)\n\n\t\tr.CheckRemoteItems(t, file2, file3, file4)\n\t} else {\n\t\tt.Log(\"No hash on uploaded file so skipping compare timestamp test\")\n\t}\n\n\t// check empty dest, old compare\n\tfile5c := r.WriteFile(\"two\", \"twot3\", t3)\n\tr.CheckRemoteItems(t, file2, file3, file4)\n\tr.CheckLocalItems(t, file1c, file5c)\n\n\taccounting.GlobalStats().ResetCounters()\n\terr = Sync(ctx, fdst, r.Flocal, false)\n\trequire.NoError(t, err)\n\n\tfile5cdst := file5c\n\tfile5cdst.Path = \"dst/two\"\n\n\tr.CheckRemoteItems(t, file2, file3, file4, file5cdst)\n}", "func (h *InputHost) checkDestination(ctx thrift.Context, path string) (string, shared.DestinationType, metrics.ErrorClass, error) {\n\t// talk to metadata\n\tmGetRequest := shared.ReadDestinationRequest{Path: common.StringPtr(path)}\n\tdestDesc, err := h.mClient.ReadDestination(ctx, &mGetRequest)\n\tif err != nil {\n\t\terrC, newErr := common.ConvertDownstreamErrors(h.logger, err)\n\t\treturn \"\", shared.DestinationType_UNKNOWN, errC, newErr\n\t}\n\n\t// Make sure destDesc cannot be nil\n\tif destDesc == nil {\n\t\terrMsg := fmt.Sprintf(\"unable to get destination description from metadata for dst=%v\", path)\n\t\terrC, newErr := common.ConvertDownstreamErrors(h.logger, &cherami.BadRequestError{Message: errMsg})\n\t\treturn \"\", shared.DestinationType_UNKNOWN, errC, newErr\n\t}\n\n\t// Now make sure the destination is writable\n\tif !h.isDestinationWritable(destDesc) {\n\t\terrMsg := fmt.Sprintf(\"Destination is not writable, dst=%v, status=%v\", path, destDesc.GetStatus())\n\t\terrC, newErr := common.ConvertDownstreamErrors(h.logger, &cherami.BadRequestError{Message: errMsg})\n\t\treturn \"\", shared.DestinationType_UNKNOWN, errC, newErr\n\t}\n\n\treturn destDesc.GetDestinationUUID(), destDesc.GetType(), metrics.NoError, nil\n}", "func mustCopy(dst io.Writer, src io.Reader) {\n\tif _, err := io.Copy(dst, src); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (e *copyS2SMigrationEnumeratorBase) initDestPipeline(ctx context.Context) error {\n\tswitch e.FromTo {\n\t// Currently, e.CredentialInfo is always for the target needs to trigger copy API.\n\t// In this case, blob destination will use it which needs to call StageBlockFromURL later.\n\tcase common.EFromTo.BlobBlob(), common.EFromTo.FileBlob(), common.EFromTo.S3Blob():\n\t\tp, err := createBlobPipeline(ctx, e.CredentialInfo)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\te.destBlobPipeline = p\n\tdefault:\n\t\tpanic(fmt.Errorf(\"invalid from-to pair, %v\", e.FromTo))\n\t}\n\treturn nil\n}", "func (e CopyEntry) Validate() error {\n\tif e.SrcRelPath == \"\" {\n\t\treturn skerr.Fmt(\"SrcRelPath is required\")\n\t}\n\tif e.DstRelPath == \"\" {\n\t\treturn skerr.Fmt(\"DstRelPath is required\")\n\t}\n\treturn nil\n}", "func (o NetworkInterfaceOutput) SourceDestCheck() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v *NetworkInterface) pulumi.BoolPtrOutput { return v.SourceDestCheck }).(pulumi.BoolPtrOutput)\n}", "func TestSyncCopyDest(t *testing.T) {\n\tctx := context.Background()\n\tctx, ci := fs.AddConfig(ctx)\n\tr := fstest.NewRun(t)\n\n\tif r.Fremote.Features().Copy == nil {\n\t\tt.Skip(\"Skipping test as remote does not support server-side copy\")\n\t}\n\n\tci.CopyDest = []string{r.FremoteName + \"/CopyDest\"}\n\n\tfdst, err := fs.NewFs(ctx, r.FremoteName+\"/dst\")\n\trequire.NoError(t, err)\n\n\t// check empty dest, empty copy\n\tfile1 := r.WriteFile(\"one\", \"one\", t1)\n\tr.CheckLocalItems(t, file1)\n\n\taccounting.GlobalStats().ResetCounters()\n\terr = Sync(ctx, fdst, r.Flocal, false)\n\trequire.NoError(t, err)\n\n\tfile1dst := file1\n\tfile1dst.Path = \"dst/one\"\n\n\tr.CheckRemoteItems(t, file1dst)\n\n\t// check old dest, empty copy\n\tfile1b := r.WriteFile(\"one\", \"onet2\", t2)\n\tr.CheckRemoteItems(t, file1dst)\n\tr.CheckLocalItems(t, file1b)\n\n\taccounting.GlobalStats().ResetCounters()\n\terr = Sync(ctx, fdst, r.Flocal, false)\n\trequire.NoError(t, err)\n\n\tfile1bdst := file1b\n\tfile1bdst.Path = \"dst/one\"\n\n\tr.CheckRemoteItems(t, file1bdst)\n\n\t// check old dest, new copy, backup-dir\n\n\tci.BackupDir = r.FremoteName + \"/BackupDir\"\n\n\tfile3 := r.WriteObject(ctx, \"dst/one\", \"one\", t1)\n\tfile2 := r.WriteObject(ctx, \"CopyDest/one\", \"onet2\", t2)\n\tfile1c := r.WriteFile(\"one\", \"onet2\", t2)\n\tr.CheckRemoteItems(t, file2, file3)\n\tr.CheckLocalItems(t, file1c)\n\n\taccounting.GlobalStats().ResetCounters()\n\terr = Sync(ctx, fdst, r.Flocal, false)\n\trequire.NoError(t, err)\n\n\tfile2dst := file2\n\tfile2dst.Path = \"dst/one\"\n\tfile3.Path = \"BackupDir/one\"\n\n\tr.CheckRemoteItems(t, file2, file2dst, file3)\n\tci.BackupDir = \"\"\n\n\t// check empty dest, new copy\n\tfile4 := r.WriteObject(ctx, \"CopyDest/two\", \"two\", t2)\n\tfile5 := r.WriteFile(\"two\", \"two\", t2)\n\tr.CheckRemoteItems(t, file2, file2dst, file3, file4)\n\tr.CheckLocalItems(t, file1c, file5)\n\n\taccounting.GlobalStats().ResetCounters()\n\terr = Sync(ctx, fdst, r.Flocal, false)\n\trequire.NoError(t, err)\n\n\tfile4dst := file4\n\tfile4dst.Path = \"dst/two\"\n\n\tr.CheckRemoteItems(t, file2, file2dst, file3, file4, file4dst)\n\n\t// check new dest, new copy\n\taccounting.GlobalStats().ResetCounters()\n\terr = Sync(ctx, fdst, r.Flocal, false)\n\trequire.NoError(t, err)\n\n\tr.CheckRemoteItems(t, file2, file2dst, file3, file4, file4dst)\n\n\t// check empty dest, old copy\n\tfile6 := r.WriteObject(ctx, \"CopyDest/three\", \"three\", t2)\n\tfile7 := r.WriteFile(\"three\", \"threet3\", t3)\n\tr.CheckRemoteItems(t, file2, file2dst, file3, file4, file4dst, file6)\n\tr.CheckLocalItems(t, file1c, file5, file7)\n\n\taccounting.GlobalStats().ResetCounters()\n\terr = Sync(ctx, fdst, r.Flocal, false)\n\trequire.NoError(t, err)\n\n\tfile7dst := file7\n\tfile7dst.Path = \"dst/three\"\n\n\tr.CheckRemoteItems(t, file2, file2dst, file3, file4, file4dst, file6, file7dst)\n}", "func (e *copyS2SMigrationEnumeratorBase) createDestBucket(ctx context.Context, destURL url.URL, metadata common.Metadata) error {\n\t// TODO: For dry run, createDestBucket should do nothing and directly return.\n\tswitch e.FromTo {\n\tcase common.EFromTo.BlobBlob(), common.EFromTo.FileBlob(), common.EFromTo.S3Blob():\n\t\tif e.destBlobPipeline == nil {\n\t\t\tpanic(errors.New(\"invalid state, blob type destination's pipeline is not initialized\"))\n\t\t}\n\t\ttmpContainerURL := blobURLPartsExtension{azblob.NewBlobURLParts(destURL)}.getContainerURL()\n\t\tcontainerURL := azblob.NewContainerURL(tmpContainerURL, e.destBlobPipeline)\n\t\t// Create the container, in case of it doesn't exist.\n\t\t_, err := containerURL.Create(ctx, metadata.ToAzBlobMetadata(), azblob.PublicAccessNone)\n\t\tif err != nil {\n\t\t\t// Skip the error, when container already exists.\n\t\t\tstgErr, isStgErr := err.(azblob.StorageError)\n\t\t\tif isStgErr && stgErr.ServiceCode() == azblob.ServiceCodeContainerAlreadyExists {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// Skip the error, when azcopy doesn't have permission to create container, and fail to get the info whether container exists.\n\t\t\t// As when it's destination with WRITE only permission, azcopy should try to suppose container already exists and continue transfer.\n\t\t\tif isStgErr && stgErr.Response().StatusCode == http.StatusForbidden { // In this case, we don't know if the container already exists.\n\t\t\t\tif _, getErr := containerURL.GetProperties(ctx, azblob.LeaseAccessConditions{}); getErr == nil {\n\t\t\t\t\t// The container already exists, ignore the create error\n\t\t\t\t\treturn nil\n\t\t\t\t} else {\n\t\t\t\t\t// Cannot get the info whether container exists.\n\t\t\t\t\tstgErr, isStgErr := getErr.(azblob.StorageError)\n\t\t\t\t\tif !isStgErr || stgErr.Response().StatusCode != http.StatusNotFound {\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn fmt.Errorf(\"fail to create container, %v\", err)\n\t\t}\n\tdefault:\n\t\tpanic(fmt.Errorf(\"invalid from-to pair, %v\", e.FromTo))\n\t}\n\treturn nil\n}", "func (m *Map) SafeDestination(loc Location) bool {\n\tif _, exists := m.Water[loc]; exists {\n\t\treturn false\n\t}\n\tif occupied := m.Destinations[loc]; occupied {\n\t\treturn false\n\t}\n\treturn true\n}", "func cpifneeded(src, dest string) error {\n\tif _, err := os.Stat(dest); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn os.Link(src, dest)\n\t\t}\n\t\treturn errors.Wrap(err, \"error getting destination\")\n\t}\n\treturn nil\n}", "func TestCopyFileWithInvalidDest(t *testing.T) {\n\ttempFolder, err := ioutil.TempDir(\"\", \"docker-fileutils-test\")\n\tdefer os.RemoveAll(tempFolder)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsrc := path.Join(tempFolder, \"file\")\n\terr = ioutil.WriteFile(src, []byte(\"content\"), 0740)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbytes, err := CopyFile(src, path.Join(tempFolder, \"/invalid/dest/path\"))\n\tif err == nil {\n\t\tt.Fatal(\"Should have fail to copy an invalid src file\")\n\t}\n\tif bytes != 0 {\n\t\tt.Fatal(\"Should have written 0 bytes\")\n\t}\n\n}", "func (s *DockerCLICpSuite) TestCpCheckDestOwnership(c *testing.T) {\n\ttestRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)\n\ttmpVolDir := getTestDir(c, \"test-cp-tmpvol\")\n\tcontainerID := makeTestContainer(c,\n\t\ttestContainerOptions{volumes: []string{fmt.Sprintf(\"%s:/tmpvol\", tmpVolDir)}})\n\n\ttmpDir := getTestDir(c, \"test-cp-to-check-ownership\")\n\tdefer os.RemoveAll(tmpDir)\n\n\tmakeTestContentInDir(c, tmpDir)\n\n\tsrcPath := cpPath(tmpDir, \"file1\")\n\tdstPath := containerCpPath(containerID, \"/tmpvol\", \"file1\")\n\n\tassert.NilError(c, runDockerCp(c, srcPath, dstPath))\n\n\tstat, err := os.Stat(filepath.Join(tmpVolDir, \"file1\"))\n\tassert.NilError(c, err)\n\tuid, gid, err := getRootUIDGID()\n\tassert.NilError(c, err)\n\tfi := stat.Sys().(*syscall.Stat_t)\n\tassert.Equal(c, fi.Uid, uint32(uid), \"Copied file not owned by container root UID\")\n\tassert.Equal(c, fi.Gid, uint32(gid), \"Copied file not owned by container root GID\")\n}", "func CopyValidator() bool {\n\t// RAW: Implement\n\treturn true\n}", "func (e *copyS2SMigrationEnumeratorBase) isDestBucketSyntactically() bool {\n\tswitch e.FromTo {\n\tcase common.EFromTo.BlobBlob(), common.EFromTo.FileBlob(), common.EFromTo.S3Blob():\n\t\tdsue := blobURLPartsExtension{BlobURLParts: azblob.NewBlobURLParts(*e.destURL)}\n\t\treturn dsue.isContainerSyntactically()\n\tdefault:\n\t\tpanic(fmt.Errorf(\"invalid from-to pair, %v\", e.FromTo))\n\t}\n}", "func TestSyncMultipleCompareDest(t *testing.T) {\n\tctx := context.Background()\n\tctx, ci := fs.AddConfig(ctx)\n\tr := fstest.NewRun(t)\n\tprecision := fs.GetModifyWindow(ctx, r.Fremote, r.Flocal)\n\n\tci.CompareDest = []string{r.FremoteName + \"/pre-dest1\", r.FremoteName + \"/pre-dest2\"}\n\n\t// check empty dest, new compare\n\tfsrc1 := r.WriteFile(\"1\", \"1\", t1)\n\tfsrc2 := r.WriteFile(\"2\", \"2\", t1)\n\tfsrc3 := r.WriteFile(\"3\", \"3\", t1)\n\tr.CheckLocalItems(t, fsrc1, fsrc2, fsrc3)\n\n\tfdest1 := r.WriteObject(ctx, \"pre-dest1/1\", \"1\", t1)\n\tfdest2 := r.WriteObject(ctx, \"pre-dest2/2\", \"2\", t1)\n\tr.CheckRemoteItems(t, fdest1, fdest2)\n\n\taccounting.GlobalStats().ResetCounters()\n\tfdst, err := fs.NewFs(ctx, r.FremoteName+\"/dest\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, Sync(ctx, fdst, r.Flocal, false))\n\n\tfdest3 := fsrc3\n\tfdest3.Path = \"dest/3\"\n\n\tfstest.CheckItemsWithPrecision(t, fdst, precision, fsrc3)\n\tr.CheckRemoteItems(t, fdest1, fdest2, fdest3)\n}", "func TestCopyFileWithInvalidSrc(t *testing.T) {\n\ttempFolder, err := ioutil.TempDir(\"\", \"docker-fileutils-test\")\n\tdefer os.RemoveAll(tempFolder)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbytes, err := CopyFile(\"/invalid/file/path\", path.Join(tempFolder, \"dest\"))\n\tif err == nil {\n\t\tt.Fatal(\"Should have fail to copy an invalid src file\")\n\t}\n\tif bytes != 0 {\n\t\tt.Fatal(\"Should have written 0 bytes\")\n\t}\n\n}", "func (e *copyS2SMigrationEnumeratorBase) isDestServiceSyntactically() bool {\n\tswitch e.FromTo {\n\tcase common.EFromTo.BlobBlob(), common.EFromTo.FileBlob(), common.EFromTo.S3Blob():\n\t\tdsue := blobURLPartsExtension{BlobURLParts: azblob.NewBlobURLParts(*e.destURL)}\n\t\treturn dsue.isServiceSyntactically()\n\tdefault:\n\t\tpanic(fmt.Errorf(\"invalid from-to pair, %v\", e.FromTo))\n\t}\n}", "func (m *ScheduledJobDestination) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (p *PublisherMunger) ensureCloned(dst string, dstURL string) error {\n\tif _, err := os.Stat(dst); err == nil {\n\t\treturn nil\n\t}\n\n\terr := exec.Command(\"mkdir\", \"-p\", dst).Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = exec.Command(\"git\", \"clone\", dstURL, dst).Run()\n\treturn err\n}", "func (e AssignDestAddressRequestValidationError) Reason() string { return e.reason }", "func ensureDestinationExists(source, destination string) error {\n\tfileInfo, err := os.Stat(source)\n\tif err != nil {\n\t\treturn errwrap.Wrap(fmt.Errorf(\"could not stat source location: %v\", source), err)\n\t}\n\n\ttargetPathParent, _ := filepath.Split(destination)\n\tif err := os.MkdirAll(targetPathParent, SharedVolPerm); err != nil {\n\t\treturn errwrap.Wrap(fmt.Errorf(\"could not create parent directory: %v\", targetPathParent), err)\n\t}\n\n\tif fileInfo.IsDir() {\n\t\tif err := os.Mkdir(destination, SharedVolPerm); !os.IsExist(err) {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif file, err := os.OpenFile(destination, os.O_CREATE, SharedVolPerm); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tfile.Close()\n\t\t}\n\t}\n\treturn nil\n}", "func (f *Sink) moveFailed(endpoint *Endpoint) {\n\t// Should never get here if we're closing, caller should check IsClosing()\n\tif !endpoint.IsAlive() {\n\t\treturn\n\t}\n\n\tif endpoint.isReady {\n\t\tf.readyList.Remove(&endpoint.readyElement)\n\t\tendpoint.isReady = false\n\t}\n\n\tif endpoint.IsFull() {\n\t\tf.fullList.Remove(&endpoint.readyElement)\n\t}\n\n\tendpoint.mutex.Lock()\n\tendpoint.status = endpointStatusFailed\n\tendpoint.averageLatency = 0\n\tendpoint.mutex.Unlock()\n\n\tf.failedList.PushFront(&endpoint.failedElement)\n}", "func checkMountDestination(rootfs, dest string) error {\n\tinvalidDestinations := []string{\n\t\t\"/proc\",\n\t}\n\t// White list, it should be sub directories of invalid destinations\n\tvalidDestinations := []string{\n\t\t// These entries can be bind mounted by files emulated by fuse,\n\t\t// so commands like top, free displays stats in container.\n\t\t\"/proc/cpuinfo\",\n\t\t\"/proc/diskstats\",\n\t\t\"/proc/meminfo\",\n\t\t\"/proc/stat\",\n\t\t\"/proc/net/dev\",\n\t}\n\tfor _, valid := range validDestinations {\n\t\tpath, err := filepath.Rel(filepath.Join(rootfs, valid), dest)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif path == \".\" {\n\t\t\treturn nil\n\t\t}\n\t}\n\tfor _, invalid := range invalidDestinations {\n\t\tpath, err := filepath.Rel(filepath.Join(rootfs, invalid), dest)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif path == \".\" || !strings.HasPrefix(path, \"..\") {\n\t\t\treturn fmt.Errorf(\"%q cannot be mounted because it is located inside %q\", dest, invalid)\n\t\t}\n\n\t}\n\treturn nil\n}", "func (p *Plugin) validateMoveOrCopy(wpl *WranglerPostList, originalChannel *model.Channel, targetChannel *model.Channel, extra *model.CommandArgs) (*model.CommandResponse, bool, error) {\n\tif wpl.NumPosts() == 0 {\n\t\treturn nil, false, errors.New(\"The wrangler post list contains no posts\")\n\t}\n\n\tconfig := p.getConfiguration()\n\n\tswitch originalChannel.Type {\n\tcase model.CHANNEL_PRIVATE:\n\t\tif !config.MoveThreadFromPrivateChannelEnable {\n\t\t\treturn getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, \"Wrangler is currently configured to not allow moving posts from private channels\"), false, nil\n\t\t}\n\tcase model.CHANNEL_DIRECT:\n\t\tif !config.MoveThreadFromDirectMessageChannelEnable {\n\t\t\treturn getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, \"Wrangler is currently configured to not allow moving posts from direct message channels\"), false, nil\n\t\t}\n\tcase model.CHANNEL_GROUP:\n\t\tif !config.MoveThreadFromGroupMessageChannelEnable {\n\t\t\treturn getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, \"Wrangler is currently configured to not allow moving posts from group message channels\"), false, nil\n\t\t}\n\t}\n\n\tif !originalChannel.IsGroupOrDirect() {\n\t\t// DM and GM channels are \"teamless\" so it doesn't make sense to check\n\t\t// the MoveThreadToAnotherTeamEnable config when dealing with those.\n\t\tif !config.MoveThreadToAnotherTeamEnable && targetChannel.TeamId != originalChannel.TeamId {\n\t\t\treturn getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, \"Wrangler is currently configured to not allow moving messages to different teams\"), false, nil\n\t\t}\n\t}\n\n\tif config.MaxThreadCountMoveSizeInt() != 0 && config.MaxThreadCountMoveSizeInt() < wpl.NumPosts() {\n\t\treturn getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, fmt.Sprintf(\"Error: the thread is %d posts long, but this command is configured to only move threads of up to %d posts\", wpl.NumPosts(), config.MaxThreadCountMoveSizeInt())), true, nil\n\t}\n\n\tif wpl.RootPost().ChannelId != extra.ChannelId {\n\t\treturn getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, \"Error: this command must be run from the channel containing the post\"), true, nil\n\t}\n\n\t_, appErr := p.API.GetChannelMember(targetChannel.Id, extra.UserId)\n\tif appErr != nil {\n\t\treturn getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, fmt.Sprintf(\"Error: channel with ID %s doesn't exist or you are not a member\", targetChannel.Id)), true, nil\n\t}\n\n\tif extra.RootId == wpl.RootPost().Id || extra.ParentId == wpl.RootPost().Id {\n\t\treturn getCommandResponse(model.COMMAND_RESPONSE_TYPE_EPHEMERAL, \"Error: this command cannot be run from inside the thread; please run directly in the channel containing the thread\"), true, nil\n\t}\n\n\treturn nil, false, nil\n}", "func validateOutputFiles(copies []*sbox_proto.Copy, sandboxDir string) []error {\n\tvar missingOutputErrors []error\n\tfor _, copyPair := range copies {\n\t\tfromPath := joinPath(sandboxDir, copyPair.GetFrom())\n\t\tfileInfo, err := os.Stat(fromPath)\n\t\tif err != nil {\n\t\t\tmissingOutputErrors = append(missingOutputErrors, fmt.Errorf(\"%s: does not exist\", fromPath))\n\t\t\tcontinue\n\t\t}\n\t\tif fileInfo.IsDir() {\n\t\t\tmissingOutputErrors = append(missingOutputErrors, fmt.Errorf(\"%s: not a file\", fromPath))\n\t\t}\n\t}\n\treturn missingOutputErrors\n}", "func checkParameters(src []string, dest string, algorithm string) (is bool) {\n\tis = true\n\t// check src\n\tif len(src) == 0 {\n\t\tis = false\n\t\tfmt.Println(\"Source file list can't be empty.\")\n\t\treturn is\n\t}\n\tfor i := 0; i < len(src); i++ {\n\t\tis, _ = PathExist(src[i])\n\t\tif !is {\n\t\t\tfmt.Printf(\"Source file %v path not exist.\\n\", i+1)\n\t\t\treturn is\n\t\t}\n\t}\n\t// check algorithm\n\tswitch algorithm {\n\tcase \"AES\", \"aes\":\n\tcase \"DES\", \"des\":\n\tcase \"3DES\", \"3des\":\n\tcase \"RSA\", \"rsa\":\n\tcase \"BASE64\", \"base64\":\n\tdefault:\n\t\tis = false\n\t\tfmt.Printf(\"Algorithm %v not support.\\n\", algorithm)\n\t}\n\treturn is\n}", "func copyNonZeroFrom(src, dst *storeSnap) {\n\tif len(src.Architectures) > 0 {\n\t\tdst.Architectures = src.Architectures\n\t}\n\tif src.Base != \"\" {\n\t\tdst.Base = src.Base\n\t}\n\tif src.Confinement != \"\" {\n\t\tdst.Confinement = src.Confinement\n\t}\n\tif src.Contact != \"\" {\n\t\tdst.Contact = src.Contact\n\t}\n\tif src.CreatedAt != \"\" {\n\t\tdst.CreatedAt = src.CreatedAt\n\t}\n\tif src.Description.Clean() != \"\" {\n\t\tdst.Description = src.Description\n\t}\n\tif src.Download.URL != \"\" {\n\t\tdst.Download = src.Download\n\t}\n\tif src.Epoch.String() != \"0\" {\n\t\tdst.Epoch = src.Epoch\n\t}\n\tif src.License != \"\" {\n\t\tdst.License = src.License\n\t}\n\tif src.Name != \"\" {\n\t\tdst.Name = src.Name\n\t}\n\tif len(src.Prices) > 0 {\n\t\tdst.Prices = src.Prices\n\t}\n\tif src.Private {\n\t\tdst.Private = src.Private\n\t}\n\tif src.Publisher.ID != \"\" {\n\t\tdst.Publisher = src.Publisher\n\t}\n\tif src.Revision > 0 {\n\t\tdst.Revision = src.Revision\n\t}\n\tif src.SnapID != \"\" {\n\t\tdst.SnapID = src.SnapID\n\t}\n\tif src.SnapYAML != \"\" {\n\t\tdst.SnapYAML = src.SnapYAML\n\t}\n\tif src.Summary.Clean() != \"\" {\n\t\tdst.Summary = src.Summary\n\t}\n\tif src.Title.Clean() != \"\" {\n\t\tdst.Title = src.Title\n\t}\n\tif src.Type != \"\" {\n\t\tdst.Type = src.Type\n\t}\n\tif src.Version != \"\" {\n\t\tdst.Version = src.Version\n\t}\n\tif len(src.Media) > 0 {\n\t\tdst.Media = src.Media\n\t}\n\tif len(src.CommonIDs) > 0 {\n\t\tdst.CommonIDs = src.CommonIDs\n\t}\n}", "func (upvc *UnsavedPostVideoCreate) check() error {\n\tif _, ok := upvc.mutation.UUID(); !ok {\n\t\treturn &ValidationError{Name: \"uuid\", err: errors.New(\"ent: missing required field \\\"uuid\\\"\")}\n\t}\n\tif v, ok := upvc.mutation.UUID(); ok {\n\t\tif err := unsavedpostvideo.UUIDValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"uuid\", err: fmt.Errorf(\"ent: validator failed for field \\\"uuid\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := upvc.mutation.Validity(); !ok {\n\t\treturn &ValidationError{Name: \"validity\", err: errors.New(\"ent: missing required field \\\"validity\\\"\")}\n\t}\n\tif v, ok := upvc.mutation.Validity(); ok {\n\t\tif err := unsavedpostvideo.ValidityValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"validity\", err: fmt.Errorf(\"ent: validator failed for field \\\"validity\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := upvc.mutation.Title(); ok {\n\t\tif err := unsavedpostvideo.TitleValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"title\", err: fmt.Errorf(\"ent: validator failed for field \\\"title\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := upvc.mutation.URL(); ok {\n\t\tif err := unsavedpostvideo.URLValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"url\", err: fmt.Errorf(\"ent: validator failed for field \\\"url\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := upvc.mutation.CreatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"created_at\", err: errors.New(\"ent: missing required field \\\"created_at\\\"\")}\n\t}\n\tif _, ok := upvc.mutation.UnsavedPostID(); !ok {\n\t\treturn &ValidationError{Name: \"unsaved_post\", err: errors.New(\"ent: missing required edge \\\"unsaved_post\\\"\")}\n\t}\n\treturn nil\n}", "func (t Transition) Validate() error {\n\tif _, err := sdk.AccAddressFromBech32(t.Subject); err != nil {\n\t\treturn errors.Wrap(err, \"invalid subject address\")\n\t}\n\tif _, err := sdk.AccAddressFromBech32(t.Destination); err != nil {\n\t\treturn errors.Wrap(err, \"invalid destination address\")\n\t}\n\treturn nil\n}", "func (dsc *DataSourceCreate) check() error {\n\tif _, ok := dsc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(`ent: missing required field \"DataSource.name\"`)}\n\t}\n\tif v, ok := dsc.mutation.Name(); ok {\n\t\tif err := datasource.NameValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"name\", err: fmt.Errorf(`ent: validator failed for field \"DataSource.name\": %w`, err)}\n\t\t}\n\t}\n\tif _, ok := dsc.mutation.Address(); !ok {\n\t\treturn &ValidationError{Name: \"address\", err: errors.New(`ent: missing required field \"DataSource.address\"`)}\n\t}\n\treturn nil\n}", "func (c clone) dest(context ggman.Context, url env.URL) (string, error) {\n\tif c.Here || c.Local { // clone into directory named automatically\n\t\tcomps := url.Components()\n\t\tif len(comps) == 0 {\n\t\t\treturn \"\", errCloneNoComps\n\t\t}\n\t\treturn context.Environment.Abs(comps[len(comps)-1])\n\t}\n\n\tif c.To != \"\" { // clone directory into a directory\n\t\treturn context.Environment.Abs(c.To)\n\t}\n\n\t// normal clone!\n\treturn context.Environment.Local(url)\n}", "func (p params) allowsFolderTransfers() bool {\n\treturn !p.destNull && p.includePattern+p.includeAttributes+p.excludePattern+p.excludeAttributes == \"\"\n}", "func (etc *ExportTaskCreate) check() error {\n\tif _, ok := etc.mutation.GetType(); !ok {\n\t\treturn &ValidationError{Name: \"type\", err: errors.New(\"ent: missing required field \\\"type\\\"\")}\n\t}\n\tif v, ok := etc.mutation.GetType(); ok {\n\t\tif err := exporttask.TypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"type\", err: fmt.Errorf(\"ent: validator failed for field \\\"type\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := etc.mutation.Status(); !ok {\n\t\treturn &ValidationError{Name: \"status\", err: errors.New(\"ent: missing required field \\\"status\\\"\")}\n\t}\n\tif v, ok := etc.mutation.Status(); ok {\n\t\tif err := exporttask.StatusValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"status\", err: fmt.Errorf(\"ent: validator failed for field \\\"status\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := etc.mutation.Progress(); !ok {\n\t\treturn &ValidationError{Name: \"progress\", err: errors.New(\"ent: missing required field \\\"progress\\\"\")}\n\t}\n\tif v, ok := etc.mutation.Progress(); ok {\n\t\tif err := exporttask.ProgressValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"progress\", err: fmt.Errorf(\"ent: validator failed for field \\\"progress\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := etc.mutation.Filters(); !ok {\n\t\treturn &ValidationError{Name: \"filters\", err: errors.New(\"ent: missing required field \\\"filters\\\"\")}\n\t}\n\treturn nil\n}", "func TestDiff_srcDestContentsDiffer(t *testing.T) {\n\ts := t.TempDir()\n\td := t.TempDir()\n\n\terr := os.Mkdir(filepath.Join(s, \"a1\"), 0700)\n\tassert.NoError(t, err)\n\terr = os.WriteFile(\n\t\tfilepath.Join(s, \"a1\", \"f.yaml\"), []byte(`a`), 0600)\n\tassert.NoError(t, err)\n\n\terr = os.Mkdir(filepath.Join(d, \"a1\"), 0700)\n\tassert.NoError(t, err)\n\terr = os.WriteFile(\n\t\tfilepath.Join(d, \"a1\", \"f.yaml\"), []byte(`b`), 0600)\n\tassert.NoError(t, err)\n\n\tdiff, err := Diff(s, d)\n\tassert.NoError(t, err)\n\tassert.ElementsMatch(t, diff.List(), []string{\n\t\tfmt.Sprintf(\"a1%sf.yaml\", string(filepath.Separator)),\n\t})\n}", "func copySpec(in copySpecInput) error {\n\t// Backup fields that should be preserved from dest.\n\tpreservedFields := map[string]interface{}{}\n\tfor _, field := range in.fieldsToPreserve {\n\t\tvalue, found, err := unstructured.NestedFieldNoCopy(in.dest.Object, field...)\n\t\tif !found {\n\t\t\t// Continue if the field does not exist in src. fieldsToPreserve don't have to exist.\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to get field %q from %s\", strings.Join(field, \".\"), tlog.KObj{Obj: in.dest})\n\t\t}\n\t\tpreservedFields[strings.Join(field, \".\")] = value\n\t}\n\n\t// Get spec from src.\n\tsrcSpec, found, err := unstructured.NestedFieldNoCopy(in.src.Object, strings.Split(in.srcSpecPath, \".\")...)\n\tif !found {\n\t\treturn errors.Errorf(\"missing field %q in %s\", in.srcSpecPath, tlog.KObj{Obj: in.src})\n\t} else if err != nil {\n\t\treturn errors.Wrapf(err, \"failed to get field %q from %s\", in.srcSpecPath, tlog.KObj{Obj: in.src})\n\t}\n\n\t// Set spec in dest.\n\tif err := unstructured.SetNestedField(in.dest.Object, srcSpec, strings.Split(in.destSpecPath, \".\")...); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to set field %q on %s\", in.destSpecPath, tlog.KObj{Obj: in.dest})\n\t}\n\n\t// Restore preserved fields.\n\tfor path, value := range preservedFields {\n\t\tif err := unstructured.SetNestedField(in.dest.Object, value, strings.Split(path, \".\")...); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to set field %q on %s\", path, tlog.KObj{Obj: in.dest})\n\t\t}\n\t}\n\treturn nil\n}", "func (t *Transport) buildDest() string {\n\tdst := t.config.DestDir\n\tif t.config.DestHost != \"\" {\n\t\tdst = t.config.DestHost + \":\" + dst\n\t}\n\treturn dst\n}", "func (store *ConfigurationStore) validateSecretDestinations() (admission.Warnings, error) {\n\tif store.Spec.OperatorSpec == nil {\n\t\treturn nil, nil\n\t}\n\tif store.Spec.OperatorSpec.Secrets == nil {\n\t\treturn nil, nil\n\t}\n\ttoValidate := []*genruntime.SecretDestination{\n\t\tstore.Spec.OperatorSpec.Secrets.PrimaryConnectionString,\n\t\tstore.Spec.OperatorSpec.Secrets.PrimaryKey,\n\t\tstore.Spec.OperatorSpec.Secrets.PrimaryKeyID,\n\t\tstore.Spec.OperatorSpec.Secrets.PrimaryReadOnlyConnectionString,\n\t\tstore.Spec.OperatorSpec.Secrets.PrimaryReadOnlyKey,\n\t\tstore.Spec.OperatorSpec.Secrets.PrimaryReadOnlyKeyID,\n\t\tstore.Spec.OperatorSpec.Secrets.SecondaryConnectionString,\n\t\tstore.Spec.OperatorSpec.Secrets.SecondaryKey,\n\t\tstore.Spec.OperatorSpec.Secrets.SecondaryKeyID,\n\t\tstore.Spec.OperatorSpec.Secrets.SecondaryReadOnlyConnectionString,\n\t\tstore.Spec.OperatorSpec.Secrets.SecondaryReadOnlyKey,\n\t\tstore.Spec.OperatorSpec.Secrets.SecondaryReadOnlyKeyID,\n\t}\n\treturn genruntime.ValidateSecretDestinations(toValidate)\n}", "func validateWorkflow(m *workflow.Manager, keyspace string, vtworkers, sourceShards, destinationShards []string, minHealthyRdonlyTablets string, skipSplitRatioCheck bool) error {\n\tif len(sourceShards) == 0 || len(destinationShards) == 0 {\n\t\treturn fmt.Errorf(\"invalid source or destination shards\")\n\t}\n\tif len(vtworkers) != len(destinationShards) {\n\t\treturn fmt.Errorf(\"there are %v vtworkers, %v destination shards: the number should be same\", len(vtworkers), len(destinationShards))\n\t}\n\n\tsplitRatio := len(destinationShards) / len(sourceShards)\n\tif minHealthyRdonlyTabletsVal, err := strconv.Atoi(minHealthyRdonlyTablets); err != nil || (!skipSplitRatioCheck && minHealthyRdonlyTabletsVal < splitRatio) {\n\t\treturn fmt.Errorf(\"there are not enough rdonly tablets in source shards. You need at least %v, it got: %v\", splitRatio, minHealthyRdonlyTablets)\n\t}\n\n\t// find the OverlappingShards in the keyspace\n\tosList, err := topotools.FindOverlappingShards(context.Background(), m.TopoServer(), keyspace)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot FindOverlappingShards in %v: %v\", keyspace, err)\n\t}\n\n\t// find the shard we mentioned in there, if any\n\tos := topotools.OverlappingShardsForShard(osList, sourceShards[0])\n\tif os == nil {\n\t\treturn fmt.Errorf(\"the specified source shard %v/%v is not in any overlapping shard\", keyspace, sourceShards[0])\n\t}\n\tfor _, sourceShard := range sourceShards {\n\t\tif !os.ContainsShard(sourceShard) {\n\t\t\treturn fmt.Errorf(\"the specified source shard %v/%v is not in any overlapping shard\", keyspace, sourceShard)\n\t\t}\n\t}\n\tfor _, destinationShard := range destinationShards {\n\t\tif !os.ContainsShard(destinationShard) {\n\t\t\treturn fmt.Errorf(\"the specified destination shard %v/%v is not in any overlapping shard\", keyspace, destinationShard)\n\t\t}\n\t}\n\treturn nil\n}", "func CanCopy(source, dest *bigquery.Table) bool {\n\tif dest == nil || source == nil || dest.Schema == nil || source.Schema == nil {\n\t\treturn true\n\t}\n\tsourceColumns := IndexFields(source.Schema.Fields)\n\tdestColumns := IndexFields(dest.Schema.Fields)\n\tfor k := range destColumns {\n\t\tdelete(sourceColumns, k)\n\t}\n\treturn len(sourceColumns) == 0\n}", "func (e MovableObjectValidationError) Cause() error { return e.cause }", "func (v EditValidator) Copy() StakeMsg {\n\tv1 := v\n\tdesc := *v.Description\n\tv1.Description = &desc\n\treturn v1\n}", "func (e UpstreamValidationError) Cause() error { return e.cause }", "func (e UpstreamValidationError) Cause() error { return e.cause }", "func destinationSync(ctx context.Context, name string,\n\toriginConsul *consul.Client, originSyncPath string, originVault *vault.Client, originMounts []string,\n\tdestinationConsul *consul.Client, destinationSyncPath string, destinationVault *vault.Client, destinationMounts []string,\n\tpack transformer.Pack,\n\thasher hash.Hash, numBuckets int, timeout time.Duration, numWorkers int,\n\ttriggerCh chan bool, errCh chan error) {\n\n\tconst op = apperr.Op(\"cmd.destinationSync\")\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\ttime.Sleep(100 * time.Microsecond)\n\t\t\ttelemetryClient.Count(\"vsync.destination.cycle\", 1, \"status:stopped\")\n\t\t\tlog.Debug().Str(\"trigger\", \"context done\").Msg(\"closed destination sync\")\n\t\t\treturn\n\t\tcase _, ok := <-triggerCh:\n\t\t\tif !ok {\n\t\t\t\ttime.Sleep(100 * time.Microsecond)\n\t\t\t\tlog.Debug().Str(\"trigger\", \"nil channel\").Msg(\"closed destination sync\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttelemetryClient.Count(\"vsync.destination.cycle\", 1, \"status:started\")\n\t\t\tlog.Info().Msg(\"\")\n\t\t\tlog.Debug().Msg(\"sync info changed in origin\")\n\n\t\t\tsyncCtx, syncCancel := context.WithTimeout(ctx, timeout)\n\n\t\t\t// check origin token permission before starting each cycle\n\t\t\tfor _, oMount := range originMounts {\n\t\t\t\terr := originVault.MountChecks(oMount, vault.CheckOrigin, name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Debug().Err(err).Msg(\"failures on data paths checks on origin\")\n\t\t\t\t\terrCh <- apperr.New(fmt.Sprintf(\"failures on data paths checks on origin\"), err, op, apperr.Fatal, ErrInitialize)\n\n\t\t\t\t\tsyncCancel()\n\t\t\t\t\ttime.Sleep(500 * time.Microsecond)\n\t\t\t\t\ttelemetryClient.Count(\"vsync.destination.cycle\", 1, \"status:failure\")\n\t\t\t\t\tlog.Info().Msg(\"incomplete sync cycle, failure in vault connectivity or token permission\\n\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdestinationChecks := vault.CheckDestination\n\t\t\tif syncer.IgnoreDeletes {\n\t\t\t\tdestinationChecks = vault.CheckDestinationWithoutDelete\n\t\t\t}\n\n\t\t\t// check destination token permission before starting each cycle\n\t\t\tfor _, dMount := range destinationMounts {\n\t\t\t\terr := destinationVault.MountChecks(dMount, destinationChecks, name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Debug().Err(err).Msg(\"failures on data paths checks on destination\")\n\t\t\t\t\terrCh <- apperr.New(fmt.Sprintf(\"failures on data paths checks on destination\"), err, op, apperr.Fatal, ErrInitialize)\n\n\t\t\t\t\tsyncCancel()\n\t\t\t\t\ttime.Sleep(500 * time.Microsecond)\n\t\t\t\t\ttelemetryClient.Count(\"vsync.destination.cycle\", 1, \"status:failure\")\n\t\t\t\t\tlog.Info().Msg(\"incomplete sync cycle, failure in vault connectivity or token permission\\n\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// origin sync info\n\t\t\toriginfo, err := syncer.NewInfo(numBuckets, hasher)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug().Err(err).Int(\"numBuckets\", numBuckets).Str(\"path\", originSyncPath).Msg(\"failure in initializing origin sync info\")\n\t\t\t\terrCh <- apperr.New(fmt.Sprintf(\"cannot create new sync info in path %q\", originSyncPath), err, apperr.Fatal, op, ErrInitialize)\n\n\t\t\t\tsyncCancel()\n\t\t\t\ttime.Sleep(100 * time.Microsecond)\n\t\t\t\tlog.Warn().Msg(\"incomplete sync cycle, failure in creating new origin sync info\\n\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\terr = syncer.InfoFromConsul(originConsul, originfo, originSyncPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug().Err(err).Str(\"path\", originSyncPath).Msg(\"cannot get sync info from origin consul\")\n\t\t\t\terrCh <- apperr.New(fmt.Sprintf(\"cannot get sync info in path %q\", originSyncPath), err, apperr.Fatal, op, ErrInvalidInfo)\n\n\t\t\t\tsyncCancel()\n\t\t\t\ttime.Sleep(100 * time.Microsecond)\n\t\t\t\tlog.Warn().Msg(\"incomplete sync cycle, failure in getting origin sync info\\n\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Info().Msg(\"retrieved origin sync info\")\n\n\t\t\t// destination sync info\n\t\t\tdestinationInfo, err := syncer.NewInfo(numBuckets, hasher)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug().Err(err).Int(\"numBuckets\", numBuckets).Str(\"path\", destinationSyncPath).Msg(\"failure in initializing destination sync info\")\n\t\t\t\terrCh <- apperr.New(fmt.Sprintf(\"cannot create new sync info in path %q\", destinationSyncPath), err, apperr.Fatal, op, ErrInitialize)\n\n\t\t\t\tsyncCancel()\n\t\t\t\ttime.Sleep(100 * time.Microsecond)\n\t\t\t\tlog.Warn().Msg(\"incomplete sync cycle, failure in creating new destination sync info\\n\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\terr = syncer.InfoFromConsul(destinationConsul, destinationInfo, destinationSyncPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug().Err(err).Str(\"path\", destinationSyncPath).Msg(\"cannot get sync info from destination consul\")\n\t\t\t\terrCh <- apperr.New(fmt.Sprintf(\"cannot get sync info in path %q\", destinationSyncPath), err, op, apperr.Fatal, ErrInvalidInfo)\n\n\t\t\t\tsyncCancel()\n\t\t\t\ttime.Sleep(100 * time.Microsecond)\n\t\t\t\tlog.Warn().Msg(\"incomplete sync cycle, failure in getting destination sync info\\n\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Info().Msg(\"retrieved destination sync info\")\n\n\t\t\t// compare sync info\n\t\t\taddTasks, updateTasks, deleteTasks, errs := originfo.Compare(destinationInfo)\n\t\t\tfor _, err := range errs {\n\t\t\t\terrCh <- apperr.New(fmt.Sprintf(\"cannot compare origin and destination infos\"), err, op, ErrInvalidInsight)\n\t\t\t}\n\n\t\t\ttelemetryClient.Gauge(\"vsync.destination.paths.to_be_processed\", float64(len(addTasks)), \"operation:add\")\n\t\t\ttelemetryClient.Gauge(\"vsync.destination.paths.to_be_processed\", float64(len(updateTasks)), \"operation:update\")\n\t\t\ttelemetryClient.Gauge(\"vsync.destination.paths.to_be_processed\", float64(len(deleteTasks)), \"operation:delete\")\n\t\t\tlog.Info().Int(\"count\", len(addTasks)).Msg(\"paths to be added to destination\")\n\t\t\tlog.Info().Int(\"count\", len(updateTasks)).Msg(\"paths to be updated to destination\")\n\t\t\tlog.Info().Int(\"count\", len(deleteTasks)).Msg(\"paths to be deleted from destination\")\n\n\t\t\t// create go routines for fetch and save and inturn saves to destination sync info\n\t\t\tvar wg sync.WaitGroup\n\t\t\tinTaskCh := make(chan syncer.Task, numWorkers)\n\t\t\tfor i := 0; i < numWorkers; i++ {\n\t\t\t\twg.Add(1)\n\t\t\t\tgo syncer.FetchAndSave(syncCtx,\n\t\t\t\t\t&wg, i,\n\t\t\t\t\toriginVault, destinationVault,\n\t\t\t\t\tdestinationInfo, pack,\n\t\t\t\t\tinTaskCh,\n\t\t\t\t\terrCh)\n\t\t\t}\n\n\t\t\t// create go routine to save sync info to consul\n\t\t\t// 1 buffer to unblock this main routine in case timeout closes gather go routine\n\t\t\t// so no one exists to send data in saved channel which blocks the main routine\n\t\t\tsaveCh := make(chan bool, 1)\n\t\t\tdoneCh := make(chan bool, 1)\n\t\t\tgo saveInfoToConsul(syncCtx,\n\t\t\t\tdestinationInfo, destinationConsul, destinationSyncPath,\n\t\t\t\tsaveCh, doneCh, errCh)\n\n\t\t\t// no changes\n\t\t\tif len(addTasks) == 0 && len(updateTasks) == 0 && len(deleteTasks) == 0 {\n\t\t\t\tlog.Info().Msg(\"no changes from origin\")\n\n\t\t\t\tsyncCancel()\n\t\t\t\ttime.Sleep(500 * time.Microsecond)\n\t\t\t\tlog.Info().Msg(\"completed sync cycle, no changes\\n\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// we need to send tasks to workers as well as watch for context done\n\t\t\t// in case of more paths and a timeout the worker will exit but we would be waiting forever for some worker to recieve the job\n\t\t\tgo sendTasks(syncCtx, inTaskCh, addTasks, updateTasks, deleteTasks)\n\n\t\t\t// close the inTaskCh and wait for all the workers and sync info to finish\n\t\t\t// in case of timeout the workers\n\t\t\t//\tmostly perform the current processing and then die, so we have to wait till they die\n\t\t\t// \twhich takes at most 1 minute * number of retries per client call\n\t\t\twg.Wait()\n\n\t\t\terr = destinationInfo.Reindex()\n\t\t\tif err != nil {\n\t\t\t\terrCh <- apperr.New(fmt.Sprintf(\"cannot reindex destination info\"), err, op, ErrInvalidInfo)\n\t\t\t}\n\n\t\t\t// trigger save info to consul and wait for done\n\t\t\tsaveCh <- true\n\t\t\tclose(saveCh)\n\n\t\t\tif ok := <-doneCh; ok {\n\t\t\t\tlog.Info().Int(\"buckets\", numBuckets).Msg(\"saved origin sync info in consul\")\n\t\t\t} else {\n\t\t\t\terrCh <- apperr.New(fmt.Sprintf(\"cannot save origin, mostly due to timeout\"), ErrTimout, op, apperr.Fatal)\n\t\t\t}\n\n\t\t\t// cancel any go routine and free context memory\n\t\t\tsyncCancel()\n\t\t\ttime.Sleep(500 * time.Microsecond)\n\t\t\ttelemetryClient.Count(\"vsync.destination.cycle\", 1, \"status:success\")\n\t\t\tlog.Info().Msg(\"completed sync cycle\\n\")\n\t\t}\n\t}\n}", "func copyExistingContents(source, destination string) error {\n\tdstList, err := ioutil.ReadDir(destination)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(dstList) != 0 {\n\t\treturn errors.Errorf(\"volume at %q is not initially empty\", destination)\n\t}\n\treturn fs.CopyDir(destination, source)\n}", "func TestCopyToFinalDest(t *testing.T) {\n\tt.Parallel()\n\n\tt.Run(\"no duplicates\", func(t *testing.T) {\n\t\tdestDir, err := ioutil.TempDir(\"\", \"destDir_unarchive\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.RemoveAll(destDir)\n\n\t\tfileA, err := ioutil.TempFile(destDir, \"fileA.txt\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.Remove(fileA.Name())\n\n\t\tfileB, err := ioutil.TempFile(destDir, \"fileB.txt\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.Remove(fileB.Name())\n\n\t\tddInfo, err := os.Open(destDir)\n\t\trequire.NoError(t, err)\n\t\tdefer ddInfo.Close()\n\n\t\tfetchDir, err := ioutil.TempDir(\"\", \"fetchDir_unarchive\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.RemoveAll(fetchDir)\n\n\t\tfileC, err := ioutil.TempFile(fetchDir, \"fileC.txt\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.Remove(fileC.Name())\n\n\t\tfileD, err := ioutil.TempFile(fetchDir, \"fileD.txt\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.Remove(fileD.Name())\n\n\t\tfdInfo, err := os.Open(fetchDir)\n\t\trequire.NoError(t, err)\n\t\tdefer fdInfo.Close()\n\n\t\tu := &Unarchive{\n\t\t\tdestDir: ddInfo,\n\t\t\tfetchDir: fdInfo,\n\t\t}\n\n\t\terr = filepath.Walk(u.destDir.Name(), func(path string, f os.FileInfo, err error) error {\n\t\t\tu.destContents = append(u.destContents, path)\n\t\t\treturn nil\n\t\t})\n\t\trequire.NoError(t, err)\n\n\t\terr = filepath.Walk(u.fetchDir.Name(), func(path string, f os.FileInfo, err error) error {\n\t\t\tu.fetchContents = append(u.fetchContents, path)\n\t\t\treturn nil\n\t\t})\n\t\trequire.NoError(t, err)\n\n\t\texp := []string{destDir, \"fileA.txt\", \"fileB.txt\", \"fileC.txt\", \"fileD.txt\"}\n\n\t\ttestErr := u.copyToFinalDest()\n\n\t\tact := []string{}\n\t\terr = filepath.Walk(u.destDir.Name(), func(path string, f os.FileInfo, err error) error {\n\t\t\tact = append(act, path)\n\t\t\treturn nil\n\t\t})\n\t\trequire.NoError(t, err)\n\n\t\tassert.NoError(t, testErr)\n\t\tassert.Equal(t, 5, len(act))\n\t\tassert.True(t, strings.Contains(act[0], exp[0]) || strings.Contains(act[1], exp[0]) || strings.Contains(act[2], exp[0]) || strings.Contains(act[3], exp[0]) || strings.Contains(act[4], exp[0]))\n\t\tassert.True(t, strings.Contains(act[0], exp[1]) || strings.Contains(act[1], exp[1]) || strings.Contains(act[2], exp[1]) || strings.Contains(act[3], exp[1]) || strings.Contains(act[4], exp[1]))\n\t\tassert.True(t, strings.Contains(act[0], exp[2]) || strings.Contains(act[1], exp[2]) || strings.Contains(act[2], exp[2]) || strings.Contains(act[3], exp[2]) || strings.Contains(act[4], exp[2]))\n\t\tassert.True(t, strings.Contains(act[0], exp[3]) || strings.Contains(act[1], exp[3]) || strings.Contains(act[2], exp[3]) || strings.Contains(act[3], exp[3]) || strings.Contains(act[4], exp[3]))\n\t\tassert.True(t, strings.Contains(act[0], exp[4]) || strings.Contains(act[1], exp[4]) || strings.Contains(act[2], exp[4]) || strings.Contains(act[3], exp[4]) || strings.Contains(act[4], exp[4]))\n\t})\n\n\tt.Run(\"duplicates\", func(t *testing.T) {\n\t\tdestDir, err := ioutil.TempDir(\"\", \"destDir_unarchive\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.RemoveAll(destDir)\n\n\t\tfileADest, err := os.Create(destDir + \"/fileA.txt\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.Remove(fileADest.Name())\n\n\t\tddInfo, err := os.Open(destDir)\n\t\trequire.NoError(t, err)\n\t\tdefer ddInfo.Close()\n\n\t\tfetchDir, err := ioutil.TempDir(\"\", \"fetchDir_unarchive\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.RemoveAll(fetchDir)\n\n\t\tfileAFetch, err := os.Create(fetchDir + \"/fileA.txt\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.Remove(fileAFetch.Name())\n\n\t\tfdInfo, err := os.Open(fetchDir)\n\t\trequire.NoError(t, err)\n\t\tdefer fdInfo.Close()\n\n\t\tt.Run(\"checksum match\", func(t *testing.T) {\n\t\t\tu := &Unarchive{\n\t\t\t\tdestDir: ddInfo,\n\t\t\t\tfetchDir: fdInfo,\n\t\t\t}\n\n\t\t\tchecksumDest, err := u.getChecksum(destDir + \"/fileA.txt\")\n\t\t\trequire.NoError(t, err)\n\t\t\tchecksumFetch, err := u.getChecksum(fetchDir + \"/fileA.txt\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, checksumDest, checksumFetch)\n\n\t\t\terr = filepath.Walk(u.destDir.Name(), func(path string, f os.FileInfo, err error) error {\n\t\t\t\tu.destContents = append(u.destContents, path)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = filepath.Walk(u.fetchDir.Name(), func(path string, f os.FileInfo, err error) error {\n\t\t\t\tu.fetchContents = append(u.fetchContents, path)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\n\t\t\texp := []string{destDir, \"fileA.txt\"}\n\n\t\t\ttestErr := u.copyToFinalDest()\n\n\t\t\tact := []string{}\n\t\t\terr = filepath.Walk(u.destDir.Name(), func(path string, f os.FileInfo, err error) error {\n\t\t\t\tact = append(act, path)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.NoError(t, testErr)\n\t\t\tassert.Equal(t, 2, len(act))\n\t\t\tassert.True(t, strings.Contains(act[0], exp[0]) || strings.Contains(act[1], exp[0]))\n\t\t\tassert.True(t, strings.Contains(act[0], exp[1]) || strings.Contains(act[1], exp[1]))\n\t\t})\n\n\t\tt.Run(\"checksum mismatch\", func(t *testing.T) {\n\t\t\tfileBDest, err := os.Create(destDir + \"/fileB.txt\")\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer os.Remove(fileBDest.Name())\n\n\t\t\tfileBFetch, err := os.Create(fetchDir + \"/fileB.txt\")\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer os.Remove(fileBFetch.Name())\n\n\t\t\t_, err = fileBFetch.Write([]byte{1})\n\t\t\trequire.NoError(t, err)\n\n\t\t\tu := &Unarchive{\n\t\t\t\tDestination: destDir,\n\t\t\t\tdestDir: ddInfo,\n\t\t\t\tfetchDir: fdInfo,\n\t\t\t}\n\n\t\t\tchecksumDest, err := u.getChecksum(destDir + \"/fileB.txt\")\n\t\t\trequire.NoError(t, err)\n\t\t\tchecksumFetch, err := u.getChecksum(fetchDir + \"/fileB.txt\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotEqual(t, checksumDest, checksumFetch)\n\n\t\t\terr = filepath.Walk(u.destDir.Name(), func(path string, f os.FileInfo, err error) error {\n\t\t\t\tu.destContents = append(u.destContents, path)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = filepath.Walk(u.fetchDir.Name(), func(path string, f os.FileInfo, err error) error {\n\t\t\t\tu.fetchContents = append(u.fetchContents, path)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\n\t\t\texp := []string{destDir, \"fileA.txt\", \"fileB.txt\"}\n\n\t\t\ttestErr := u.copyToFinalDest()\n\n\t\t\tact := []string{}\n\t\t\terr = filepath.Walk(u.destDir.Name(), func(path string, f os.FileInfo, err error) error {\n\t\t\t\tact = append(act, path)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\n\t\t\tchecksumDest, err = u.getChecksum(destDir + \"/fileB.txt\")\n\t\t\trequire.NoError(t, err)\n\t\t\tchecksumFetch, err = u.getChecksum(fetchDir + \"/fileB.txt\")\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.NoError(t, testErr)\n\t\t\tassert.Equal(t, 3, len(act))\n\t\t\tassert.True(t, strings.Contains(act[0], exp[0]) || strings.Contains(act[1], exp[0]) || strings.Contains(act[2], exp[0]))\n\t\t\tassert.True(t, strings.Contains(act[0], exp[1]) || strings.Contains(act[1], exp[1]) || strings.Contains(act[2], exp[1]))\n\t\t\tassert.True(t, strings.Contains(act[0], exp[2]) || strings.Contains(act[1], exp[2]) || strings.Contains(act[2], exp[2]))\n\t\t\tassert.Equal(t, checksumDest, checksumFetch)\n\t\t})\n\t})\n\n\tt.Run(\"recurse\", func(t *testing.T) {\n\t\tdestDir, err := ioutil.TempDir(\"\", \"destDir_unarchive\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.RemoveAll(destDir)\n\n\t\tddInfo, err := os.Open(destDir)\n\t\trequire.NoError(t, err)\n\t\tdefer ddInfo.Close()\n\n\t\tfetchDir, err := ioutil.TempDir(\"\", \"fetchDir_unarchive\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.RemoveAll(fetchDir)\n\n\t\tdirA, err := ioutil.TempDir(fetchDir, \"dirA\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.RemoveAll(dirA)\n\n\t\tdirB, err := ioutil.TempDir(dirA, \"dirB\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.RemoveAll(dirB)\n\n\t\tdirC, err := ioutil.TempDir(dirB, \"dirC\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.RemoveAll(dirC)\n\n\t\tfileC, err := os.Create(dirC + \"/fileC.txt\")\n\t\trequire.NoError(t, err)\n\t\tdefer os.Remove(fileC.Name())\n\n\t\tfdInfo, err := os.Open(fetchDir)\n\t\trequire.NoError(t, err)\n\t\tdefer fdInfo.Close()\n\n\t\tu := &Unarchive{\n\t\t\tDestination: destDir,\n\t\t\tdestDir: ddInfo,\n\t\t\tfetchDir: fdInfo,\n\t\t}\n\n\t\terr = filepath.Walk(u.destDir.Name(), func(path string, f os.FileInfo, err error) error {\n\t\t\tu.destContents = append(u.destContents, path)\n\t\t\treturn nil\n\t\t})\n\t\trequire.NoError(t, err)\n\n\t\terr = filepath.Walk(u.fetchDir.Name(), func(path string, f os.FileInfo, err error) error {\n\t\t\tu.fetchContents = append(u.fetchContents, path)\n\t\t\treturn nil\n\t\t})\n\t\trequire.NoError(t, err)\n\n\t\texp := []string{destDir, \"dirA\", \"dirB\", \"dirC\", \"fileC.txt\"}\n\n\t\ttestErr := u.copyToFinalDest()\n\n\t\tact := []string{}\n\t\terr = filepath.Walk(u.destDir.Name(), func(path string, f os.FileInfo, err error) error {\n\t\t\tact = append(act, path)\n\t\t\treturn nil\n\t\t})\n\t\trequire.NoError(t, err)\n\n\t\tassert.NoError(t, testErr)\n\t\tassert.Equal(t, 5, len(act))\n\t\tassert.True(t, strings.Contains(act[0], exp[0]) || strings.Contains(act[1], exp[0]) || strings.Contains(act[2], exp[0]) || strings.Contains(act[3], exp[0]) || strings.Contains(act[4], exp[0]))\n\t\tassert.True(t, strings.Contains(act[0], exp[1]) || strings.Contains(act[1], exp[1]) || strings.Contains(act[2], exp[1]) || strings.Contains(act[3], exp[1]) || strings.Contains(act[4], exp[1]))\n\t\tassert.True(t, strings.Contains(act[0], exp[2]) || strings.Contains(act[1], exp[2]) || strings.Contains(act[2], exp[2]) || strings.Contains(act[3], exp[2]) || strings.Contains(act[4], exp[2]))\n\t\tassert.True(t, strings.Contains(act[0], exp[3]) || strings.Contains(act[1], exp[3]) || strings.Contains(act[2], exp[3]) || strings.Contains(act[3], exp[3]) || strings.Contains(act[4], exp[3]))\n\t\tassert.True(t, strings.Contains(act[0], exp[4]) || strings.Contains(act[1], exp[4]) || strings.Contains(act[2], exp[4]) || strings.Contains(act[3], exp[4]) || strings.Contains(act[4], exp[4]))\n\t})\n}", "func (state *SandboxState) ValidTransition(oldState StateString, newState StateString) error {\n\treturn state.State.validTransition(oldState, newState)\n}", "func (p *Partitions) Validate(ctx *shared.Context, comparator *Comparator, source, dest Record) error {\n\tkeys := p.Partition.Columns\n\tif len(keys) == 0 {\n\t\treturn nil\n\t}\n\tif len(dest) == 0 {\n\t\treturn nil\n\t}\n\tif !comparator.AreKeysInSync(ctx, keys, source, dest) {\n\t\tvar dataInfo = make([]string, 0)\n\t\tfor i := range keys {\n\t\t\tsourceValue := source[keys[i]]\n\t\t\tdestValue := dest[keys[i]]\n\t\t\tdataInfo = append(dataInfo, fmt.Sprintf(\"%v: src(%T): %v, dest(%T):%v\", keys[i], sourceValue, sourceValue, destValue, destValue))\n\t\t}\n\t\treturn fmt.Errorf(\"inconsistent partition value: %v, src: %v, dest:%v, %v\", keys, source.Index(keys), dest.Index(keys), strings.Join(dataInfo, \",\"))\n\t}\n\treturn nil\n}", "func testFailingWrite(c *testContext, flow testFlow, wantErr *tcpip.Error) {\n\tc.t.Helper()\n\n\th := flow.header4Tuple(outgoing)\n\twriteDstAddr := flow.mapAddrIfApplicable(h.dstAddr.Addr)\n\n\tpayload := buffer.View(newPayload())\n\t_, _, gotErr := c.ep.Write(tcpip.SlicePayload(payload), tcpip.WriteOptions{\n\t\tTo: &tcpip.FullAddress{Addr: writeDstAddr, Port: h.dstAddr.Port},\n\t})\n\tif gotErr != wantErr {\n\t\tc.t.Fatalf(\"Write returned unexpected error: got %v, want %v\", gotErr, wantErr)\n\t}\n}", "func (t Transfer) Validate(vs ValidationStrategy) error {\n\treturn vs.Validate(t)\n}", "func (m Mux) CanTransfer(ctx context.Context, dsturl, srcurl string) (bool, error) {\n\tsrcB, _, err := m.Bucket(ctx, srcurl)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdstB, _, err := m.Bucket(ctx, dsturl)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tvar srcScheme, dstScheme string\n\tif u, err := url.Parse(srcurl); err == nil {\n\t\tsrcScheme = u.Scheme\n\t}\n\tif u, err := url.Parse(dsturl); err == nil {\n\t\tdstScheme = u.Scheme\n\t}\n\tswitch {\n\tcase srcScheme != \"\" && dstScheme != \"\" && srcScheme != dstScheme:\n\t\treturn false, errors.E(errors.NotSupported, errors.Errorf(\"mux.Transfer %s -> %s\", srcScheme, dstScheme))\n\tcase reflect.TypeOf(srcB) != reflect.TypeOf(dstB):\n\t\treturn false, errors.E(errors.NotSupported, errors.Errorf(\"mux.Transfer %T -> %T)\", srcB, dstB))\n\t}\n\treturn true, nil\n}", "func validateTemplate(t *testing.T, tplI config.Template, dest bot.Destination) {\n\tt.Helper()\n\n\t// First, make sure all advertised files exist.\n\tfor _, file := range tplI.Describe(dest) {\n\t\t// Don't bother checking directories, they're meant to be black\n\t\t// boxes. We could implement type-specific checks if we really\n\t\t// wanted.\n\t\tif file.IsDir {\n\t\t\tcontinue\n\t\t}\n\n\t\tbytes, err := dest.Read(file.Name)\n\t\trequire.NoError(t, err)\n\n\t\t// Should at least be non-empty.\n\t\tt.Logf(\"Expected file %q for template %q has length: %d\", file.Name, tplI.Name(), len(bytes))\n\t\trequire.Truef(t, len(bytes) > 0, \"file %q in template %q must be non-empty\", file.Name, tplI.Name())\n\t}\n\n\t// Next, for supported template types, make sure they're valid.\n\t// TODO: consider adding further type-specific tests.\n\tswitch tpl := tplI.(type) {\n\tcase *config.TemplateIdentity:\n\t\t// Make sure the identityfile package can read this identity file.\n\t\tb, err := dest.Read(tpl.FileName)\n\t\trequire.NoError(t, err)\n\n\t\tbuf := bytes.NewBuffer(b)\n\t\t_, err = identityfile.Read(buf)\n\t\trequire.NoError(t, err)\n\tcase *config.TemplateTLSCAs:\n\t\tb, err := dest.Read(tpl.HostCAPath)\n\t\trequire.NoError(t, err)\n\t\t_, err = tlsca.ParseCertificatePEM(b)\n\t\trequire.NoError(t, err)\n\n\t\tb, err = dest.Read(tpl.UserCAPath)\n\t\trequire.NoError(t, err)\n\t\t_, err = tlsca.ParseCertificatePEM(b)\n\t\trequire.NoError(t, err)\n\t}\n}", "func MustCopyTo(bc *braille.Canvas, dst *canvas.Canvas) {\n\tif err := bc.CopyTo(dst); err != nil {\n\t\tpanic(fmt.Sprintf(\"bc.CopyTo => unexpected error: %v\", err))\n\t}\n}", "func (c *Cloud) configureInstanceSourceDestCheck(instanceID string, sourceDestCheck bool) error {\n\trequest := &ec2.ModifyInstanceAttributeInput{}\n\trequest.InstanceId = aws.String(instanceID)\n\trequest.SourceDestCheck = &ec2.AttributeBooleanValue{Value: aws.Bool(sourceDestCheck)}\n\n\t_, err := c.ec2.ModifyInstanceAttribute(request)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error configuring source-dest-check on instance %s: %q\", instanceID, err)\n\t}\n\treturn nil\n}", "func MustCopy(dst io.Writer, src io.Reader) {\n\tif _, err := io.Copy(dst, src); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (account *DatabaseAccount) validateSecretDestinations() (admission.Warnings, error) {\n\tif account.Spec.OperatorSpec == nil {\n\t\treturn nil, nil\n\t}\n\tif account.Spec.OperatorSpec.Secrets == nil {\n\t\treturn nil, nil\n\t}\n\ttoValidate := []*genruntime.SecretDestination{\n\t\taccount.Spec.OperatorSpec.Secrets.DocumentEndpoint,\n\t\taccount.Spec.OperatorSpec.Secrets.PrimaryMasterKey,\n\t\taccount.Spec.OperatorSpec.Secrets.PrimaryReadonlyMasterKey,\n\t\taccount.Spec.OperatorSpec.Secrets.SecondaryMasterKey,\n\t\taccount.Spec.OperatorSpec.Secrets.SecondaryReadonlyMasterKey,\n\t}\n\treturn genruntime.ValidateSecretDestinations(toValidate)\n}", "func (v CreateValidator) Copy() StakeMsg {\n\tv1 := v\n\tdesc := *v.Description\n\tv1.Description = &desc\n\treturn v1\n}", "func checkIdenticalDownload(ctx context.Context, dst, src fs.Object) (differ bool, err error) {\n\tin1, err := dst.Open(ctx)\n\tif err != nil {\n\t\treturn true, errors.Wrapf(err, \"failed to open %q\", dst)\n\t}\n\ttr1 := accounting.Stats(ctx).NewTransfer(dst)\n\tdefer func() {\n\t\ttr1.Done(nil) // error handling is done by the caller\n\t}()\n\tin1 = tr1.Account(ctx, in1).WithBuffer() // account and buffer the transfer\n\n\tin2, err := src.Open(ctx)\n\tif err != nil {\n\t\treturn true, errors.Wrapf(err, \"failed to open %q\", src)\n\t}\n\ttr2 := accounting.Stats(ctx).NewTransfer(dst)\n\tdefer func() {\n\t\ttr2.Done(nil) // error handling is done by the caller\n\t}()\n\tin2 = tr2.Account(ctx, in2).WithBuffer() // account and buffer the transfer\n\n\t// To assign err variable before defer.\n\tdiffer, err = CheckEqualReaders(in1, in2)\n\treturn\n}", "func (uds *unfinishedDownloadSegment) fail(err error) {\n\tuds.failed = true\n\tuds.recoveryComplete = true\n\tfor i := range uds.physicalSegmentData {\n\t\tuds.physicalSegmentData[i] = nil\n\t}\n\tuds.download.fail(fmt.Errorf(\"segment %v failed: %v\", uds.segmentIndex, err))\n\tuds.destination = nil\n}", "func copyOwnership(source, destination string) error {\n\treturn nil\n}", "func (pf *PetsFile) NeedsLink() PetsCause {\n\tif !pf.Link || pf.Source == \"\" || pf.Dest == \"\" {\n\t\treturn NONE\n\t}\n\n\tfi, err := os.Lstat(pf.Dest)\n\n\tif os.IsNotExist(err) {\n\t\t// Dest does not exist yet. Happy path, we are gonna create it!\n\t\treturn LINK\n\t}\n\n\tif err != nil {\n\t\t// There was an error calling lstat, putting all my money on\n\t\t// permission denied.\n\t\tlog.Printf(\"[ERROR] cannot lstat Dest file %s: %v\\n\", pf.Dest, err)\n\t\treturn NONE\n\t}\n\n\t// We are here because Dest already exists and lstat succeeded. At this\n\t// point there are two options:\n\t// (1) Dest is already a link to Source \\o/\n\t// (2) Dest is a file, or a directory, or a link to something else /o\\\n\t//\n\t// In any case there is no action to take, but let's come up with a valid\n\t// excuse for not doing anything.\n\n\t// Easy case first: Dest exists and it is not a symlink\n\tif fi.Mode()&os.ModeSymlink == 0 {\n\t\tlog.Printf(\"[ERROR] %s already exists\\n\", pf.Dest)\n\t\treturn NONE\n\t}\n\n\t// Dest is a symlink\n\tpath, err := filepath.EvalSymlinks(pf.Dest)\n\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] cannot EvalSymlinks() Dest file %s: %v\\n\", pf.Dest, err)\n\t} else if pf.Source == path {\n\t\t// Happy path\n\t\tlog.Printf(\"[DEBUG] %s is a symlink to %s already\\n\", pf.Dest, pf.Source)\n\t} else {\n\t\tlog.Printf(\"[ERROR] %s is a symlink to %s instead of %s\\n\", pf.Dest, path, pf.Source)\n\t}\n\treturn NONE\n}", "func (dest Destination) Equal(other Destination) bool {\n\treturn dest.Address.Equal(other.Address) &&\n\t\tdest.Port == other.Port &&\n\t\tdest.Weight == other.Weight &&\n\t\tdest.Flags == other.Flags &&\n\t\tdest.LowerThreshold == other.LowerThreshold &&\n\t\tdest.UpperThreshold == other.UpperThreshold\n}", "func (b *Binary) CopyAndValidateChecksum(dst io.Writer, src io.Reader) (int64, error) {\n\th := sha256.New()\n\tw := io.MultiWriter(h, dst)\n\n\twritten, err := io.Copy(w, src)\n\tif err != nil {\n\t\treturn written, err\n\t}\n\tsum := fmt.Sprintf(\"%x\", h.Sum(nil))\n\tif b.Checksum != sum {\n\t\treturn written, errors.WithStack(&InvalidChecksumError{got: sum, want: b.Checksum})\n\t}\n\n\treturn written, nil\n}", "func (dd *dictDecoder) tryWriteCopy(dist, length int) int {\n\tdstPos := dd.wrPos\n\tendPos := dstPos + length\n\tif dstPos < dist || endPos > len(dd.hist) {\n\t\treturn 0\n\t}\n\tdstBase := dstPos\n\tsrcPos := dstPos - dist\n\n\t// Copy possibly overlapping section before destination position.\nloop:\n\tdstPos += copy(dd.hist[dstPos:endPos], dd.hist[srcPos:dstPos])\n\tif dstPos < endPos {\n\t\tgoto loop // Avoid for-loop so that this function can be inlined\n\t}\n\n\tdd.wrPos = dstPos\n\treturn dstPos - dstBase\n}", "func (raw *rawSyncCmdArgs) cook() (cookedSyncCmdArgs, error) {\n\tcooked := cookedSyncCmdArgs{}\n\n\t// set up the front end scanning logger\n\tazcopyScanningLogger = common.NewJobLogger(azcopyCurrentJobID, azcopyLogVerbosity, azcopyLogPathFolder, \"-scanning\")\n\tazcopyScanningLogger.OpenLog()\n\tglcm.RegisterCloseFunc(func() {\n\t\tazcopyScanningLogger.CloseLog()\n\t})\n\n\t// this if statement ladder remains instead of being separated to help determine valid combinations for sync\n\t// consider making a map of valid source/dest combos and consolidating this to generic source/dest setups, akin to the lower if statement\n\t// TODO: if expand the set of source/dest combos supported by sync, update this method the declarative test framework:\n\n\tvar err error\n\terr = cooked.trailingDot.Parse(raw.trailingDot)\n\tif err != nil {\n\t\treturn cooked, err\n\t}\n\n\tcooked.fromTo, err = ValidateFromTo(raw.src, raw.dst, raw.fromTo)\n\tif err != nil {\n\t\treturn cooked, err\n\t}\n\n\tswitch cooked.fromTo {\n\tcase common.EFromTo.Unknown():\n\t\treturn cooked, fmt.Errorf(\"Unable to infer the source '%s' / destination '%s'. \", raw.src, raw.dst)\n\tcase common.EFromTo.LocalBlob(), common.EFromTo.LocalFile():\n\t\tcooked.destination, err = SplitResourceString(raw.dst, cooked.fromTo.To())\n\t\tcommon.PanicIfErr(err)\n\tcase common.EFromTo.BlobLocal(), common.EFromTo.FileLocal():\n\t\tcooked.source, err = SplitResourceString(raw.src, cooked.fromTo.From())\n\t\tcommon.PanicIfErr(err)\n\tcase common.EFromTo.BlobBlob(), common.EFromTo.FileFile(), common.EFromTo.BlobFile(), common.EFromTo.FileBlob(), common.EFromTo.BlobFSBlobFS(), common.EFromTo.BlobFSBlob(), common.EFromTo.BlobFSFile(), common.EFromTo.BlobBlobFS(), common.EFromTo.FileBlobFS():\n\t\tcooked.destination, err = SplitResourceString(raw.dst, cooked.fromTo.To())\n\t\tcommon.PanicIfErr(err)\n\t\tcooked.source, err = SplitResourceString(raw.src, cooked.fromTo.From())\n\t\tcommon.PanicIfErr(err)\n\tdefault:\n\t\treturn cooked, fmt.Errorf(\"source '%s' / destination '%s' combination '%s' not supported for sync command \", raw.src, raw.dst, cooked.fromTo)\n\t}\n\n\t// Do this check separately so we don't end up with a bunch of code duplication when new src/dstn are added\n\tif cooked.fromTo.From() == common.ELocation.Local() {\n\t\tcooked.source = common.ResourceString{Value: common.ToExtendedPath(cleanLocalPath(raw.src))}\n\t} else if cooked.fromTo.To() == common.ELocation.Local() {\n\t\tcooked.destination = common.ResourceString{Value: common.ToExtendedPath(cleanLocalPath(raw.dst))}\n\t}\n\n\t// we do not support service level sync yet\n\tif cooked.fromTo.From().IsRemote() {\n\t\terr = raw.validateURLIsNotServiceLevel(cooked.source.Value, cooked.fromTo.From())\n\t\tif err != nil {\n\t\t\treturn cooked, err\n\t\t}\n\t}\n\n\t// we do not support service level sync yet\n\tif cooked.fromTo.To().IsRemote() {\n\t\terr = raw.validateURLIsNotServiceLevel(cooked.destination.Value, cooked.fromTo.To())\n\t\tif err != nil {\n\t\t\treturn cooked, err\n\t\t}\n\t}\n\n\t// use the globally generated JobID\n\tcooked.jobID = azcopyCurrentJobID\n\n\tcooked.blockSize, err = blockSizeInBytes(raw.blockSizeMB)\n\tif err != nil {\n\t\treturn cooked, err\n\t}\n\n\tif err = cooked.symlinkHandling.Determine(raw.followSymlinks, raw.preserveSymlinks); err != nil {\n\t\treturn cooked, err\n\t}\n\tcooked.recursive = raw.recursive\n\tcooked.forceIfReadOnly = raw.forceIfReadOnly\n\tif err = validateForceIfReadOnly(cooked.forceIfReadOnly, cooked.fromTo); err != nil {\n\t\treturn cooked, err\n\t}\n\n\tcooked.backupMode = raw.backupMode\n\tif err = validateBackupMode(cooked.backupMode, cooked.fromTo); err != nil {\n\t\treturn cooked, err\n\t}\n\n\t// determine whether we should prompt the user to delete extra files\n\terr = cooked.deleteDestination.Parse(raw.deleteDestination)\n\tif err != nil {\n\t\treturn cooked, err\n\t}\n\n\t// warn on legacy filters\n\tif raw.legacyInclude != \"\" || raw.legacyExclude != \"\" {\n\t\treturn cooked, fmt.Errorf(\"the include and exclude parameters have been replaced by include-pattern and exclude-pattern. They work on filenames only (not paths)\")\n\t}\n\n\t// parse the filter patterns\n\tcooked.includePatterns = raw.parsePatterns(raw.include)\n\tcooked.excludePatterns = raw.parsePatterns(raw.exclude)\n\tcooked.excludePaths = raw.parsePatterns(raw.excludePath)\n\n\t// parse the attribute filter patterns\n\tcooked.includeFileAttributes = raw.parsePatterns(raw.includeFileAttributes)\n\tcooked.excludeFileAttributes = raw.parsePatterns(raw.excludeFileAttributes)\n\n\tcooked.preserveSMBInfo = raw.preserveSMBInfo && areBothLocationsSMBAware(cooked.fromTo)\n\n\tif err = validatePreserveSMBPropertyOption(cooked.preserveSMBInfo, cooked.fromTo, nil, \"preserve-smb-info\"); err != nil {\n\t\treturn cooked, err\n\t}\n\n\tisUserPersistingPermissions := raw.preserveSMBPermissions || raw.preservePermissions\n\tif cooked.preserveSMBInfo && !isUserPersistingPermissions {\n\t\tglcm.Info(\"Please note: the preserve-permissions flag is set to false, thus AzCopy will not copy SMB ACLs between the source and destination. To learn more: https://aka.ms/AzCopyandAzureFiles.\")\n\t}\n\n\tif err = validatePreserveSMBPropertyOption(isUserPersistingPermissions, cooked.fromTo, nil, PreservePermissionsFlag); err != nil {\n\t\treturn cooked, err\n\t}\n\t// TODO: the check on raw.preservePermissions on the next line can be removed once we have full support for these properties in sync\n\t// if err = validatePreserveOwner(raw.preserveOwner, cooked.fromTo); raw.preservePermissions && err != nil {\n\t//\treturn cooked, err\n\t// }\n\tcooked.preservePermissions = common.NewPreservePermissionsOption(isUserPersistingPermissions, raw.preserveOwner, cooked.fromTo)\n\tif cooked.fromTo == common.EFromTo.BlobBlob() && cooked.preservePermissions.IsTruthy() {\n\t\tcooked.isHNSToHNS = true // override HNS settings, since if a user is tx'ing blob->blob and copying permissions, it's DEFINITELY going to be HNS (since perms don't exist w/o HNS).\n\t}\n\n\tcooked.preservePOSIXProperties = raw.preservePOSIXProperties\n\tif cooked.preservePOSIXProperties && !areBothLocationsPOSIXAware(cooked.fromTo) {\n\t\treturn cooked, fmt.Errorf(\"in order to use --preserve-posix-properties, both the source and destination must be POSIX-aware (valid pairings are Linux->Blob, Blob->Linux, Blob->Blob)\")\n\t}\n\n\tif err = cooked.compareHash.Parse(raw.compareHash); err != nil {\n\t\treturn cooked, err\n\t} else {\n\t\tswitch cooked.compareHash {\n\t\tcase common.ESyncHashType.MD5():\n\t\t\t// Save any new MD5s on files we download.\n\t\t\traw.putMd5 = true\n\t\tdefault: // no need to put a hash of any kind.\n\t\t}\n\t}\n\n\tif err = common.LocalHashStorageMode.Parse(raw.localHashStorageMode); err != nil {\n\t\treturn cooked, err\n\t}\n\n\tcooked.putMd5 = raw.putMd5\n\tif err = validatePutMd5(cooked.putMd5, cooked.fromTo); err != nil {\n\t\treturn cooked, err\n\t}\n\n\terr = cooked.md5ValidationOption.Parse(raw.md5ValidationOption)\n\tif err != nil {\n\t\treturn cooked, err\n\t}\n\tif err = validateMd5Option(cooked.md5ValidationOption, cooked.fromTo); err != nil {\n\t\treturn cooked, err\n\t}\n\n\tif cooked.fromTo.IsS2S() {\n\t\tcooked.preserveAccessTier = raw.s2sPreserveAccessTier\n\t}\n\n\t// Check if user has provided `s2s-preserve-blob-tags` flag.\n\t// If yes, we have to ensure that both source and destination must be blob storages.\n\tif raw.s2sPreserveBlobTags {\n\t\tif cooked.fromTo.From() != common.ELocation.Blob() || cooked.fromTo.To() != common.ELocation.Blob() {\n\t\t\treturn cooked, fmt.Errorf(\"either source or destination is not a blob storage. \" +\n\t\t\t\t\"blob index tags is a property of blobs only therefore both source and destination must be blob storage\")\n\t\t} else {\n\t\t\tcooked.s2sPreserveBlobTags = raw.s2sPreserveBlobTags\n\t\t}\n\t}\n\n\t// Setting CPK-N\n\tcpkOptions := common.CpkOptions{}\n\t// Setting CPK-N\n\tif raw.cpkScopeInfo != \"\" {\n\t\tif raw.cpkInfo {\n\t\t\treturn cooked, fmt.Errorf(\"cannot use both cpk-by-name and cpk-by-value at the same time\")\n\t\t}\n\t\tcpkOptions.CpkScopeInfo = raw.cpkScopeInfo\n\t}\n\n\t// Setting CPK-V\n\t// Get the key (EncryptionKey and EncryptionKeySHA256) value from environment variables when required.\n\tcpkOptions.CpkInfo = raw.cpkInfo\n\n\t// We only support transfer from source encrypted by user key when user wishes to download.\n\t// Due to service limitation, S2S transfer is not supported for source encrypted by user key.\n\tif cooked.fromTo.IsDownload() && (cpkOptions.CpkScopeInfo != \"\" || cpkOptions.CpkInfo) {\n\t\tglcm.Info(\"Client Provided Key for encryption/decryption is provided for download scenario. \" +\n\t\t\t\"Assuming source is encrypted.\")\n\t\tcpkOptions.IsSourceEncrypted = true\n\t}\n\n\tcooked.cpkOptions = cpkOptions\n\n\tcooked.mirrorMode = raw.mirrorMode\n\n\tcooked.includeRegex = raw.parsePatterns(raw.includeRegex)\n\tcooked.excludeRegex = raw.parsePatterns(raw.excludeRegex)\n\n\tcooked.dryrunMode = raw.dryrun\n\n\tif azcopyOutputVerbosity == common.EOutputVerbosity.Quiet() || azcopyOutputVerbosity == common.EOutputVerbosity.Essential() {\n\t\tif cooked.deleteDestination == common.EDeleteDestination.Prompt() {\n\t\t\terr = fmt.Errorf(\"cannot set output level '%s' with delete-destination option '%s'\", azcopyOutputVerbosity.String(), cooked.deleteDestination.String())\n\t\t} else if cooked.dryrunMode {\n\t\t\terr = fmt.Errorf(\"cannot set output level '%s' with dry-run mode\", azcopyOutputVerbosity.String())\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn cooked, err\n\t}\n\n\treturn cooked, nil\n}", "func (sp *SkynetPortals) validatePortalChanges(additions []modules.SkynetPortal, removals []modules.NetAddress) error {\n\t// Check for nil input\n\tif len(additions)+len(removals) == 0 {\n\t\treturn errors.New(\"no portals being added or removed\")\n\t}\n\n\tadditionsMap := make(map[modules.NetAddress]struct{})\n\tfor _, addition := range additions {\n\t\taddress := addition.Address\n\t\tif err := address.IsStdValid(); err != nil {\n\t\t\treturn errors.New(\"invalid network address: \" + err.Error())\n\t\t}\n\t\tadditionsMap[address] = struct{}{}\n\t}\n\t// Check that each removal is valid.\n\tfor _, removalAddress := range removals {\n\t\tif err := removalAddress.IsStdValid(); err != nil {\n\t\t\treturn errors.New(\"invalid network address: \" + err.Error())\n\t\t}\n\t\tif _, exists := sp.portals[removalAddress]; !exists {\n\t\t\tif _, added := additionsMap[removalAddress]; !added {\n\t\t\t\treturn errors.New(\"address \" + string(removalAddress) + \" not already present in list of portals or being added\")\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (udc *unfinishedDownloadChunk) fail(err error) {\n\tudc.failed = true\n\tudc.recoveryComplete = true\n\tfor i := range udc.physicalChunkData {\n\t\tudc.physicalChunkData[i] = nil\n\t}\n\tudc.download.managedFail(fmt.Errorf(\"chunk %v failed: %v\", udc.staticChunkIndex, err))\n\tudc.destination = nil\n}", "func (moves *Moves) ValidMovement(move Move) bool {\n\tt := move.LocationStart\n\tvar check Territory\n\n\tswitch move.OrderType {\n\tcase SUPPORT:\n\t\tcheck = move.SecondLocationSubmitted\n\tcase CONVOY:\n\t\tcheck = move.SecondLocationSubmitted\n\tcase MOVE:\n\t\tcheck = move.LocationSubmitted\n\tcase MOVEVIACONVOY:\n\t\tcheck = move.LocationSubmitted\n\tcase RETREAT:\n\t\tcheck = move.LocationSubmitted\n\tdefault:\n\t\tcheck = move.LocationSubmitted\n\t}\n\n\t// attacking yourself is invalid\n\t// TODO return a message\n\t// false, invalid move\n\tif moves.attackingYourSelf(check, move) {\n\t\treturn false\n\t}\n\n\tswitch move.UnitType {\n\tcase ARMY:\n\t\tif move.OrderType == MOVEVIACONVOY {\n\t\t\treturn t.ValidConvoyBeginAndEnd(check) && moves.ConvoyPathDoesExist(move.LocationStart, move.LocationSubmitted)\n\t\t} else if move.OrderType == RETREAT {\n\t\t\treturn t.ValidLandMovement(check, RETREAT) && check != move.DislodgedFrom\n\t\t} else {\n\t\t\treturn t.ValidLandMovement(check, move.OrderType)\n\t\t}\n\tcase NAVY:\n\t\tif move.OrderType == CONVOY {\n\t\t\treturn move.LocationSubmitted.ValidConvoyBeginAndEnd(check)\n\t\t} else {\n\t\t\treturn t.ValidSeaMovement(check)\n\t\t}\n\tdefault:\n\t\treturn false\n\t}\n}", "func (f FileUpload) validateSource() error {\n\tif f.Source == \"\" {\n\t\treturn &errFieldMustBeSpecified{\n\t\t\tmissingField: \"source\",\n\t\t}\n\t}\n\treturn nil\n}", "func (r *PvcCloneReconciler) validateCloneAndSourcePVC(syncState *dvSyncState, log logr.Logger) (bool, error) {\n\tdatavolume := syncState.dvMutated\n\tsourcePvc, err := r.findSourcePvc(datavolume)\n\tif err != nil {\n\t\t// Clone without source\n\t\tif k8serrors.IsNotFound(err) {\n\t\t\tsyncErr := r.syncDataVolumeStatusPhaseWithEvent(syncState, datavolume.Status.Phase, nil,\n\t\t\t\tEvent{\n\t\t\t\t\teventType: corev1.EventTypeWarning,\n\t\t\t\t\treason: CloneWithoutSource,\n\t\t\t\t\tmessage: fmt.Sprintf(MessageCloneWithoutSource, \"pvc\", datavolume.Spec.Source.PVC.Name),\n\t\t\t\t})\n\t\t\tif syncErr != nil {\n\t\t\t\tlog.Error(syncErr, \"failed to sync DataVolume status with event\")\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\n\terr = cc.ValidateClone(sourcePvc, &datavolume.Spec)\n\tif err != nil {\n\t\tr.recorder.Event(datavolume, corev1.EventTypeWarning, CloneValidationFailed, MessageCloneValidationFailed)\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}", "func isRecordFromDst(record entities.Record) bool {\n\tdstIEWithValue, exist := record.GetInfoElementWithValue(\"destinationPodName\")\n\tif !exist || dstIEWithValue.Value == \"\" {\n\t\treturn false\n\t}\n\tsrcIEWithValue, exist := record.GetInfoElementWithValue(\"sourcePodName\")\n\tif exist && srcIEWithValue.Value != \"\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func validate(m migrator.Interface, ch *cliHelper, output string, ignoreV3Data bool) *migrator.MigrationData {\n\t// First check whether we can migrate from the current version.\n\terr := m.CanMigrate()\n\tif err != nil {\n\t\tch.Separator()\n\t\tch.Msg(\"Failed to validate v1 to v3 conversion.\")\n\t\tch.Bullet(err.Error())\n\t\tch.NewLine()\n\t\tos.Exit(1)\n\t\treturn nil\n\t}\n\n\t// Validate the conversion and that the destination is empty.\n\tdata, cerr := m.ValidateConversion()\n\tclean, derr := m.IsDestinationEmpty()\n\n\t// If we didn't hit any conversion errors and the destination is clean (or the --ignore-v3-data\n\t// option is set), then the validation was successful.\n\tif cerr == nil && derr == nil && (clean || ignoreV3Data) {\n\t\tch.Separator()\n\t\tch.Msg(\"Successfully validated v1 to v3 conversion.\")\n\t\treturn data\n\t}\n\n\t// We hit an error in one of the validations. Output final messages to include details of\n\t// both validations.\n\tch.Separator()\n\tch.Msg(\"Failed to validate v1 to v3 conversion.\")\n\tif data != nil && data.HasErrors() {\n\t\tch.Bullet(\"errors converting data, see report(s) below for details\")\n\t} else if cerr != nil {\n\t\tch.Bullet(cerr.Error())\n\t}\n\tif !clean && !ignoreV3Data {\n\t\tch.Bullet(\"The v3 datastore is not clean. We recommend that you remove any calico \" +\n\t\t\t\"data before attempting the upgrade. If you want to keep the existing v3 data, you may use \" +\n\t\t\t\"the '--ignore-v3-data' flag when running the 'start-upgrade' command to force the upgrade, in which \" +\n\t\t\t\"case the v1 data will be converted and will overwrite matching entries in the v3 datastore.\")\n\t} else if derr != nil {\n\t\tch.Bullet(derr.Error())\n\t}\n\t// Include the report for any errors.\n\tif data != nil && data.HasErrors() {\n\t\tprintAndOutputReport(output, data)\n\t}\n\tch.NewLine()\n\tos.Exit(1)\n\treturn nil\n}", "func (m *AssignDestAddressRequest) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for AccessToken\n\n\t// no validation rules for DestAddressId\n\n\treturn nil\n}", "func validateConvertTestCase(testCase *convertTestCase, manifest *dep.Manifest, lock *dep.Lock, convertErr error) error {\n\tif testCase.wantConvertErr {\n\t\tif convertErr == nil {\n\t\t\treturn errors.New(\"Expected the conversion to fail, but it did not return an error\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tif convertErr != nil {\n\t\treturn errors.Wrap(convertErr, \"Expected the conversion to pass, but it returned an error\")\n\t}\n\n\t// Ignored projects checks.\n\tif len(manifest.Ignored) != testCase.wantIgnoreCount {\n\t\treturn errors.Errorf(\"Expected manifest to have %d ignored project(s), got %d\",\n\t\t\ttestCase.wantIgnoreCount,\n\t\t\tlen(manifest.Ignored))\n\t}\n\n\tif !equalSlice(manifest.Ignored, testCase.wantIgnoredPackages) {\n\t\treturn errors.Errorf(\"Expected manifest to have ignore %s, got %s\",\n\t\t\tstrings.Join(testCase.wantIgnoredPackages, \", \"),\n\t\t\tstrings.Join(manifest.Ignored, \", \"))\n\t}\n\n\t// Constraints checks below.\n\tif testCase.wantConstraint != \"\" {\n\t\td, ok := manifest.Constraints[testCase.projectRoot]\n\t\tif !ok {\n\t\t\treturn errors.Errorf(\"Expected the manifest to have a dependency for '%s' but got none\",\n\t\t\t\ttestCase.projectRoot)\n\t\t}\n\n\t\tv := d.Constraint.String()\n\t\tif v != testCase.wantConstraint {\n\t\t\treturn errors.Errorf(\"Expected manifest constraint to be %s, got %s\", testCase.wantConstraint, v)\n\t\t}\n\t}\n\n\t// Lock checks.\n\tif lock != nil {\n\t\tif len(lock.P) != testCase.wantLockCount {\n\t\t\treturn errors.Errorf(\"Expected lock to have %d project(s), got %d\",\n\t\t\t\ttestCase.wantLockCount,\n\t\t\t\tlen(lock.P))\n\t\t}\n\n\t\tp := lock.P[0]\n\n\t\tif p.Ident().ProjectRoot != testCase.projectRoot {\n\t\t\treturn errors.Errorf(\"Expected the lock to have a project for '%s' but got '%s'\",\n\t\t\t\ttestCase.projectRoot,\n\t\t\t\tp.Ident().ProjectRoot)\n\t\t}\n\n\t\tif p.Ident().Source != testCase.wantSourceRepo {\n\t\t\treturn errors.Errorf(\"Expected locked source to be %s, got '%s'\", testCase.wantSourceRepo, p.Ident().Source)\n\t\t}\n\n\t\t// Break down the locked \"version\" into a version (optional) and revision\n\t\tvar gotVersion string\n\t\tvar gotRevision gps.Revision\n\t\tif lpv, ok := p.Version().(gps.PairedVersion); ok {\n\t\t\tgotVersion = lpv.String()\n\t\t\tgotRevision = lpv.Revision()\n\t\t} else if lr, ok := p.Version().(gps.Revision); ok {\n\t\t\tgotRevision = lr\n\t\t} else {\n\t\t\treturn errors.New(\"could not determine the type of the locked version\")\n\t\t}\n\n\t\tif gotRevision != testCase.wantRevision {\n\t\t\treturn errors.Errorf(\"unexpected locked revision : \\n\\t(GOT) %v \\n\\t(WNT) %v\",\n\t\t\t\tgotRevision,\n\t\t\t\ttestCase.wantRevision)\n\t\t}\n\t\tif gotVersion != testCase.wantVersion {\n\t\t\treturn errors.Errorf(\"unexpected locked version: \\n\\t(GOT) %v \\n\\t(WNT) %v\",\n\t\t\t\tgotVersion,\n\t\t\t\ttestCase.wantVersion)\n\t\t}\n\t}\n\treturn nil\n}", "func (a *analysis) onlineCopy(dst, src nodeid) bool {\n\tif dst != src {\n\t\tif nsrc := a.nodes[src]; nsrc.solve.copyTo.add(dst) {\n\t\t\tif a.log != nil {\n\t\t\t\tfmt.Fprintf(a.log, \"\\t\\t\\tdynamic copy n%d <- n%d\\n\", dst, src)\n\t\t\t}\n\t\t\t// TODO(adonovan): most calls to onlineCopy\n\t\t\t// are followed by addWork, possibly batched\n\t\t\t// via a 'changed' flag; see if there's a\n\t\t\t// noticeable penalty to calling addWork here.\n\t\t\treturn a.nodes[dst].solve.pts.addAll(&nsrc.solve.pts)\n\t\t}\n\t}\n\treturn false\n}", "func (o *BaseEdgeLBPoolSpec) ValidateTransition(previous *BaseEdgeLBPoolSpec) error {\n\t// If we're transitioning to a cloud-provider configuration, we don't need to perform any additional validations, as a new EdgeLB pool will always be created.\n\tif *previous.CloudProviderConfiguration == \"\" && *o.CloudProviderConfiguration != \"\" {\n\t\treturn nil\n\t}\n\t// Prevent the cloud-provider configuration from being removed.\n\tif *previous.CloudProviderConfiguration != \"\" && *o.CloudProviderConfiguration == \"\" {\n\t\treturn fmt.Errorf(\"the cloud-provider configuration cannot be removed\")\n\t}\n\t// Prevent the name of the EdgeLB pool from changing.\n\tif *previous.Name != *o.Name {\n\t\treturn errors.New(\"the name of the target edgelb pool cannot be changed\")\n\t}\n\t// Prevent the role of the EdgeLB pool from changing.\n\tif *previous.Role != *o.Role {\n\t\treturn errors.New(\"the role of the target edgelb pool cannot be changed\")\n\t}\n\t// Prevent the virtual network of the target EdgeLB pool from changing.\n\tif *previous.Network != *o.Network {\n\t\treturn errors.New(\"the virtual network of the target edgelb pool cannot be changed\")\n\t}\n\treturn nil\n}", "func (sbr *SnapshotRestoreArgs) Validate() bool {\n\tif sbr.SnapIdentifier == \"\" || sbr.ID == \"\" || sbr.PStore == nil || !sbr.PStore.Validate() || sbr.SourceSnapshot == \"\" || sbr.DestFile == \"\" || sbr.ProtectionDomainID == \"\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func (d *portworx) validateNodeIDMigration(delNode *api.StorageNode, newNode *api.StorageNode,\n\tstoragelessNodes []*api.StorageNode) bool {\n\t// delNode is a deleted node and newNode is a node which picked the NodeId from delNode\n\n\t// Validate that nodeID is picked up by the storage-less node\n\tif len(storagelessNodes) != 0 && !d.Contains(storagelessNodes, newNode) {\n\t\tlog.Errorf(\"Delete NodeId [%s] is not pick up by storageless node\", delNode.Id)\n\t\treturn false\n\t}\n\n\t// Validate that dirves and pool IDs are same after picking up by storage-less node\n\tif !d.comparePoolsAndDisks(delNode, newNode) {\n\t\tlog.Errorf(\"Pools [%v] in deleted node are not macthing with new node pools [%v]\", delNode.Pools, newNode.Pools)\n\t\treturn false\n\t}\n\treturn true\n}", "func IsDestination(v cty.Value) bool {\n\treturn v.Type().Equals(DestinationCty)\n}", "func attemptCopyGroup(fromPath, toPath string) {\n\tinfo, err := os.Stat(fromPath)\n\tif err != nil || info.Sys() == nil {\n\t\treturn\n\t}\n\tif stat, ok := info.Sys().(*syscall.Stat_t); ok {\n\t\tuid := int(stat.Uid)\n\t\t// prefer self over previous owner of file, because it has a higher chance\n\t\t// of success\n\t\tif user, err := user.Current(); err == nil {\n\t\t\tif tmpUID, err := strconv.Atoi(user.Uid); err == nil {\n\t\t\t\tuid = tmpUID\n\t\t\t}\n\t\t}\n\t\tif err = os.Chown(toPath, uid, int(stat.Gid)); err != nil {\n\t\t\tfs.Debugf(nil, \"Failed to keep previous owner of config file: %v\", err)\n\t\t}\n\t}\n}", "func CheckValid(data Dstream) bool {\n\n\tdata.Reset()\n\tnames := data.Names()\n\n\tfor c := 0; data.Next(); c++ {\n\t\tn0 := ilen(data.GetPos(0))\n\t\tfor j := 1; j < len(names); j++ {\n\t\t\tn1 := ilen(data.GetPos(j))\n\t\t\tif n1 != n0 {\n\t\t\t\tmsg := fmt.Sprintf(\"Length mismatch in chunk %d: len(%s) = %d, len(%s) = %d\\n\",\n\t\t\t\t\tc, names[0], n0, names[j], n1)\n\t\t\t\t_, _ = io.WriteString(os.Stderr, msg)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\tdata.Reset()\n\n\treturn true\n}", "func MoveValid(x, y int) bool {\n\treturn (math.Abs(float64(x)) == 2 || math.Abs(float64(y)) == 2) && (math.Abs(float64(x)) == 1 || math.Abs(float64(y)) == 1)\n}", "func (c *Channel) PreCheckRecievedTransfer(tr encoding.EnvelopMessager) (fromState *EndState, toState *EndState, err error) {\n\tevMsg := tr.GetEnvelopMessage()\n\tif !c.isValidEnvelopMessage(evMsg) {\n\t\terr = fmt.Errorf(\"ch address mismatch,expect=%s,got=%s\", c.ChannelIdentifier.String(), evMsg)\n\t\treturn\n\t}\n\tif tr.GetSender() == c.OurState.Address {\n\t\tfromState = c.OurState\n\t\ttoState = c.PartnerState\n\t} else if tr.GetSender() == c.PartnerState.Address {\n\t\tfromState = c.PartnerState\n\t\ttoState = c.OurState\n\t} else {\n\t\terr = fmt.Errorf(\"received transfer from unknown address =%s\", utils.APex(tr.GetSender()))\n\t\treturn\n\t}\n\t/*\n\t\t\t nonce is changed only when a transfer is un/registered, if the test\n\t\t fails either we are out of sync, a message out of order, or it's a\n\t\t forged transfer\n\t\t\tStrictly monotonic value used to order transfers. The nonce starts at 1\n\t*/\n\tisInvalidNonce := evMsg.Nonce < 1 || evMsg.Nonce != fromState.nonce()+1\n\t//If a node data is damaged, then the channel will not work, so the data must not be damaged.\n\tif isInvalidNonce {\n\t\t/*\n\t\t\tmay occur on normal operation\n\t\t\ttodo: give a example\n\t\t*/\n\t\tlog.Info(fmt.Sprintf(\"invalid nonce node=%s,from=%s,to=%s,expected nonce=%d,nonce=%d\",\n\t\t\tutils.Pex(c.OurState.Address[:]), utils.Pex(fromState.Address[:]),\n\t\t\tutils.Pex(toState.Address[:]), fromState.nonce()+1, evMsg.Nonce))\n\t\terr = rerr.InvalidNonce(utils.StringInterface(tr, 3))\n\t\treturn\n\t}\n\t// transfer amount should never decrese.\n\tif evMsg.TransferAmount.Cmp(fromState.TransferAmount()) < 0 {\n\t\tlog.Error(fmt.Sprintf(\"NEGATIVE TRANSFER node=%s,from=%s,to=%s,transfer=%s\",\n\t\t\tutils.Pex(c.OurState.Address[:]), utils.Pex(fromState.Address[:]), utils.Pex(toState.Address[:]),\n\t\t\tutils.StringInterface(tr, 3))) //for nest struct\n\t\terr = fmt.Errorf(\"negative transfer\")\n\t\treturn\n\t}\n\treturn\n}", "func TestDiff(t *testing.T) {\n\tt.Parallel()\n\n\tsrc, err := ioutil.TempFile(\"\", \"unarchive_test.txt\")\n\trequire.NoError(t, err)\n\tdefer os.Remove(src.Name())\n\n\tdestInvalid, err := ioutil.TempFile(\"\", \"unarchive_test.txt\")\n\trequire.NoError(t, err)\n\tdefer os.Remove(destInvalid.Name())\n\n\tt.Run(\"source does not exist\", func(t *testing.T) {\n\t\tu := &Unarchive{\n\t\t\tSource: \"\",\n\t\t\tDestination: \"/tmp\",\n\t\t}\n\t\tstatus := resource.NewStatus()\n\n\t\terr := u.diff(status)\n\n\t\tassert.EqualError(t, err, \"cannot unarchive: stat : no such file or directory\")\n\t\tassert.Equal(t, resource.StatusCantChange, status.StatusCode())\n\t\tassert.True(t, status.HasChanges())\n\t})\n\n\tt.Run(\"destination is not directory\", func(t *testing.T) {\n\t\tu := &Unarchive{\n\t\t\tSource: src.Name(),\n\t\t\tDestination: destInvalid.Name(),\n\t\t}\n\t\tstatus := resource.NewStatus()\n\n\t\terr := u.diff(status)\n\n\t\tassert.EqualError(t, err, fmt.Sprintf(\"invalid destination \\\"%s\\\", must be directory\", u.Destination))\n\t\tassert.Equal(t, resource.StatusCantChange, status.StatusCode())\n\t\tassert.True(t, status.HasChanges())\n\t})\n\n\tt.Run(\"destination does not exist\", func(t *testing.T) {\n\t\tu := &Unarchive{\n\t\t\tSource: src.Name(),\n\t\t\tDestination: \"\",\n\t\t}\n\t\tstatus := resource.NewStatus()\n\n\t\terr := u.diff(status)\n\n\t\tassert.EqualError(t, err, fmt.Sprintf(\"destination \\\"%s\\\" does not exist\", u.Destination))\n\t\tassert.Equal(t, resource.StatusCantChange, status.StatusCode())\n\t\tassert.True(t, status.HasChanges())\n\t})\n\n\tt.Run(\"unarchive\", func(t *testing.T) {\n\t\tu := &Unarchive{\n\t\t\tSource: src.Name(),\n\t\t\tDestination: \"/tmp\",\n\t\t}\n\t\tstatus := resource.NewStatus()\n\n\t\terr := u.diff(status)\n\n\t\tassert.NoError(t, err)\n\t\tassert.Equal(t, u.Source, status.Diffs()[\"unarchive\"].Original())\n\t\tassert.Equal(t, u.Destination, status.Diffs()[\"unarchive\"].Current())\n\t\tassert.Equal(t, resource.StatusWillChange, status.StatusCode())\n\t\tassert.True(t, status.HasChanges())\n\t})\n}", "func (TransferStatus) Failed() TransferStatus { return TransferStatus(-1) }", "func (m MoveResult) IsValid() bool {\n\treturn m.valid\n}", "func (m *Maps) validMove(d types.Direction, c *character.Character) bool {\n\n\t// Make the move and check its validity\n\tnewLoc := types.Move(c.Location(), d)\n\n\tlog.WithField(\"coord\", types.Coordinate{X: newLoc.X, Y: newLoc.Y}).Info(\"valid move\")\n\n\t// Ensure the character isn't going off the grid, tron\n\tinBounds := m.ValidCoordinate(newLoc)\n\n\t// Ensure the character is going onto an empty location\n\tisDisplaceable := false\n\tif inBounds {\n\t\tswitch m.active[newLoc.Y][newLoc.X].(type) {\n\t\tcase Displaceable:\n\t\t\tisDisplaceable = true\n\t\t}\n\t}\n\n\treturn inBounds && isDisplaceable\n}", "func hasReencryptDestinationCACert(cfg *ServiceAliasConfig) bool {\n\tdestCertKey := generateDestCertKey(cfg)\n\tdestCACert, ok := cfg.Certificates[destCertKey]\n\treturn ok && len(destCACert.Contents) > 0\n}", "func prepareCopy(ctx context.Context, dst Target, dstRef string, proxy *cas.Proxy, root ocispec.Descriptor, opts *CopyOptions) error {\n\tif refPusher, ok := dst.(registry.ReferencePusher); ok {\n\t\t// optimize performance for ReferencePusher targets\n\t\tpreCopy := opts.PreCopy\n\t\topts.PreCopy = func(ctx context.Context, desc ocispec.Descriptor) error {\n\t\t\tif preCopy != nil {\n\t\t\t\tif err := preCopy(ctx, desc); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !content.Equal(desc, root) {\n\t\t\t\t// for non-root node, do nothing\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t// for root node, prepare optimized copy\n\t\t\tif err := copyCachedNodeWithReference(ctx, proxy, refPusher, desc, dstRef); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif opts.PostCopy != nil {\n\t\t\t\tif err := opts.PostCopy(ctx, desc); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\t// skip the regular copy workflow\n\t\t\treturn errSkipDesc\n\t\t}\n\t} else {\n\t\tpostCopy := opts.PostCopy\n\t\topts.PostCopy = func(ctx context.Context, desc ocispec.Descriptor) error {\n\t\t\tif content.Equal(desc, root) {\n\t\t\t\t// for root node, tag it after copying it\n\t\t\t\tif err := dst.Tag(ctx, root, dstRef); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif postCopy != nil {\n\t\t\t\treturn postCopy(ctx, desc)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tonCopySkipped := opts.OnCopySkipped\n\topts.OnCopySkipped = func(ctx context.Context, desc ocispec.Descriptor) error {\n\t\tif onCopySkipped != nil {\n\t\t\tif err := onCopySkipped(ctx, desc); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif !content.Equal(desc, root) {\n\t\t\treturn nil\n\t\t}\n\t\t// enforce tagging when root is skipped\n\t\tif refPusher, ok := dst.(registry.ReferencePusher); ok {\n\t\t\treturn copyCachedNodeWithReference(ctx, proxy, refPusher, desc, dstRef)\n\t\t}\n\t\treturn dst.Tag(ctx, root, dstRef)\n\t}\n\n\treturn nil\n}", "func testManifestValidationJobFixesDisturbance(t *testing.T, disturb func(*keppel.DB, []int64, []string)) {\n\tj, s := setup(t)\n\ts.Clock.StepBy(1 * time.Hour)\n\tvalidateManifestJob := j.ManifestValidationJob(s.Registry)\n\n\tvar (\n\t\tallBlobIDs []int64\n\t\tallManifestDigests []string\n\t)\n\n\t//setup two image manifests, both with some layers\n\timages := make([]test.Image, 2)\n\tfor idx := range images {\n\t\timage := test.GenerateImage(\n\t\t\ttest.GenerateExampleLayer(int64(10*idx+1)),\n\t\t\ttest.GenerateExampleLayer(int64(10*idx+2)),\n\t\t)\n\t\tallBlobIDs = append(allBlobIDs,\n\t\t\timage.Layers[0].MustUpload(t, s, fooRepoRef).ID,\n\t\t\timage.Layers[1].MustUpload(t, s, fooRepoRef).ID,\n\t\t\timage.Config.MustUpload(t, s, fooRepoRef).ID,\n\t\t)\n\n\t\timages[idx] = image\n\t\timage.MustUpload(t, s, fooRepoRef, \"\")\n\t\tallManifestDigests = append(allManifestDigests, image.Manifest.Digest.String())\n\t}\n\n\t//also setup an image list manifest containing those images (so that we have\n\t//some manifest-manifest refs to play with)\n\timageList := test.GenerateImageList(images[0], images[1])\n\timageList.MustUpload(t, s, fooRepoRef, \"\")\n\tallManifestDigests = append(allManifestDigests, imageList.Manifest.Digest.String())\n\n\t//since these manifests were just uploaded, validated_at is set to right now,\n\t//so ManifestValidationJob will report that there is nothing to do\n\texpectError(t, sql.ErrNoRows.Error(), validateManifestJob.ProcessOne(s.Ctx))\n\n\t//once they need validating, they validate successfully\n\ts.Clock.StepBy(36 * time.Hour)\n\texpectSuccess(t, validateManifestJob.ProcessOne(s.Ctx))\n\texpectSuccess(t, validateManifestJob.ProcessOne(s.Ctx))\n\texpectSuccess(t, validateManifestJob.ProcessOne(s.Ctx))\n\texpectError(t, sql.ErrNoRows.Error(), validateManifestJob.ProcessOne(s.Ctx))\n\teasypg.AssertDBContent(t, s.DB.DbMap.Db, \"fixtures/manifest-validate-001-before-disturbance.sql\")\n\n\t//disturb the DB state, then rerun ManifestValidationJob to fix it\n\ts.Clock.StepBy(36 * time.Hour)\n\tdisturb(s.DB, allBlobIDs, allManifestDigests)\n\texpectSuccess(t, validateManifestJob.ProcessOne(s.Ctx))\n\texpectSuccess(t, validateManifestJob.ProcessOne(s.Ctx))\n\texpectSuccess(t, validateManifestJob.ProcessOne(s.Ctx))\n\texpectError(t, sql.ErrNoRows.Error(), validateManifestJob.ProcessOne(s.Ctx))\n\teasypg.AssertDBContent(t, s.DB.DbMap.Db, \"fixtures/manifest-validate-002-after-fix.sql\")\n}" ]
[ "0.65766543", "0.6280285", "0.6110826", "0.5810207", "0.57578343", "0.5727806", "0.56967705", "0.55596083", "0.55264664", "0.54655516", "0.5427644", "0.5416648", "0.541464", "0.54048395", "0.5392832", "0.53838646", "0.536724", "0.53310525", "0.5314515", "0.5311886", "0.52938545", "0.5288708", "0.52478546", "0.52467626", "0.5175985", "0.5136203", "0.51170486", "0.5103233", "0.50977147", "0.5079622", "0.50567716", "0.50116223", "0.5008315", "0.4997263", "0.49846193", "0.4984434", "0.49701384", "0.4962897", "0.49589786", "0.49583566", "0.49315065", "0.49185926", "0.4911142", "0.48894855", "0.4870046", "0.48690435", "0.48577443", "0.48565546", "0.48487702", "0.48437124", "0.4835002", "0.48343134", "0.48192266", "0.48192266", "0.4813943", "0.48127028", "0.48114425", "0.4809422", "0.48043755", "0.48034114", "0.47932434", "0.4790932", "0.47819617", "0.47807196", "0.47704545", "0.4770384", "0.47662902", "0.47481373", "0.47446772", "0.47258076", "0.4718881", "0.47056332", "0.4705082", "0.47012743", "0.4691161", "0.46900773", "0.46860573", "0.46824354", "0.46798253", "0.46785158", "0.46768945", "0.46765277", "0.46746823", "0.46638468", "0.46590874", "0.46573162", "0.46475118", "0.46221036", "0.4616319", "0.46074936", "0.4600991", "0.45959133", "0.4590413", "0.45870265", "0.45869026", "0.45847532", "0.45800248", "0.45675305", "0.45631695", "0.45555118", "0.45518923" ]
0.0
-1
use reflect.Value's SetXXX methods instead of pointers and type switch, because we should set by kind, not type.
func scanInt(src int64, dest reflect.Value) error { const ( minInt32 = -1 << 31 maxInt32 = 1<<31 - 1 maxUint32 = 1<<32 - 1 minInt16 = -1 << 15 maxInt16 = 1<<15 - 1 maxUint16 = 1<<16 - 1 minInt8 = -1 << 7 maxInt8 = 1<<7 - 1 maxUint8 = 1<<8 - 1 ) switch dest.Kind() { case reflect.Int64, reflect.Int: // ignore 32 bit machine dest.SetInt(src) case reflect.Uint64, reflect.Uint: dest.SetUint(uint64(src)) case reflect.Int32: if src < minInt32 || src > maxInt32 { return errorValueOutOfRange(src, dest) } dest.SetInt(src) case reflect.Uint32: if src < 0 || src > maxUint32 { return errorValueOutOfRange(src, dest) } dest.SetUint(uint64(src)) case reflect.Int16: if src < minInt16 || src > maxInt16 { return errorValueOutOfRange(src, dest) } dest.SetInt(src) case reflect.Uint16: if src < 0 || src > maxUint16 { return errorValueOutOfRange(src, dest) } dest.SetUint(uint64(src)) case reflect.Int8: if src < minInt8 || src > maxInt8 { return errorValueOutOfRange(src, dest) } dest.SetInt(src) case reflect.Uint8: if src < 0 || src > maxUint8 { return errorValueOutOfRange(src, dest) } dest.SetUint(uint64(src)) case reflect.Interface: if dest.Type() == emptyInterface { dest.Set(reflect.ValueOf(src)) } else { return errorCannotAssign(src, dest) } default: return errorCannotAssign(src, dest) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func setVal(v reflect.Value, pValue interface{}) string {\n\tswitch v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tx, ok := pValue.(int64)\n\t\tif !ok && pValue != nil {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tif v.OverflowInt(x) {\n\t\t\treturn fmt.Sprintf(\"value %v overflows struct field of type %v\", x, v.Type())\n\t\t}\n\t\tv.SetInt(x)\n\tcase reflect.Bool:\n\t\tx, ok := pValue.(bool)\n\t\tif !ok && pValue != nil {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tv.SetBool(x)\n\tcase reflect.String:\n\t\tswitch x := pValue.(type) {\n\t\tcase appengine.BlobKey:\n\t\t\tv.SetString(string(x))\n\t\tcase ByteString:\n\t\t\tv.SetString(string(x))\n\t\tcase string:\n\t\t\tv.SetString(x)\n\t\tdefault:\n\t\t\tif pValue != nil {\n\t\t\t\treturn typeMismatchReason(pValue, v)\n\t\t\t}\n\t\t}\n\tcase reflect.Float32, reflect.Float64:\n\t\tx, ok := pValue.(float64)\n\t\tif !ok && pValue != nil {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tif v.OverflowFloat(x) {\n\t\t\treturn fmt.Sprintf(\"value %v overflows struct field of type %v\", x, v.Type())\n\t\t}\n\t\tv.SetFloat(x)\n\tcase reflect.Ptr:\n\t\tx, ok := pValue.(*Key)\n\t\tif !ok && pValue != nil {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tif _, ok := v.Interface().(*Key); !ok {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tv.Set(reflect.ValueOf(x))\n\tcase reflect.Struct:\n\t\tswitch v.Type() {\n\t\tcase typeOfTime:\n\t\t\tx, ok := pValue.(time.Time)\n\t\t\tif !ok && pValue != nil {\n\t\t\t\treturn typeMismatchReason(pValue, v)\n\t\t\t}\n\t\t\tv.Set(reflect.ValueOf(x))\n\t\tcase typeOfGeoPoint:\n\t\t\tx, ok := pValue.(appengine.GeoPoint)\n\t\t\tif !ok && pValue != nil {\n\t\t\t\treturn typeMismatchReason(pValue, v)\n\t\t\t}\n\t\t\tv.Set(reflect.ValueOf(x))\n\t\tdefault:\n\t\t\tent, ok := pValue.(*Entity)\n\t\t\tif !ok {\n\t\t\t\treturn typeMismatchReason(pValue, v)\n\t\t\t}\n\n\t\t\t// Recursively load nested struct\n\t\t\tpls, err := newStructPLS(v.Addr().Interface())\n\t\t\tif err != nil {\n\t\t\t\treturn err.Error()\n\t\t\t}\n\n\t\t\t// if ent has a Key value and our struct has a Key field,\n\t\t\t// load the Entity's Key value into the Key field on the struct.\n\t\t\tif ent.Key != nil && pls.codec.keyField != -1 {\n\n\t\t\t\tpls.v.Field(pls.codec.keyField).Set(reflect.ValueOf(ent.Key))\n\t\t\t}\n\n\t\t\terr = pls.Load(ent.Properties)\n\t\t\tif err != nil {\n\t\t\t\treturn err.Error()\n\t\t\t}\n\t\t}\n\tcase reflect.Slice:\n\t\tx, ok := pValue.([]byte)\n\t\tif !ok {\n\t\t\tif y, yok := pValue.(ByteString); yok {\n\t\t\t\tx, ok = []byte(y), true\n\t\t\t}\n\t\t}\n\t\tif !ok && pValue != nil {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tif v.Type().Elem().Kind() != reflect.Uint8 {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tv.SetBytes(x)\n\tdefault:\n\t\treturn typeMismatchReason(pValue, v)\n\t}\n\treturn \"\"\n}", "func setVal(v reflect.Value, pValue interface{}) string {\n\tswitch v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tx, ok := pValue.(int64)\n\t\tif !ok && pValue != nil {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tif v.OverflowInt(x) {\n\t\t\treturn fmt.Sprintf(\"value %v overflows struct field of type %v\", x, v.Type())\n\t\t}\n\t\tv.SetInt(x)\n\tcase reflect.Bool:\n\t\tx, ok := pValue.(bool)\n\t\tif !ok && pValue != nil {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tv.SetBool(x)\n\tcase reflect.String:\n\t\tswitch x := pValue.(type) {\n\t\tcase []byte:\n\t\t\tv.SetString(string(x))\n\t\tcase string:\n\t\t\tv.SetString(x)\n\t\tdefault:\n\t\t\tif pValue != nil {\n\t\t\t\treturn typeMismatchReason(pValue, v)\n\t\t\t}\n\t\t}\n\tcase reflect.Float32, reflect.Float64:\n\t\tx, ok := pValue.(float64)\n\t\tif !ok && pValue != nil {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tif v.OverflowFloat(x) {\n\t\t\treturn fmt.Sprintf(\"value %v overflows struct field of type %v\", x, v.Type())\n\t\t}\n\t\tv.SetFloat(x)\n\tcase reflect.Ptr:\n\t\tx, ok := pValue.(*Key)\n\t\tif !ok && pValue != nil {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tif _, ok := v.Interface().(*Key); !ok {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tv.Set(reflect.ValueOf(x))\n\tcase reflect.Struct:\n\t\tswitch v.Type() {\n\t\tcase typeOfTime:\n\t\t\tx, ok := pValue.(time.Time)\n\t\t\tif !ok && pValue != nil {\n\t\t\t\treturn typeMismatchReason(pValue, v)\n\t\t\t}\n\t\t\tv.Set(reflect.ValueOf(x))\n\t\tcase typeOfGeoPoint:\n\t\t\tx, ok := pValue.(appengine.GeoPoint)\n\t\t\tif !ok && pValue != nil {\n\t\t\t\treturn typeMismatchReason(pValue, v)\n\t\t\t}\n\t\t\tv.Set(reflect.ValueOf(x))\n\t\tdefault:\n\t\t\tent, ok := pValue.(*Entity)\n\t\t\tif !ok {\n\t\t\t\treturn typeMismatchReason(pValue, v)\n\t\t\t}\n\n\t\t\t// Recursively load nested struct\n\t\t\tpls, err := newStructPLS(v.Addr().Interface())\n\t\t\tif err != nil {\n\t\t\t\treturn err.Error()\n\t\t\t}\n\n\t\t\t// if ent has a Key value and our struct has a Key field,\n\t\t\t// load the Entity's Key value into the Key field on the struct.\n\t\t\tif ent.Key != nil && pls.codec.keyField != -1 {\n\n\t\t\t\tpls.v.Field(pls.codec.keyField).Set(reflect.ValueOf(ent.Key))\n\t\t\t}\n\n\t\t\terr = pls.Load(ent.Properties)\n\t\t\tif err != nil {\n\t\t\t\treturn err.Error()\n\t\t\t}\n\t\t}\n\tcase reflect.Slice:\n\t\tx, ok := pValue.([]byte)\n\t\tif !ok {\n\t\t\tif y, yok := pValue.(ByteString); yok {\n\t\t\t\tx, ok = []byte(y), true\n\t\t\t}\n\t\t}\n\t\tif !ok && pValue != nil {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tif v.Type().Elem().Kind() != reflect.Uint8 {\n\t\t\treturn typeMismatchReason(pValue, v)\n\t\t}\n\t\tv.SetBytes(x)\n\tdefault:\n\t\treturn typeMismatchReason(pValue, v)\n\t}\n\treturn \"\"\n}", "func SetValue(v reflect.Value, value string) error {\n\tswitch indirectType(v.Type()) {\n\tcase timeType:\n\t\treturn setTime(&v, value)\n\tcase durationType:\n\t\treturn setDuration(&v, value)\n\tcase durationCustomType:\n\t\treturn setDurationCustom(&v, value)\n\t}\n\n\tswitch v.Kind() {\n\tcase reflect.String:\n\t\tv.SetString(value)\n\tcase reflect.Slice:\n\t\tsetSlice(&v, value)\n\tcase reflect.Int, reflect.Int32, reflect.Int64:\n\t\treturn setInt(&v, value)\n\tcase reflect.Uint, reflect.Uint32, reflect.Uint64:\n\t\treturn setUint(&v, value)\n\tcase reflect.Bool:\n\t\tsetBool(&v, value)\n\t}\n\n\treturn nil\n}", "func setValue(fieldType reflect.Type, fieldValue reflect.Value, v string) error {\n\tif len(v) == 0 {\n\t\treturn nil\n\t}\n\tvar err error\n\tswitch k := fieldValue.Kind(); k {\n\tcase reflect.Int,\n\t\treflect.Int8,\n\t\treflect.Int16,\n\t\treflect.Int32,\n\t\treflect.Int64:\n\t\tvar i int64\n\t\ti, err = strconv.ParseInt(v, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfieldValue.SetInt(i)\n\tcase reflect.String:\n\t\tfieldValue.SetString(v)\n\tcase reflect.Bool:\n\t\tvar b bool\n\t\tb, err = strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfieldValue.SetBool(b)\n\tcase reflect.Float32, reflect.Float64:\n\t\tvar f float64\n\t\tf, err = strconv.ParseFloat(v, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfieldValue.SetFloat(f)\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tvar u uint64\n\t\tu, err = strconv.ParseUint(v, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfieldValue.SetUint(u)\n\tcase reflect.Slice:\n\t\terr = setSliceValue(fieldType, fieldValue, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn errors.New(\"turbo: not supported kind[\" + k.String() + \"]\")\n\t}\n\treturn nil\n}", "func setValue(fv *reflect.Value, c *Config, key string) error {\n\t// Update the value with the correct type\n\tswitch fv.Kind() {\n\tcase reflect.Int:\n\t\tval, err := c.GetInt(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfv.SetInt(int64(val))\n\tcase reflect.Float64:\n\t\tval, err := c.GetFloat(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfv.SetFloat(val)\n\tcase reflect.Bool:\n\t\tval, err := c.GetBool(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfv.SetBool(val)\n\tcase reflect.String:\n\t\tval, err := c.GetString(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfv.SetString(val)\n\t}\n\n\treturn nil\n}", "func setValue(val reflect.Value, s string) (err error) {\n\n\t// If the type complies with the TextUnmarshaler interface, use it.\n\tif val.CanInterface() {\n\t\tintf := val.Addr().Interface()\n\t\tif obj, ok := intf.(encoding.TextUnmarshaler); ok {\n\t\t\terr = obj.UnmarshalText([]byte(s))\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Special support for some types\n\tvar newval reflect.Value\n\tdone := true\n\tswitch val.Type().String() {\n\t\tcase \"net.TCPAddr\":\n\t\t\tnewval, err = convTCPAddr(s)\n\t\tcase \"net.IPAddr\":\n\t\t\tnewval, err = convIPAddr(s)\n\t\tcase \"net.IPNet\":\n\t\t\tnewval, err = convIPNet(s)\n\t\tcase \"time.Duration\":\n\t\t\tnewval, err = convDuration(s)\n\t\tdefault:\n\t\t\tdone = false\n\t}\n\tif done {\n\t\tif err == nil {\n\t\t\tval.Set(newval)\n\t\t}\n\t\treturn\n\t}\n\n\t// Perhaps a primitive type\n\terr = setPrimitive(val, s)\n\n\treturn\n}", "func (i *injector) Set(typ reflect.Type, val reflect.Value) TypeMapper {\n\ti.values[typ] = val\n\treturn i\n}", "func (field *Field) Set(value interface{}) (err error) {\n if !field.Field.IsValid() {\n return errors.New(\"field value not valid\")\n }\n\n if !field.Field.CanAddr() {\n return ErrUnaddressable\n }\n\n reflectValue, ok := value.(reflect.Value)\n if !ok {\n reflectValue = reflect.ValueOf(value)\n }\n\n fieldValue := field.Field\n if reflectValue.IsValid() {\n if reflectValue.Type().ConvertibleTo(fieldValue.Type()) {\n fieldValue.Set(reflectValue.Convert(fieldValue.Type()))\n } else {\n if fieldValue.Kind() == reflect.Ptr {\n if fieldValue.IsNil() {\n fieldValue.Set(reflect.New(field.Struct.Type.Elem()))\n }\n fieldValue = fieldValue.Elem()\n }\n\n if reflectValue.Type().ConvertibleTo(fieldValue.Type()) {\n fieldValue.Set(reflectValue.Convert(fieldValue.Type()))\n } else if scanner, ok := fieldValue.Addr().Interface().(sql.Scanner); ok {\n v := reflectValue.Interface()\n if valuer, ok := v.(driver.Valuer); ok {\n if v, err = valuer.Value(); err == nil {\n err = scanner.Scan(v)\n }\n } else {\n err = scanner.Scan(v)\n }\n } else {\n err = fmt.Errorf(\"could not convert argument of field %s from %s to %s\", field.Name, reflectValue.Type(), fieldValue.Type())\n }\n }\n } else {\n field.Field.Set(reflect.Zero(field.Field.Type()))\n }\n\n field.IsBlank = isBlank(field.Field)\n return err\n}", "func (t *Dense) Set(i int, x interface{}) {\n\tswitch t.t.Kind() {\n\tcase reflect.Bool:\n\t\txv := x.(bool)\n\t\tt.setB(i, xv)\n\tcase reflect.Int:\n\t\txv := x.(int)\n\t\tt.setI(i, xv)\n\tcase reflect.Int8:\n\t\txv := x.(int8)\n\t\tt.setI8(i, xv)\n\tcase reflect.Int16:\n\t\txv := x.(int16)\n\t\tt.setI16(i, xv)\n\tcase reflect.Int32:\n\t\txv := x.(int32)\n\t\tt.setI32(i, xv)\n\tcase reflect.Int64:\n\t\txv := x.(int64)\n\t\tt.setI64(i, xv)\n\tcase reflect.Uint:\n\t\txv := x.(uint)\n\t\tt.setU(i, xv)\n\tcase reflect.Uint8:\n\t\txv := x.(uint8)\n\t\tt.setU8(i, xv)\n\tcase reflect.Uint16:\n\t\txv := x.(uint16)\n\t\tt.setU16(i, xv)\n\tcase reflect.Uint32:\n\t\txv := x.(uint32)\n\t\tt.setU32(i, xv)\n\tcase reflect.Uint64:\n\t\txv := x.(uint64)\n\t\tt.setU64(i, xv)\n\tcase reflect.Uintptr:\n\t\txv := x.(uintptr)\n\t\tt.setUintptr(i, xv)\n\tcase reflect.Float32:\n\t\txv := x.(float32)\n\t\tt.setF32(i, xv)\n\tcase reflect.Float64:\n\t\txv := x.(float64)\n\t\tt.setF64(i, xv)\n\tcase reflect.Complex64:\n\t\txv := x.(complex64)\n\t\tt.setC64(i, xv)\n\tcase reflect.Complex128:\n\t\txv := x.(complex128)\n\t\tt.setC128(i, xv)\n\tcase reflect.String:\n\t\txv := x.(string)\n\t\tt.setStr(i, xv)\n\tcase reflect.UnsafePointer:\n\t\txv := x.(unsafe.Pointer)\n\t\tt.setUnsafePointer(i, xv)\n\tdefault:\n\t\txv := reflect.ValueOf(x)\n\t\tptr := uintptr(t.data)\n\t\twant := ptr + uintptr(i)*t.t.Size()\n\t\tval := reflect.NewAt(t.t, unsafe.Pointer(want))\n\t\tval = reflect.Indirect(val)\n\t\tval.Set(xv)\n\t}\n}", "func (t TypeRegister) Set(i interface{}) {\n\tif reflect.ValueOf(i).Kind() != reflect.Ptr {\n\t\tpanic(errors.New(\"gpks.TypeRegister.Set() argument must to be a pointer\"))\n\t}\n\tt[reflect.TypeOf(i).String()] = reflect.TypeOf(i)\n}", "func (t TypeRegister) Set(i interface{}) {\n\tif reflect.ValueOf(i).Kind() != reflect.Ptr {\n\t\tpanic(errors.New(\"TypeRegister.Set() argument must to be a pointer\"))\n\t}\n\tt[reflect.TypeOf(i).String()] = reflect.TypeOf(i)\n}", "func setPrimitive(val reflect.Value, s string) (err error) {\n\n\tswitch val.Type().Kind() {\n\t\tcase reflect.Bool:\n\t\t\tswitch strings.ToLower(s) {\n\t\t\t\tcase \"n\", \"no\", \"f\", \"false\", \"off\":\n\t\t\t\t\tval.SetBool(false)\n\t\t\t\tcase \"y\", \"yes\", \"t\", \"true\", \"on\", \"\":\n\t\t\t\t\tval.SetBool(true)\n\t\t\t\tdefault:\n\t\t\t\t\terr = fmt.Errorf(\"not a boolean value\")\n\t\t\t}\n\t\tcase reflect.Uint64:\n\t\t\tvar i uint64\n\t\t\tif i, err = convUint(s, 64); err == nil {\n\t\t\t\tval.SetUint(i)\n\t\t\t}\n\t\tcase reflect.Int64:\n\t\t\tswitch val.Type().String() {\n\t\t\tdefault:\n\t\t\t\tvar i int64\n\t\t\t\tif i, err = convInt(s, 64); err == nil {\n\t\t\t\t\tval.SetInt(i)\n\t\t\t\t}\n\t\t\t}\n\t\tcase reflect.Uint32:\n\t\t\tvar i uint64\n\t\t\tif i, err = convUint(s, 32); err == nil {\n\t\t\t\tval.SetUint(i)\n\t\t\t}\n\t\tcase reflect.Uint:\n\t\t\tvar i uint64\n\t\t\tif i, err = convUint(s, 0); err == nil {\n\t\t\t\tval.SetUint(i)\n\t\t\t}\n\t\tcase reflect.Int:\n\t\t\tvar i int64\n\t\t\tif i, err = convInt(s, 0); err == nil {\n\t\t\t\tval.SetInt(i)\n\t\t\t}\n\t\tcase reflect.Float64:\n\t\t\tvar fl float64\n\t\t\tif fl, err = convFloat(s); err == nil {\n\t\t\t\tval.SetFloat(fl)\n\t\t\t}\n\t\tcase reflect.String:\n\t\t\tif len(s) > 0 && s[0] == '\"' {\n\t\t\t\ts, err = strconv.Unquote(s)\n\t\t\t\tif err == nil {\n\t\t\t\t\tval.SetString(s)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tval.SetString(s)\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"unsupported type %s\",\n\t\t\t\t\t\tval.Type().String())\n\t}\n\treturn\n}", "func SetValue(r interface{}, val string) error {\n\tiVal, err := ValueFromString(val, reflect.TypeOf(r))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trecv := reflect.ValueOf(r)\n\tif recv.Type().Kind() == reflect.Ptr {\n\t\trecv = recv.Elem()\n\t}\n\n\tv := reflect.ValueOf(iVal)\n\tif v.Type().Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\trecv.Set(v)\n\treturn nil\n}", "func (field *Field) setValue(value reflect.Value, args ...string) (size int, err error) {\n\tlog.Debug(\"try set value %[1]T (%#v)\", value.Interface(), args)\n\n\tswitch value.Interface().(type) {\n\tcase bool:\n\t\t// toggle the boolean\n\t\tvalue.SetBool(!value.Interface().(bool))\n\tcase int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:\n\t\t// override the integer\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass %v\", TYPE_INT)\n\t\t\treturn\n\t\t}\n\n\t\tvar val int\n\t\tif val, err = strconv.Atoi(args[0]); err != nil {\n\t\t\terr = fmt.Errorf(\"should pass %v: %v\", TYPE_INT, args[0])\n\t\t\treturn\n\t\t}\n\n\t\tif len(field.Choices) > 0 {\n\t\t\tidx := sort.SearchStrings(field.Choices, args[0])\n\t\t\tif idx == len(field.Choices) || field.Choices[idx] != args[0] {\n\t\t\t\terr = fmt.Errorf(\"%v should choice from %v\", args[0], field.Choices)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tswitch field.Value.Kind() {\n\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\tvalue.SetInt(int64(val))\n\t\tdefault:\n\t\t\tvalue.SetUint(uint64(val))\n\t\t}\n\n\t\tsize++\n\tcase string:\n\t\t// override the string\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass %v\", TYPE_STRING)\n\t\t\treturn\n\t\t}\n\n\t\tif len(field.Choices) > 0 {\n\t\t\tidx := sort.SearchStrings(field.Choices, args[0])\n\t\t\tif idx == len(field.Choices) || field.Choices[idx] != args[0] {\n\t\t\t\terr = fmt.Errorf(\"%v should choice from %v\", args[0], field.Choices)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tvalue.SetString(args[0])\n\t\tsize++\n\tcase *os.File:\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass filename\")\n\t\t\treturn\n\t\t}\n\n\t\tlog.Info(\"open file %#v\", args[0])\n\n\t\tvar f *os.File\n\t\tif f, err = os.Open(args[0]); err == nil {\n\t\t\tvalue.Set(reflect.ValueOf(f))\n\t\t\tsize++\n\t\t}\n\t\treturn\n\tcase os.FileMode:\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass file perm\")\n\t\t\treturn\n\t\t}\n\n\t\tlog.Info(\"set os.FileMode as %v\", args[0])\n\t\tvar perm int\n\t\tif perm, err = strconv.Atoi(args[0]); err != nil || uint64(perm)&uint64(0xFFFFFFFF00000000) != 0 {\n\t\t\tlog.Info(\"cannot set os.FileMode %#v: %v\", args[0], err)\n\t\t\terr = fmt.Errorf(\"cannot set os.FileMode %#v: %v\", args[0], err)\n\t\t\treturn\n\t\t}\n\n\t\tvalue.Set(reflect.ValueOf(os.FileMode(uint32(perm))))\n\t\tsize++\n\tcase time.Time:\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass TIME: RFC-3339 (2006-01-02T15:04:05+07:00)\")\n\t\t\treturn\n\t\t}\n\n\t\tlog.Info(\"set time.Time as %v\", args[0])\n\t\tvar timestamp time.Time\n\n\t\tif timestamp, err = time.Parse(time.RFC3339, args[0]); err != nil {\n\t\t\tlog.Info(\"should pass RFC-3339 (2006-01-02T15:04:05+07:00): %v: %v\", args[0], err)\n\t\t\terr = fmt.Errorf(\"should pass RFC-3339 (2006-01-02T15:04:05+07:00): %v: %v\", args[0], err)\n\t\t\treturn\n\t\t}\n\t\tvalue.Set(reflect.ValueOf(timestamp))\n\t\tsize++\n\tcase net.Interface:\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass IFACE\")\n\t\t\treturn\n\t\t}\n\n\t\tvar iface *net.Interface\n\n\t\tif iface, err = net.InterfaceByName(args[0]); err != nil {\n\t\t\terr = fmt.Errorf(\"invalid IFACE %#v: %v\", args[0], err)\n\t\t\treturn\n\t\t}\n\n\t\tvalue.Set(reflect.ValueOf(*iface))\n\t\tsize++\n\tcase net.IP:\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass IP\")\n\t\t\treturn\n\t\t}\n\n\t\tip := field.getIP(args[0])\n\t\tif ip == nil {\n\t\t\terr = fmt.Errorf(\"invalid IP: %#v\", args[0])\n\t\t\treturn\n\t\t}\n\n\t\tvalue.Set(reflect.ValueOf(ip))\n\t\tsize++\n\tcase net.IPNet:\n\t\tif len(args) == 0 {\n\t\t\terr = fmt.Errorf(\"should pass CIDR\")\n\t\t\treturn\n\t\t}\n\n\t\tinet := field.getCIRD(args[0])\n\t\tif inet == nil {\n\t\t\terr = fmt.Errorf(\"invalid CIDR: %#v\", args[0])\n\t\t\treturn\n\t\t}\n\n\t\tvalue.Set(reflect.ValueOf(*inet))\n\t\tsize++\n\tdefault:\n\t\tswitch value.Kind() {\n\t\tcase reflect.Struct:\n\t\t\t// execute sub-command\n\t\t\tif err = field.Subcommand.Parse(args...); err != nil {\n\t\t\t\t// only show the help message on the sub-command\n\t\t\t\tfield.Subcommand.HelpMessage(err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\tcase reflect.Ptr:\n\t\t\tlog.Debug(\"set pointer %v: %v\", field.Name, value)\n\n\t\t\tif value.IsNil() {\n\t\t\t\tif field.Subcommand != nil {\n\t\t\t\t\tlog.Info(\"nil pointer, assign as sub-command\")\n\n\t\t\t\t\tvalue.Set(field.Subcommand.Value)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Info(\"nil pointer, new instance: %v\", value.Type())\n\n\t\t\t\t\tobj := reflect.New(value.Type().Elem())\n\t\t\t\t\tvalue.Set(obj)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif size, err = field.setValue(value.Elem(), args...); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase reflect.Slice:\n\t\t\telem := reflect.New(value.Type().Elem()).Elem()\n\t\t\tif size, err = field.setValue(elem, args...); err != nil {\n\t\t\t\terr = fmt.Errorf(\"cannot set %#v: %v\", value.Type(), err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// append to the slice\n\t\t\tvalue.Set(reflect.Append(value, elem))\n\t\tdefault:\n\t\t\tlog.Warn(\"not implemented set value: %[1]v (%[1]T)\", value.Interface())\n\t\t\terr = fmt.Errorf(\"not implemented set value: %[1]v (%[1]T)\", value.Interface())\n\t\t\treturn\n\t\t}\n\t}\n\n\tlog.Debug(\"success set %v (%d)\", value, size)\n\treturn\n}", "func (v *value) set(val interface{}) Value {\n\tswitch val.(type) {\n\tcase int:\n\t\tv.valueType = Real\n\t\tv.real = float64(val.(int))\n\t\tv.imaginary = 0\n\t\tbreak\n\tcase int32:\n\t\tv.valueType = Real\n\t\tv.real = float64(val.(int32))\n\t\tv.imaginary = 0\n\t\tbreak\n\tcase int64:\n\t\tv.valueType = Real\n\t\tv.real = float64(val.(int64))\n\t\tv.imaginary = 0\n\t\tbreak\n\tcase float64:\n\t\tv.valueType = Real\n\t\tfloatVal := val.(float64)\n\t\tv.real = floatVal\n\t\tv.imaginary = 0\n\t\tbreak\n\tcase float32:\n\t\tv.valueType = Real\n\t\tv.real = float64(val.(float32))\n\t\tv.imaginary = 0\n\t\tbreak\n\tcase complex128:\n\t\tv.valueType = Complex\n\t\tcomplexVal := val.(complex128)\n\t\tv.real = real(complexVal)\n\t\timagValue := imag(complexVal)\n\t\tif imagValue == 0 {\n\t\t\tv.valueType = Real\n\t\t}\n\t\tv.imaginary = imagValue\n\t\tbreak\n\tcase complex64:\n\t\tv.valueType = Complex\n\t\tcomplexVal := complex128(val.(complex64))\n\t\tv.real = real(complexVal)\n\t\timagValue := imag(complexVal)\n\t\tif imagValue == 0 {\n\t\t\tv.valueType = Real\n\t\t}\n\t\tv.imaginary = imagValue\n\t\tbreak\n\tdefault:\n\t\treturn Zero()\n\t}\n\tv.precision = 1\n\treturn v\n}", "func (reg *reflectRegistry) set(rt reflect.Type, info *reflectInfo) {\n\treg.Lock()\n\tif exist := reg.infoMap[rt]; exist == nil {\n\t\treg.infoMap[rt] = info\n\t}\n\treg.Unlock()\n}", "func setValueByName(target interface{}, fieldName string, fieldValue interface{}) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = exception.Newf(\"Error setting field: %v\", r)\n\t\t}\n\t}()\n\ttypeCheck := reflect.TypeOf(target)\n\tif typeCheck.Kind() != reflect.Ptr {\n\t\treturn exception.New(\"Cannot modify non-pointer target\")\n\t}\n\n\ttargetValue := reflectValue(target)\n\ttargetType := reflectType(target)\n\trelevantField, hasField := targetType.FieldByName(fieldName)\n\n\tif !hasField {\n\t\treturn exception.Newf(\"Field not found %s.%s\", targetType.Name(), fieldName)\n\t}\n\n\tfield := targetValue.FieldByName(relevantField.Name)\n\tfieldType := field.Type()\n\tif !field.CanSet() {\n\t\treturn exception.Newf(\"Cannot set field %s\", fieldName)\n\t}\n\n\tvalueReflected := reflectValue(fieldValue)\n\tif !valueReflected.IsValid() {\n\t\treturn exception.New(\"Reflected value is invalid, cannot continue.\")\n\t}\n\n\tif valueReflected.Type().AssignableTo(fieldType) {\n\t\tfield.Set(valueReflected)\n\t\treturn nil\n\t}\n\n\tif field.Kind() == reflect.Ptr {\n\t\tif valueReflected.CanAddr() {\n\t\t\tconvertedValue := valueReflected.Convert(fieldType.Elem())\n\t\t\tif convertedValue.CanAddr() {\n\t\t\t\tfield.Set(convertedValue.Addr())\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn exception.New(\"Cannot take address of value for assignment to field pointer\")\n\t}\n\n\tif fieldAsString, isString := valueReflected.Interface().(string); isString {\n\t\tvar parsedValue reflect.Value\n\t\thandledType := true\n\t\tswitch fieldType.Kind() {\n\t\tcase reflect.Int:\n\t\t\tintValue, err := strconv.Atoi(fieldAsString)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(intValue)\n\t\tcase reflect.Int64:\n\t\t\tint64Value, err := strconv.ParseInt(fieldAsString, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(int64Value)\n\t\tcase reflect.Uint16:\n\t\t\tintValue, err := strconv.Atoi(fieldAsString)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(uint16(intValue))\n\t\tcase reflect.Uint: //a.k.a. uint32\n\t\t\tintValue, err := strconv.Atoi(fieldAsString)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(uint(intValue))\n\t\tcase reflect.Uint32:\n\t\t\tintValue, err := strconv.Atoi(fieldAsString)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(uint32(intValue))\n\t\tcase reflect.Uint64:\n\t\t\tintValue, err := strconv.Atoi(fieldAsString)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(uint64(intValue))\n\t\tcase reflect.Float32:\n\t\t\tfloatValue, err := strconv.ParseFloat(fieldAsString, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(floatValue)\n\t\tcase reflect.Float64:\n\t\t\tfloatValue, err := strconv.ParseFloat(fieldAsString, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn exception.Wrap(err)\n\t\t\t}\n\t\t\tparsedValue = reflect.ValueOf(floatValue)\n\t\tdefault:\n\t\t\thandledType = false\n\t\t}\n\t\tif handledType {\n\t\t\tfield.Set(parsedValue)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tconvertedValue := valueReflected.Convert(fieldType)\n\tif convertedValue.IsValid() && convertedValue.Type().AssignableTo(fieldType) {\n\t\tfield.Set(convertedValue)\n\t\treturn nil\n\t}\n\n\treturn exception.New(\"Couldnt set field %s.%s\", targetType.Name(), fieldName)\n}", "func (u *unifier) set(x *TypeParam, t Type) {\n\tassert(t != nil)\n\tif traceInference {\n\t\tu.tracef(\"%s ➞ %s\", x, t)\n\t}\n\t*u.handles[x] = t\n}", "func setFieldValue(field *reflect.Value, value reflect.Value) {\n\tswitch field.Type().Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tfield.SetInt(int64(value.Float()))\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tfield.SetUint(uint64(value.Float()))\n\tdefault:\n\t\tfield.Set(value)\n\t}\n}", "func wrapPtrValue(ptr reflect.Value, target reflect.Type) reflect.Value {\n\tresultPtr := ptr\n\tfor resultPtr.Type() != target {\n\t\tptr := reflect.New(resultPtr.Type())\n\t\tptr.Elem().Set(resultPtr)\n\t\tresultPtr = ptr\n\t}\n\treturn resultPtr\n}", "func wrapPtrValue(ptr reflect.Value, target reflect.Type) reflect.Value {\n\tresultPtr := ptr\n\tfor resultPtr.Type() != target {\n\t\tptr := reflect.New(resultPtr.Type())\n\t\tptr.Elem().Set(resultPtr)\n\t\tresultPtr = ptr\n\t}\n\treturn resultPtr\n}", "func setField(obj interface{}, name string, value interface{}) error {\n\tstructValue := reflect.ValueOf(obj).Elem()\n\tstructFieldValue := structValue.FieldByName(name)\n\n\tif !structFieldValue.IsValid() {\n\t\treturn fmt.Errorf(\"No such field: %s in obj\", name)\n\t}\n\n\tif !structFieldValue.CanSet() {\n\t\treturn fmt.Errorf(\"Cannot set %s field value\", name)\n\t}\n\n\tstructFieldType := structFieldValue.Type()\n\n\tvar val reflect.Value\n\tswitch structFieldType.String() {\n\tcase \"int\":\n\t\ti, _ := strconv.Atoi(value.(js.Value).String())\n\t\tval = reflect.ValueOf(i)\n\t\tbreak\n\tcase \"float64\":\n\t\ti, _ := strconv.ParseFloat(value.(js.Value).String(), 64)\n\t\tval = reflect.ValueOf(i)\n\t\tbreak\n\tcase \"bool\":\n\t\ti, _ := strconv.ParseBool(value.(js.Value).String())\n\t\tval = reflect.ValueOf(i)\n\t\tbreak\n\tcase \"string\":\n\t\tval = reflect.ValueOf(value.(js.Value).String())\n\t\tbreak\n\tdefault:\n\t\tval = reflect.ValueOf(value)\n\t\tbreak\n\t}\n\n\tstructFieldValue.Set(val)\n\treturn nil\n}", "func (vs *eeValues) set(k eeValueKey, v interface{}) {\r\n\tvs.types[k.typeIndex].set(vs, k.valIndex, v)\r\n}", "func recursivelySet(val reflect.Value, prefix string) error {\n\tif val.Kind() != reflect.Ptr {\n\t\treturn errors.New(\"WTF\")\n\t}\n\n\t// dereference\n\tval = reflect.Indirect(val)\n\tif val.Kind() != reflect.Struct {\n\t\treturn errors.New(\"FML\")\n\t}\n\n\t// grab the type for this instance\n\tvType := reflect.TypeOf(val.Interface())\n\n\t// go through child fields\n\tfor i := 0; i < val.NumField(); i++ {\n\t\tthisField := val.Field(i)\n\t\tthisType := vType.Field(i)\n\t\ttags := getTags(thisType)\n\t\t// try to fetch value for each key using multiple tags\n\t\tfor _, tag := range tags {\n\t\t\tkey := prefix + tag\n\t\t\tswitch thisField.Kind() {\n\t\t\tcase reflect.Struct:\n\t\t\t\tif err := recursivelySet(thisField.Addr(), key+\".\"); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase reflect.Int:\n\t\t\t\tfallthrough\n\t\t\tcase reflect.Int32:\n\t\t\t\tfallthrough\n\t\t\tcase reflect.Int64:\n\t\t\t\t// you can only set with an int64 -> int\n\t\t\t\tconfigVal := int64(viper.GetInt(key))\n\t\t\t\t// skip the update if tag is not set in viper\n\t\t\t\tif viper.GetInt(key) == 0 && thisField.Int() != 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tthisField.SetInt(configVal)\n\t\t\tcase reflect.String:\n\t\t\t\t// skip the update if tag is not set in viper\n\t\t\t\tif viper.GetString(key) == \"\" && thisField.String() != \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tthisField.SetString(viper.GetString(key))\n\t\t\tcase reflect.Bool:\n\t\t\t\t// skip the update if tag is not set in viper\n\t\t\t\tif viper.GetBool(key) == false && thisField.Bool() == true {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tthisField.SetBool(viper.GetBool(key))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"unexpected type detected ~ aborting: %s\", thisField.Kind())\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func (field *Field) Set(value interface{}) (err error) {\n\tif !field.Field.IsValid() {\n\t\treturn errors.New(\"field value not valid\")\n\t}\n\n\tif !field.Field.CanAddr() {\n\t\treturn ErrUnaddressable\n\t}\n\n\treflectValue, ok := value.(reflect.Value)\n\tif !ok {\n\t\treflectValue = reflect.ValueOf(value)\n\t}\n\n\tfieldValue := field.Field\n\tif reflectValue.IsValid() {\n\t\tif reflectValue.Type().ConvertibleTo(fieldValue.Type()) {\n\t\t\tfieldValue.Set(reflectValue.Convert(fieldValue.Type()))\n\t\t} else {\n\t\t\tif fieldValue.Kind() == reflect.Ptr {\n\t\t\t\tif fieldValue.IsNil() {\n\t\t\t\t\tfieldValue.Set(reflect.New(field.Struct.Type.Elem()))\n\t\t\t\t}\n\t\t\t\tfieldValue = fieldValue.Elem()\n\t\t\t}\n\n\t\t\tif reflectValue.Type().ConvertibleTo(fieldValue.Type()) {\n\t\t\t\tfieldValue.Set(reflectValue.Convert(fieldValue.Type()))\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"could not convert argument of field %s from %s to %s\", field.Name, reflectValue.Type(), fieldValue.Type())\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfield.Field.Set(reflect.Zero(field.Field.Type()))\n\t}\n\n\treturn err\n}", "func (d *dbBase) setFieldValue(fi *fieldInfo, value interface{}, field reflect.Value) (interface{}, error) {\n\tfieldType := fi.fieldType\n\tisNative := !fi.isFielder\n\nsetValue:\n\tswitch {\n\tcase fieldType == TypeBooleanField:\n\t\tif isNative {\n\t\t\tif nb, ok := field.Interface().(sql.NullBool); ok {\n\t\t\t\tif value == nil {\n\t\t\t\t\tnb.Valid = false\n\t\t\t\t} else {\n\t\t\t\t\tnb.Bool = value.(bool)\n\t\t\t\t\tnb.Valid = true\n\t\t\t\t}\n\t\t\t\tfield.Set(reflect.ValueOf(nb))\n\t\t\t} else if field.Kind() == reflect.Ptr {\n\t\t\t\tif value != nil {\n\t\t\t\t\tv := value.(bool)\n\t\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif value == nil {\n\t\t\t\t\tvalue = false\n\t\t\t\t}\n\t\t\t\tfield.SetBool(value.(bool))\n\t\t\t}\n\t\t}\n\tcase fieldType == TypeVarCharField || fieldType == TypeCharField || fieldType == TypeTextField || fieldType == TypeJSONField || fieldType == TypeJsonbField:\n\t\tif isNative {\n\t\t\tif ns, ok := field.Interface().(sql.NullString); ok {\n\t\t\t\tif value == nil {\n\t\t\t\t\tns.Valid = false\n\t\t\t\t} else {\n\t\t\t\t\tns.String = value.(string)\n\t\t\t\t\tns.Valid = true\n\t\t\t\t}\n\t\t\t\tfield.Set(reflect.ValueOf(ns))\n\t\t\t} else if field.Kind() == reflect.Ptr {\n\t\t\t\tif value != nil {\n\t\t\t\t\tv := value.(string)\n\t\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif value == nil {\n\t\t\t\t\tvalue = \"\"\n\t\t\t\t}\n\t\t\t\tfield.SetString(value.(string))\n\t\t\t}\n\t\t}\n\tcase fieldType == TypeTimeField || fieldType == TypeDateField || fieldType == TypeDateTimeField:\n\t\tif isNative {\n\t\t\tif value == nil {\n\t\t\t\tvalue = time.Time{}\n\t\t\t} else if field.Kind() == reflect.Ptr {\n\t\t\t\tif value != nil {\n\t\t\t\t\tv := value.(time.Time)\n\t\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfield.Set(reflect.ValueOf(value))\n\t\t\t}\n\t\t}\n\tcase fieldType == TypePositiveBitField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tv := uint8(value.(uint64))\n\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t}\n\tcase fieldType == TypePositiveSmallIntegerField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tv := uint16(value.(uint64))\n\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t}\n\tcase fieldType == TypePositiveIntegerField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tif field.Type() == reflect.TypeOf(new(uint)) {\n\t\t\t\tv := uint(value.(uint64))\n\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t} else {\n\t\t\t\tv := uint32(value.(uint64))\n\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t}\n\t\t}\n\tcase fieldType == TypePositiveBigIntegerField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tv := value.(uint64)\n\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t}\n\tcase fieldType == TypeBitField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tv := int8(value.(int64))\n\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t}\n\tcase fieldType == TypeSmallIntegerField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tv := int16(value.(int64))\n\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t}\n\tcase fieldType == TypeIntegerField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tif field.Type() == reflect.TypeOf(new(int)) {\n\t\t\t\tv := int(value.(int64))\n\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t} else {\n\t\t\t\tv := int32(value.(int64))\n\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t}\n\t\t}\n\tcase fieldType == TypeBigIntegerField && field.Kind() == reflect.Ptr:\n\t\tif value != nil {\n\t\t\tv := value.(int64)\n\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t}\n\tcase fieldType&IsIntegerField > 0:\n\t\tif fieldType&IsPositiveIntegerField > 0 {\n\t\t\tif isNative {\n\t\t\t\tif value == nil {\n\t\t\t\t\tvalue = uint64(0)\n\t\t\t\t}\n\t\t\t\tfield.SetUint(value.(uint64))\n\t\t\t}\n\t\t} else {\n\t\t\tif isNative {\n\t\t\t\tif ni, ok := field.Interface().(sql.NullInt64); ok {\n\t\t\t\t\tif value == nil {\n\t\t\t\t\t\tni.Valid = false\n\t\t\t\t\t} else {\n\t\t\t\t\t\tni.Int64 = value.(int64)\n\t\t\t\t\t\tni.Valid = true\n\t\t\t\t\t}\n\t\t\t\t\tfield.Set(reflect.ValueOf(ni))\n\t\t\t\t} else {\n\t\t\t\t\tif value == nil {\n\t\t\t\t\t\tvalue = int64(0)\n\t\t\t\t\t}\n\t\t\t\t\tfield.SetInt(value.(int64))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase fieldType == TypeFloatField || fieldType == TypeDecimalField:\n\t\tif isNative {\n\t\t\tif nf, ok := field.Interface().(sql.NullFloat64); ok {\n\t\t\t\tif value == nil {\n\t\t\t\t\tnf.Valid = false\n\t\t\t\t} else {\n\t\t\t\t\tnf.Float64 = value.(float64)\n\t\t\t\t\tnf.Valid = true\n\t\t\t\t}\n\t\t\t\tfield.Set(reflect.ValueOf(nf))\n\t\t\t} else if field.Kind() == reflect.Ptr {\n\t\t\t\tif value != nil {\n\t\t\t\t\tif field.Type() == reflect.TypeOf(new(float32)) {\n\t\t\t\t\t\tv := float32(value.(float64))\n\t\t\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tv := value.(float64)\n\t\t\t\t\t\tfield.Set(reflect.ValueOf(&v))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\tif value == nil {\n\t\t\t\t\tvalue = float64(0)\n\t\t\t\t}\n\t\t\t\tfield.SetFloat(value.(float64))\n\t\t\t}\n\t\t}\n\tcase fieldType&IsRelField > 0:\n\t\tif value != nil {\n\t\t\tfieldType = fi.relModelInfo.fields.pk.fieldType\n\t\t\tmf := reflect.New(fi.relModelInfo.addrField.Elem().Type())\n\t\t\tfield.Set(mf)\n\t\t\tf := mf.Elem().FieldByIndex(fi.relModelInfo.fields.pk.fieldIndex)\n\t\t\tfield = f\n\t\t\tgoto setValue\n\t\t}\n\t}\n\n\tif !isNative {\n\t\tfd := field.Addr().Interface().(Fielder)\n\t\terr := fd.SetRaw(value)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"converted value `%v` set to Fielder `%s` failed, err: %s\", value, fi.fullName, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn value, nil\n}", "func (v *Object) Set(name string, value interface{}) error {\n\tcstr := C.CString(name)\n\tdefer C.free(unsafe.Pointer(cstr))\n\n\tif _, ok := value.(Object); ok {\n\t\tvalue = value.(Object).ptr\n\t}\n\n\tvar p unsafe.Pointer = nil\n\tswitch value.(type) {\n\tcase bool:\n\t\tc := gbool(value.(bool))\n\t\tp = unsafe.Pointer(&c)\n\tcase int8:\n\t\tc := C.gint8(value.(int8))\n\t\tp = unsafe.Pointer(&c)\n\tcase int16:\n\t\tc := C.gint16(value.(int16))\n\t\tp = unsafe.Pointer(&c)\n\tcase int32:\n\t\tc := C.gint32(value.(int32))\n\t\tp = unsafe.Pointer(&c)\n\tcase int64:\n\t\tc := C.gint64(value.(int64))\n\t\tp = unsafe.Pointer(&c)\n\tcase int:\n\t\tc := C.gint(value.(int))\n\t\tp = unsafe.Pointer(&c)\n\tcase uint8:\n\t\tc := C.guchar(value.(uint8))\n\t\tp = unsafe.Pointer(&c)\n\tcase uint16:\n\t\tc := C.guint16(value.(uint16))\n\t\tp = unsafe.Pointer(&c)\n\tcase uint32:\n\t\tc := C.guint32(value.(uint32))\n\t\tp = unsafe.Pointer(&c)\n\tcase uint64:\n\t\tc := C.guint64(value.(uint64))\n\t\tp = unsafe.Pointer(&c)\n\tcase uint:\n\t\tc := C.guint(value.(uint))\n\t\tp = unsafe.Pointer(&c)\n\tcase uintptr:\n\t\tp = unsafe.Pointer(C.gpointer(value.(uintptr)))\n\tcase float32:\n\t\tc := C.gfloat(value.(float32))\n\t\tp = unsafe.Pointer(&c)\n\tcase float64:\n\t\tc := C.gdouble(value.(float64))\n\t\tp = unsafe.Pointer(&c)\n\tcase string:\n\t\tcstr := C.CString(value.(string))\n\t\tdefer C.free(unsafe.Pointer(cstr))\n\t\tp = unsafe.Pointer(cstr)\n\tdefault:\n\t\tif pv, ok := value.(unsafe.Pointer); ok {\n\t\t\tp = pv\n\t\t} else {\n\t\t\t// Constants with separate types are not type asserted\n\t\t\t// above, so do a runtime check here instead.\n\t\t\tval := reflect.ValueOf(value)\n\t\t\tswitch val.Kind() {\n\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16,\n\t\t\t\treflect.Int32, reflect.Int64:\n\t\t\t\tc := C.int(val.Int())\n\t\t\t\tp = unsafe.Pointer(&c)\n\t\t\tcase reflect.Uintptr:\n\t\t\t\tp = unsafe.Pointer(C.gpointer(val.Pointer()))\n\t\t\t}\n\t\t}\n\t}\n\t// Can't call g_object_set() as it uses a variable arg list, use a\n\t// wrapper instead\n\tif p != nil {\n\t\tC._g_object_set_one(C.gpointer(v.ptr), (*C.gchar)(cstr), p)\n\t\treturn nil\n\t} else {\n\t\treturn errors.New(\"Unable to perform type conversion\")\n\t}\n}", "func SetFieldValue(i interface{}, field string, value interface{}) {\n\tv := reflect.ValueOf(i)\n\n\tif v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {\n\t\tpanic(\"input must be a pointer to a struct\")\n\t}\n\n\tfieldVal := v.Elem().FieldByName(field)\n\n\tswitch fieldVal.Kind() {\n\tcase reflect.Bool:\n\t\tfieldVal.SetBool(value.(bool))\n\tcase reflect.Int:\n\tcase reflect.Int8:\n\tcase reflect.Int16:\n\tcase reflect.Int32:\n\tcase reflect.Int64:\n\t\tfieldVal.SetInt(value.(int64))\n\tcase reflect.Uint:\n\tcase reflect.Uint8:\n\tcase reflect.Uint16:\n\tcase reflect.Uint32:\n\tcase reflect.Uint64:\n\t\tfieldVal.SetUint(value.(uint64))\n\tcase reflect.Float32:\n\tcase reflect.Float64:\n\t\tfieldVal.SetFloat(value.(float64))\n\tcase reflect.Complex64:\n\tcase reflect.Complex128:\n\t\tfieldVal.SetComplex(value.(complex128))\n\tcase reflect.String:\n\t\tfieldVal.SetString(value.(string))\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Unsupported type [%s]\", fieldVal.Kind().String()))\n\t}\n}", "func setField(obj interface{}, name string, value interface{}) error {\n\tstructValue := reflect.ValueOf(obj).Elem()\n\tstructType := reflect.TypeOf(obj).Elem()\n\tstructFieldValue := structValue.FieldByName(name)\n\n\tfor i := 0; i < structType.NumField(); i++ {\n\t\tfield := structType.Field(i)\n\t\ttag := field.Tag.Get(\"query\")\n\n\t\tif tag == name {\n\t\t\tstructFieldValue = structValue.Field(i)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !structFieldValue.IsValid() || !structFieldValue.CanSet() {\n\t\treturn errors.New(fmt.Sprintf(\"%s is not allowed\", name))\n\t}\n\n\tstructFieldType := structFieldValue.Type()\n\tval := reflect.ValueOf(value)\n\n\tif structFieldType.Kind() == reflect.Bool {\n\t\tswitch val.String() {\n\t\tcase \"false\":\n\t\t\tstructFieldValue.SetBool(false)\n\t\t\treturn nil\n\t\tcase \"true\":\n\t\t\tstructFieldValue.SetBool(true)\n\t\t\treturn nil\n\t\tdefault:\n\t\t\treturn errors.New(fmt.Sprintf(\"%s must be a boolean\", name))\n\t\t}\n\t} else {\n\t\tstructFieldValue.Set(val)\n\t\treturn nil\n\t}\n}", "func (s Scalar) apply(v reflect.Value) {\n\tv = indirect(v)\n\tswitch v.Kind() {\n\tcase reflect.String:\n\t\tv.SetString(s.String())\n\tcase reflect.Int64:\n\t\ti, err := strconv.ParseInt(s.String(), 10, 64)\n\t\tif err != nil {\n\t\t\ts.error(InvalidInt64Error{Value: s, Err: err})\n\t\t}\n\t\tv.SetInt(i)\n\tcase reflect.Uint64:\n\t\tu, err := strconv.ParseUint(s.String(), 10, 64)\n\t\tif err != nil {\n\t\t\ts.error(InvalidUint64Error{Value: s, Err: err})\n\t\t}\n\t\tv.SetUint(u)\n\tcase reflect.Bool:\n\t\tswitch s.String() {\n\t\tcase \"true\":\n\t\t\tv.SetBool(true)\n\t\tcase \"false\":\n\t\t\tv.SetBool(false)\n\t\tdefault:\n\t\t\ts.error(InvalidBoolError{Value: s})\n\t\t}\n\tcase reflect.Slice:\n\t\tif v.Type().Elem().Kind() == reflect.Uint8 {\n\t\t\tb, err := base64.StdEncoding.DecodeString(s.String())\n\t\t\tif err != nil {\n\t\t\t\ts.error(InvalidBase64Error{Value: s, Err: err})\n\t\t\t}\n\t\t\tv.Set(reflect.ValueOf(b))\n\t\t\tbreak\n\t\t}\n\t\tfallthrough\n\tdefault:\n\t\tif !reflect.TypeOf(s).AssignableTo(v.Type()) {\n\t\t\ts.error(InvalidScalarError{Type: v.Type()})\n\t\t}\n\t\tv.Set(reflect.ValueOf(s))\n\t}\n}", "func (f *FieldNames) SetValue(val interface{}) {\n\t*f = val.(FieldNames)\n}", "func (p *property) set(v reflect.Value) error {\n\tsetElement := func(element reflect.Value, s string) error {\n\t\tswitch element.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tif v, err := strconv.ParseBool(s); err != nil {\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\telement.Set(reflect.ValueOf(v))\n\t\t\t}\n\t\tcase reflect.Int:\n\t\t\tif v, err := strconv.Atoi(s); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s: not an integer\", s)\n\t\t\t} else {\n\t\t\t\telement.Set(reflect.ValueOf(v))\n\t\t\t}\n\t\tcase reflect.Float64:\n\t\t\ts = strings.Replace(s, \",\", \".\", 1) // allow both , and . as decimal delimiters.\n\t\t\tif v, err := strconv.ParseFloat(s, 64); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s: not a number\", s)\n\t\t\t} else {\n\t\t\t\telement.Set(reflect.ValueOf(v))\n\t\t\t}\n\t\tdefault:\n\t\t\t/* TODO: is this used? */\n\t\t\t// Call FromString method if it exists.\n\t\t\t// FromString must return an error as a string type.\n\t\t\tif _, ok := element.Addr().Type().MethodByName(\"FromString\"); ok {\n\t\t\t\terrStrings := element.Addr().MethodByName(\"FromString\").Call([]reflect.Value{reflect.ValueOf(s)})\n\t\t\t\terrstr := errStrings[0].String()\n\t\t\t\tif errstr != \"\" {\n\t\t\t\t\treturn fmt.Errorf(\"%s\", errstr)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif reflect.TypeOf(s).ConvertibleTo(element.Type()) == false {\n\t\t\t\treturn fmt.Errorf(\"cannot convert string to %v\", element.Type())\n\t\t\t}\n\t\t\tv := reflect.ValueOf(s).Convert(element.Type())\n\t\t\telement.Set(v)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif v.Kind() == reflect.Slice {\n\t\tslice := reflect.MakeSlice(v.Type(), len(p.Values), len(p.Values))\n\t\tfor i, s := range p.Values {\n\t\t\tif err := setElement(slice.Index(i), s); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tv.Set(slice)\n\t} else {\n\t\tif len(p.Values) != 1 {\n\t\t\treturn fmt.Errorf(\"cannot set %d values to a non-slice value\", len(p.Values))\n\t\t}\n\t\treturn setElement(v, p.Values[0])\n\t}\n\treturn nil\n}", "func (p *PCache) Set(kind string, in interface{}, push bool) error {\n\tp.Log.Infof(\"Set called for kind : %v and Object : %v\", kind, in)\n\n\t// Get entries for the kind\n\tkindMap, kindInfo := p.getKind(kind)\n\n\tkindMap.Lock()\n\tdefer kindMap.Unlock()\n\tif push {\n\t\treturn p.validateAndPush(kindMap, in, kindInfo)\n\t}\n\n\tobjMeta, err := runtime.GetObjectMeta(in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to get object meta, %v\", err)\n\t}\n\tkey := objMeta.GetKey()\n\tkindMap.entries[key] = in\n\treturn nil\n}", "func (node selfNode) makeValue(t reflect.Type) (value reflect.Value, err error) {\n\n\tkind := t.Kind()\n\tvalue = reflect.Zero(t)\n\n\tif isScalarKind(kind) {\n\t\terr = node.newPackError(\"expected a string element for scalar field\")\n\n\t} else if kind == reflect.Array {\n\t\tvalue = reflect.MakeSlice(t, t.Len(), t.Len())\n\t\terr = node.packToArray(value)\n\n\t} else if kind == reflect.Slice {\n\t\tvalue = reflect.New(t).Elem()\n\t\terr = node.packToSlice(value)\n\n\t} else if kind == reflect.Struct {\n\t\tvalue = reflect.New(t).Elem()\n\t\terr = node.packToStruct(value)\n\n\t} else if kind == reflect.Map {\n\t\tvalue = reflect.MakeMap(t)\n\t\terr = node.packToMap(value)\n\n\t} else {\n\t\terr = node.newPackError(\"unsupported field kind \" + kind.String())\n\t}\n\n\treturn\n}", "func SetValueFromStr(value reflect.Value, s string) error {\n\tswitch value.Interface().(type) {\n\tcase bool:\n\t\tval, err := strconv.ParseBool(s)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue.SetBool(val)\n\tcase float32:\n\t\tval, err := strconv.ParseFloat(s, 32)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue.SetFloat(val)\n\tcase float64:\n\t\tval, err := strconv.ParseFloat(s, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue.SetFloat(val)\n\tcase int, int32:\n\t\tval, err := strconv.ParseInt(s, 10, 32)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue.SetInt(val)\n\tcase int8:\n\t\tval, err := strconv.ParseInt(s, 10, 8)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue.SetInt(val)\n\tcase int16:\n\t\tval, err := strconv.ParseInt(s, 10, 16)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue.SetInt(val)\n\tcase int64:\n\t\tval, err := strconv.ParseInt(s, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue.SetInt(val)\n\tcase uint, uint32:\n\t\tval, err := strconv.ParseUint(s, 10, 32)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue.SetUint(val)\n\tcase uint8:\n\t\tval, err := strconv.ParseUint(s, 10, 8)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue.SetUint(val)\n\tcase uint16:\n\t\tval, err := strconv.ParseUint(s, 10, 16)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue.SetUint(val)\n\tcase uint64:\n\t\tval, err := strconv.ParseUint(s, 10, 16)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue.SetUint(val)\n\tcase string:\n\t\tvalue.SetString(s)\n\tcase []byte:\n\t\tvalue.SetBytes([]byte(s))\n\tcase []int32:\n\t\tvar val []int32\n\t\tvar err = json.Unmarshal([]byte(s), &val)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue.Set(reflect.ValueOf(val))\n\tdefault:\n\t\treturn fmt.Errorf(\"unkown-type :%v\", reflect.TypeOf(value))\n\t}\n\treturn nil\n}", "func (v Value) Set(p string, x interface{}) {\n\tpanic(message)\n}", "func SetPointer(ptr, val interface{}) {\n\tptrVal := reflect.ValueOf(ptr)\n\tptrType := ptrVal.Type()\n\tif ptrType.Kind() != reflect.Ptr {\n\t\tpanic(\"Pointer expected\")\n\t}\n\n\ttarget := ptrVal.Elem()\n\ttargetType := target.Type()\n\n\tvalue := reflect.ValueOf(val)\n\tvalueType := value.Type()\n\n\tif valueType.Kind() == reflect.Ptr && targetType.Kind() != reflect.Ptr {\n\t\tvalue = value.Elem()\n\t}\n\n\ttarget.Set(value)\n}", "func SetArgValue(name string, fval reflect.Value, value string) error {\n\tnptyp := kit.NonPtrType(fval.Type())\n\tvk := nptyp.Kind()\n\tswitch {\n\tcase vk >= reflect.Int && vk <= reflect.Uint64 && kit.Enums.TypeRegistered(nptyp):\n\t\treturn kit.Enums.SetAnyEnumValueFromString(fval, value)\n\tcase vk == reflect.Map:\n\t\tmval := make(map[string]any)\n\t\terr := toml.ReadBytes(&mval, []byte(\"tmp=\"+value)) // use toml decoder\n\t\tif err != nil {\n\t\t\tmpi.Println(err)\n\t\t\treturn err\n\t\t}\n\t\terr = kit.CopyMapRobust(fval.Interface(), mval[\"tmp\"])\n\t\tif err != nil {\n\t\t\tmpi.Println(err)\n\t\t\terr = fmt.Errorf(\"econfig.ParseArgs: not able to set map field from arg: %s val: %s\", name, value)\n\t\t\tmpi.Println(err)\n\t\t\treturn err\n\t\t}\n\tcase vk == reflect.Slice:\n\t\tmval := make(map[string]any)\n\t\terr := toml.ReadBytes(&mval, []byte(\"tmp=\"+value)) // use toml decoder\n\t\tif err != nil {\n\t\t\tmpi.Println(err)\n\t\t\treturn err\n\t\t}\n\t\terr = kit.CopySliceRobust(fval.Interface(), mval[\"tmp\"])\n\t\tif err != nil {\n\t\t\tmpi.Println(err)\n\t\t\terr = fmt.Errorf(\"econfig.ParseArgs: not able to set slice field from arg: %s val: %s\", name, value)\n\t\t\tmpi.Println(err)\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\tok := kit.SetRobust(fval.Interface(), value) // overkill but whatever\n\t\tif !ok {\n\t\t\terr := fmt.Errorf(\"econfig.ParseArgs: not able to set field from arg: %s val: %s\", name, value)\n\t\t\tmpi.Println(err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (inj *Injector) Set(values ...interface{}) {\n\tfor _, v := range values {\n\t\trv := reflect.ValueOf(v)\n\t\tif rv.Kind() != reflect.Ptr {\n\t\t\tpanic(ErrInjectorSetNeedPointer)\n\t\t}\n\t\tinj.data[rv.Type().String()] = rv\n\t}\n}", "func (m *Setting) SetValueType(value *ManagementParameterValueType)() {\n err := m.GetBackingStore().Set(\"valueType\", value)\n if err != nil {\n panic(err)\n }\n}", "func (u *unifier) setHandle(x *TypeParam, h *Type) {\n\thx := u.handles[x]\n\tassert(hx != nil)\n\tfor y, hy := range u.handles {\n\t\tif hy == hx {\n\t\t\tu.handles[y] = h\n\t\t}\n\t}\n}", "func (m Map) Set(k Name, v interface{}) error {\n\tswitch v.(type) {\n\tcase nil:\n\t\tm[k] = New(k, nil) // use default value\n\tcase uint8:\n\t\tm[k] = New(k, []byte{v.(uint8)})\n\tcase int:\n\t\tm[k] = New(k, []byte{uint8(v.(int))})\n\tcase string:\n\t\tm[k] = New(k, []byte(v.(string)))\n\tcase []byte:\n\t\tm[k] = New(k, []byte(v.([]byte)))\n\tcase DeliverySetting:\n\t\tm[k] = New(k, []byte{uint8(v.(DeliverySetting))})\n\tcase Body:\n\t\tm[k] = v.(Body)\n\tcase pdutext.Codec:\n\t\tc := v.(pdutext.Codec)\n\t\tm[k] = New(k, c.Encode())\n\t\tif k == ShortMessage {\n\t\t\tm[DataCoding] = &Fixed{Data: uint8(c.Type())}\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported field data: %#v\", v)\n\t}\n\tif k == ShortMessage {\n\t\tm[SMLength] = &Fixed{Data: uint8(m[k].Len())}\n\t}\n\treturn nil\n}", "func (c StrConv) SetValue(v reflect.Value, str string) (ok bool) {\n\tif !v.CanSet() {\n\t\treturn\n\t}\n\n\tif conv, ok := c.ByType[v.Type()]; ok {\n\t\treturn conv(str, v)\n\t}\n\n\tconv, ok := c.ByKind[v.Kind()]\n\tif !ok {\n\t\treturn\n\t}\n\n\treturn conv(str, v)\n}", "func putInStruct(structValue reflect.Value, kv []string) error {\n\t// FIXME add more types.\n\tstracer.Traceln(\"storing pair:\", kv)\n\tf := strings.Title(kv[0])\n\tfieldValue := structValue.FieldByName(f)\n\t// Field not found, try to get it by tags.\n\tif !fieldValue.IsValid() {\n\t\tfieldValue = getFieldByTagName(structValue, kv[0])\n\t}\n\terr := assignType(fieldValue, kv[1])\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func convertValueTo(v reflect.Value, typ reflect.Type) (reflect.Value, error) {\n\tif v.Type() == typ {\n\t\treturn v, nil\n\t}\n\ttypBaseType := typ\n\ttypPtrDepth := 0\n\tfor typBaseType.Kind() == reflect.Ptr {\n\t\ttypPtrDepth++\n\t\ttypBaseType = typBaseType.Elem()\n\t}\n\tvBaseType := v.Type()\n\tvPtrDepth := 0\n\tfor vBaseType.Kind() == reflect.Ptr {\n\t\tvPtrDepth++\n\t\tvBaseType = vBaseType.Elem()\n\t}\n\tswitch {\n\tcase vBaseType != typBaseType:\n\t\treturn reflect.Zero(typ), fmt.Errorf(\"cannot convert between %v and %v: differ by more than pointer indirection\", v.Type(), typ)\n\tcase vPtrDepth == typPtrDepth:\n\t\treturn v, nil\n\tcase vPtrDepth < typPtrDepth:\n\t\tfor v.Type() != typ {\n\t\t\tx := reflect.New(v.Type())\n\t\t\tx.Elem().Set(v)\n\t\t\tv = x\n\t\t}\n\t\treturn v, nil\n\tcase vPtrDepth > typPtrDepth:\n\t\tfor v.Type() != typ {\n\t\t\tif v.IsNil() {\n\t\t\t\tv = reflect.Zero(v.Type().Elem())\n\t\t\t} else {\n\t\t\t\tv = v.Elem()\n\t\t\t}\n\t\t}\n\t\treturn v, nil\n\t}\n\treturn reflect.Zero(typ), errors.New(\"unreachable\")\n}", "func (r *DNSResolvers) SetValue(val interface{}) {\n\t*r = val.(DNSResolvers)\n}", "func (d Document) SetValue(field string, value interface{}) bool {\n\tif i, ok := d.data.index[field]; ok {\n\t\tvar (\n\t\t\trv reflect.Value\n\t\t\trt reflect.Type\n\t\t\tfv = d.rv.Field(i)\n\t\t\tft = fv.Type()\n\t\t)\n\n\t\tswitch v := value.(type) {\n\t\tcase nil:\n\t\t\trv = reflect.Zero(ft)\n\t\tcase reflect.Value:\n\t\t\trv = reflect.Indirect(v)\n\t\tdefault:\n\t\t\trv = reflect.Indirect(reflect.ValueOf(value))\n\t\t}\n\n\t\trt = rv.Type()\n\n\t\tif fv.Type() == rt || rt.AssignableTo(ft) {\n\t\t\tfv.Set(rv)\n\t\t\treturn true\n\t\t}\n\n\t\tif rt.ConvertibleTo(ft) {\n\t\t\treturn setConvertValue(ft, fv, rt, rv)\n\t\t}\n\n\t\tif ft.Kind() == reflect.Ptr {\n\t\t\treturn setPointerValue(ft, fv, rt, rv)\n\t\t}\n\t}\n\n\treturn false\n}", "func (r *Resources) Set(kind string, value float64) {\n\tswitch kind {\n\tcase common.CPU:\n\t\tr.CPU = value\n\tcase common.GPU:\n\t\tr.GPU = value\n\tcase common.MEMORY:\n\t\tr.MEMORY = value\n\tcase common.DISK:\n\t\tr.DISK = value\n\t}\n}", "func (f *Flag) Set(value string) {\n\tf.count++\n\tf.flag.Set(reflect.ValueOf(f.kind.Parse(value)))\n\tf.value = value\n}", "func invokeWithValue(any interface{}, name string, args ...interface{}) []reflect.Value {\n\tinputs := make([]reflect.Value, len(args))\n\tfor i := range args {\n\t\tinputs[i] = reflect.ValueOf(args[i])\n\t}\n\n\tvar m reflect.Value\n\tswitch t := any.(type) {\n\tcase binaryheap.Heap: // 1. type switch , 2 different functions to hook\n\t\tv := any.(binaryheap.Heap)\n\t\tm = reflect.ValueOf(&v).MethodByName(name)\n\tcase btree.Tree: // 1. type switch , 2 different functions to hook\n\t\tv := any.(binaryheap.Heap)\n\t\tm = reflect.ValueOf(&v).MethodByName(name)\n\tdefault:\n\t\tlog.Printf(\"Type %s not found\\n\", t)\n\t}\n\treturn m.Call(inputs)\n}", "func (d *Data) Set(key string, i interface{}) error {\n\tswitch i.(type) {\n\tcase string:\n\t\td.Values[key] = STRING\n\tcase []string:\n\t\td.Values[key] = STRINGSLICE\n\tcase [][]string:\n\t\td.Values[key] = STRINGTABLE\n\tcase *string:\n\t\td.Values[key] = STRINGPOINTER\n\tcase int:\n\t\td.Values[key] = INT\n\tcase *int:\n\t\td.Values[key] = INTPOINTER\n\tcase float64:\n\t\td.Values[key] = FLOAT64\n\tcase []*Option:\n\t\td.Values[key] = OPTION\n\tcase *func():\n\t\td.Values[key] = FUNCPOINTER\n\tdefault:\n\t\treturn ErrTypeNotSupported\n\t}\n\tif d.isExportedData(key) {\n\t\td.Data[key] = i\n\t} else {\n\t\td.unexportedData[key] = i\n\t}\n\td.cache[key] = i\n\n\treturn nil\n}", "func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {\n\tindirects := 1\n\tvt := v.Type()\n\tupv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr)\n\trvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag))\n\tif rvf&flagIndir != 0 {\n\t\tvt = reflect.PtrTo(v.Type())\n\t\tindirects++\n\t} else if offsetScalar != 0 {\n\t\t// The value is in the scalar field when it's not one of the\n\t\t// reference types.\n\t\tswitch vt.Kind() {\n\t\tcase reflect.Uintptr:\n\t\tcase reflect.Chan:\n\t\tcase reflect.Func:\n\t\tcase reflect.Map:\n\t\tcase reflect.Ptr:\n\t\tcase reflect.UnsafePointer:\n\t\tdefault:\n\t\t\tupv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) +\n\t\t\t\toffsetScalar)\n\t\t}\n\t}\n\n\tpv := reflect.NewAt(vt, upv)\n\trv = pv\n\tfor i := 0; i < indirects; i++ {\n\t\trv = rv.Elem()\n\t}\n\treturn rv\n}", "func (x *fastReflection_Metadata) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) {\n\tswitch fd.FullName() {\n\tcase \"cosmos.bank.v1beta1.Metadata.description\":\n\t\tx.Description = value.Interface().(string)\n\tcase \"cosmos.bank.v1beta1.Metadata.denom_units\":\n\t\tlv := value.List()\n\t\tclv := lv.(*_Metadata_2_list)\n\t\tx.DenomUnits = *clv.list\n\tcase \"cosmos.bank.v1beta1.Metadata.base\":\n\t\tx.Base = value.Interface().(string)\n\tcase \"cosmos.bank.v1beta1.Metadata.display\":\n\t\tx.Display = value.Interface().(string)\n\tcase \"cosmos.bank.v1beta1.Metadata.name\":\n\t\tx.Name = value.Interface().(string)\n\tcase \"cosmos.bank.v1beta1.Metadata.symbol\":\n\t\tx.Symbol = value.Interface().(string)\n\tcase \"cosmos.bank.v1beta1.Metadata.uri\":\n\t\tx.Uri = value.Interface().(string)\n\tcase \"cosmos.bank.v1beta1.Metadata.uri_hash\":\n\t\tx.UriHash = value.Interface().(string)\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.bank.v1beta1.Metadata\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.bank.v1beta1.Metadata does not contain field %s\", fd.FullName()))\n\t}\n}", "func (f *Fieldx) Set(v interface{}) error {\n\tif !f.IsExport() {\n\t\treturn ErrNotExported\n\t}\n\n\tif !f.value.CanSet() {\n\t\treturn errNotSettable\n\t}\n\n\tvv := reflect.ValueOf(v)\n\tif f.Kind() != vv.Kind() {\n\t\treturn fmt.Errorf(\"xstruct: value kind not match, want: %s but got %s\", f.Kind(), vv.Kind())\n\t}\n\n\tf.value.Set(vv)\n\n\treturn nil\n}", "func (e Enum) setValue(v any, key string) error {\n\ti, err := e.GetValue(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvValue := reflect.ValueOf(v).Elem()\n\tif !vValue.CanSet() {\n\t\tpanic(fmt.Errorf(\"flagenum: Cannot set supplied value, %v\", vValue))\n\t}\n\n\tiValue := reflect.ValueOf(i)\n\tif !vValue.Type().AssignableTo(iValue.Type()) {\n\t\tpanic(fmt.Errorf(\"flagenum: Enumeration type (%v) is incompatible with supplied value (%v)\",\n\t\t\tvValue.Type(), iValue.Type()))\n\t}\n\n\tvValue.Set(iValue)\n\treturn nil\n}", "func (r *Wrapper) Set(name string, val any) error {\n\tfv := r.rv.FieldByName(name)\n\tif !fv.IsValid() {\n\t\treturn errors.New(\"field not found\")\n\t}\n\n\tif !fv.CanSet() {\n\t\treturn errors.New(\"field can not set value\")\n\t}\n\n\tfv.Set(reflect.ValueOf(val))\n\treturn nil\n}", "func (self *Map) set(key string, value interface{}) typeutil.Variant {\n\tvar vv = typeutil.V(value)\n\tself.data = DeepSet(self.data, strings.Split(key, `.`), vv)\n\n\treturn vv\n}", "func (v *Value) SetValue(i interface{}) error {\n\tswitch i.(type) {\n\tcase bool:\n\t\tv.Value = &Value_Bval{Bval: i.(bool)}\n\tcase float64: // JSON encodes numbers as floats\n\t\tv.Value = &Value_Fval{Fval: i.(float64)}\n\tcase int, int64, int32, int16, int8:\n\t\tival, ok := AsInt64(i)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"unsupported type for %T - %T\", v, i)\n\t\t}\n\t\tv.Value = &Value_Ival{Ival: ival}\n\tcase string:\n\t\tv.Value = &Value_Sval{Sval: i.(string)}\n\tcase time.Time:\n\t\tt := i.(time.Time)\n\t\tv.Value = &Value_Tval{Tval: t.UnixNano()}\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported type for %T - %T\", v, i)\n\t}\n\n\treturn nil\n}", "func (m *TemplateParameter) SetValueType(value *ManagementParameterValueType)() {\n err := m.GetBackingStore().Set(\"valueType\", value)\n if err != nil {\n panic(err)\n }\n}", "func (f *Field) Set(val interface{}) error {\n\t// we can't set unexported fields, so be sure this field is exported\n\tif !f.IsExported() {\n\t\treturn errNotExported\n\t}\n\n\t// do we get here? not sure...\n\tif !f.value.CanSet() {\n\t\treturn errNotSettable\n\t}\n\n\tgiven := reflect.ValueOf(val)\n\n\tif f.value.Kind() != given.Kind() {\n\t\treturn fmt.Errorf(\"wrong kind. got: %s want: %s\", given.Kind(), f.value.Kind())\n\t}\n\n\tf.value.Set(given)\n\treturn nil\n}", "func Set(val, out interface{}) error {\n\t// Special case: map out type must be set through map ptr.\n\tif util.IsMap(val) && util.IsMapPtr(out) {\n\t\treflect.ValueOf(out).Elem().Set(reflect.ValueOf(val))\n\t\treturn nil\n\t}\n\tif util.IsSlice(val) && util.IsSlicePtr(out) {\n\t\treflect.ValueOf(out).Elem().Set(reflect.ValueOf(val))\n\t\treturn nil\n\t}\n\n\tif reflect.TypeOf(val) != reflect.TypeOf(out) {\n\t\treturn fmt.Errorf(\"setFromPath from type %T != to type %T, %v\", val, out, util.IsSlicePtr(out))\n\t}\n\n\tif !reflect.ValueOf(out).CanSet() {\n\t\treturn fmt.Errorf(\"can't set %v(%T) to out type %T\", val, val, out)\n\t}\n\treflect.ValueOf(out).Set(reflect.ValueOf(val))\n\treturn nil\n}", "func (o *ObjectRef) SetField(env *Env, fieldName string, value interface{}) error {\n\tclass, err := o.getClass(env)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvType, vClassName, err := typeOfValue(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar fieldSig string\n\tif env.preCalcSig != \"\" {\n\t\tfieldSig = env.preCalcSig\n\t\tenv.preCalcSig = \"\"\n\t} else {\n\t\tfieldSig = typeSignature(vType, vClassName)\n\t}\n\n\tfid, err := env.callGetFieldID(false, class, fieldName, fieldSig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch v := value.(type) {\n\tcase bool:\n\t\tsetBooleanField(env.jniEnv, o.jobject, fid, fromBool(v))\n\tcase byte:\n\t\tsetByteField(env.jniEnv, o.jobject, fid, jbyte(v))\n\tcase uint16:\n\t\tsetCharField(env.jniEnv, o.jobject, fid, jchar(v))\n\tcase int16:\n\t\tsetShortField(env.jniEnv, o.jobject, fid, jshort(v))\n\tcase int32:\n\t\tsetIntField(env.jniEnv, o.jobject, fid, jint(v))\n\tcase int:\n\t\tsetIntField(env.jniEnv, o.jobject, fid, jint(int32(v)))\n\tcase int64:\n\t\tsetLongField(env.jniEnv, o.jobject, fid, jlong(v))\n\tcase float32:\n\t\tsetFloatField(env.jniEnv, o.jobject, fid, jfloat(v))\n\tcase float64:\n\t\tsetDoubleField(env.jniEnv, o.jobject, fid, jdouble(v))\n\tcase jobj:\n\t\tsetObjectField(env.jniEnv, o.jobject, fid, v.jobj())\n\tcase []bool, []byte, []int16, []uint16, []int32, []int, []int64, []float32, []float64:\n\t\tarray, err := env.toJavaArray(v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer deleteLocalRef(env.jniEnv, array)\n\t\tsetObjectField(env.jniEnv, o.jobject, fid, jobject(array))\n\tdefault:\n\t\treturn errors.New(\"JNIGI unknown field value\")\n\t}\n\n\tif env.exceptionCheck() {\n\t\treturn env.handleException()\n\t}\n\n\treturn nil\n}", "func (r Row) Set(k string, v interface{}) {\n\n\t// If there's no Schema defined, infer from the value itself\n\ttyp, ok := r.Schema[k]\n\tif !ok {\n\t\ttyp, ok = typeof.FromType(reflect.TypeOf(v))\n\t\tif !ok {\n\t\t\treturn // Skip\n\t\t}\n\n\t\tr.Schema[k] = typ\n\t}\n\n\t// Set the value, we have a special-case handling for string types in case the value\n\t// is of different type and was encoded as a string.\n\tswitch s := v.(type) {\n\tcase string:\n\t\tif v, ok := tryParse(s, typ); ok {\n\t\t\tr.Values[k] = v\n\t\t}\n\tdefault:\n\t\tr.Values[k] = v\n\t}\n\n}", "func (s *StructField) Set(v interface{}) error {\n\tif s.field.PkgPath != \"\" {\n\t\treturn errors.New(\"Field is not exported\")\n\t}\n\n\tif !s.CanSet() {\n\t\treturn errors.New(\"Field cannot be set\")\n\t}\n\n\tgiven := reflect.ValueOf(v)\n\n\tif s.value.Kind() != given.Kind() {\n\t\treturn errors.New(\"Field and value kind don't match\")\n\t}\n\n\ts.value.Set(given)\n\treturn nil\n}", "func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {\n\toffset := 1\n\n\tvt := v.Type()\n\tupv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr)\n\trvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag))\n\n\tif (rvf & flagIndir) != 0 {\n\t\tvt = reflect.PtrTo(v.Type())\n\t\toffset++\n\t} else if offsetScalar != 0 {\n\t\tswitch vt.Kind() {\n\t\tcase reflect.Uintptr, reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer: /*Do nonthing*/\n\t\tdefault:\n\t\t\tupv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetScalar)\n\t\t}\n\t}\n\n\tpv := reflect.NewAt(vt, upv)\n\trv = pv\n\tfor i := 0; i < offset; i++ {\n\t\trv = rv.Elem()\n\t}\n\treturn rv\n}", "func Set[T any](p *T, key, value string) error {\n\tif key == \"\" {\n\t\treturn fmt.Errorf(\"key field must not be empty\")\n\t}\n\ttags := strings.Split(key, \".\")\n\tfor _, tag := range tags {\n\t\tif _, _, err := splitTagIndex(tag); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfinalTag := tags[len(tags)-1]\n\tif len(tags) > 1 && (finalTag == \"enabled\" && tags[len(tags)-2] == \"tls\" || finalTag == \"tls\") {\n\t\tswitch value {\n\t\tcase \"{}\":\n\t\tcase \"null\":\n\t\tcase \"true\":\n\t\t\tvalue = \"{}\"\n\t\tcase \"false\":\n\t\t\tvalue = \"null\"\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"%s must be true or {}\", key)\n\t\t}\n\t\tif finalTag == \"enabled\" {\n\t\t\ttags = tags[:len(tags)-1]\n\t\t\tfinalTag = tags[len(tags)-1]\n\t\t}\n\t}\n\n\tfield, other, err := getField(tags, \"\", reflect.ValueOf(p).Elem())\n\tif err != nil {\n\t\treturn err\n\t}\n\tisOther := other != reflect.Value{}\n\n\t// For Other fields, we need to wrap the value in key:value format when\n\t// unmarshaling, and we forbid indexing.\n\tif isOther {\n\t\tif _, index, _ := splitTagIndex(finalTag); index >= 0 {\n\t\t\treturn fmt.Errorf(\"cannot index into unknown field %q\", finalTag)\n\t\t}\n\t\tfield = other\n\t}\n\n\tif !field.CanAddr() {\n\t\treturn errors.New(\"rpk bug, please describe how you encountered this at https://github.com/redpanda-data/redpanda/issues/new?assignees=&labels=kind%2Fbug&template=01_bug_report.md\")\n\t}\n\n\tif isOther {\n\t\tvalue = fmt.Sprintf(\"%s: %s\", finalTag, value)\n\t}\n\n\t// If we cannot unmarshal, but our error looks like we are trying to\n\t// unmarshal a single element into a slice, we index[0] into the slice\n\t// and try unmarshaling again.\n\trawv := []byte(value)\n\tif err := yaml.Unmarshal(rawv, field.Addr().Interface()); err != nil {\n\t\t// First we try wrapped with [ and ].\n\t\tif wrapped, ok := tryValueAsUnwrappedArray(field, value, err); ok {\n\t\t\tif err := yaml.Unmarshal([]byte(wrapped), field.Addr().Interface()); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\t// If that still fails, we try setting a slice value if the\n\t\t// target is a slice.\n\t\tif elem0, ok := tryValueAsSlice0(field, err); ok {\n\t\t\treturn yaml.Unmarshal(rawv, elem0.Addr().Interface())\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "func (obj *BlobAttribute) SetValue(value interface{}) types.TGError {\n\tif value == nil {\n\t\t//errMsg := fmt.Sprintf(\"Attribute value is required\")\n\t\t//return exception.GetErrorByType(types.TGErrorIOException, types.INTERNAL_SERVER_ERROR, errMsg, \"\")\n\t\tobj.attrValue = value\n\t\tobj.setIsModified(true)\n\t\treturn nil\n\t}\n\tif !obj.IsNull() {\n\t\treturn nil\n\t}\n\n\tif \treflect.TypeOf(value).Kind() != reflect.Float32 &&\n\t\treflect.TypeOf(value).Kind() != reflect.Float64 &&\n\t\treflect.TypeOf(value).Kind() != reflect.Array &&\n\t\treflect.TypeOf(value).Kind() != reflect.Struct &&\n\t\treflect.TypeOf(value).Kind() != reflect.String {\n\t\tlogger.Error(fmt.Sprint(\"ERROR: Returning BlobAttribute:SetValue - attribute value is NOT in expected format/type\"))\n\t\terrMsg := fmt.Sprintf(\"Failure to cast the attribute value to BlobAttribute\")\n\t\treturn exception.GetErrorByType(types.TGErrorTypeCoercionNotSupported, types.INTERNAL_SERVER_ERROR, errMsg, \"\")\n\t}\n\n\tif reflect.TypeOf(value).Kind() == reflect.Float32 {\n\t\tv, err := FloatToByteArray(value.(float32))\n\t\tif err != nil {\n\t\t\tlogger.Error(fmt.Sprint(\"ERROR: Returning BlobAttribute:SetValue - unable to extract attribute value in float format/type\"))\n\t\t\terrMsg := fmt.Sprintf(\"Failure to covert float to BlobAttribute\")\n\t\t\treturn exception.GetErrorByType(types.TGErrorTypeCoercionNotSupported, types.INTERNAL_SERVER_ERROR, errMsg, err.Error())\n\t\t}\n\t\tobj.SetBlob(v)\n\t} else if reflect.TypeOf(value).Kind() == reflect.Float64 {\n\t\tv, err := DoubleToByteArray(value.(float64))\n\t\tif err != nil {\n\t\t\tlogger.Error(fmt.Sprint(\"ERROR: Returning BlobAttribute:SetValue - unable to extract attribute value in double format/type\"))\n\t\t\terrMsg := fmt.Sprintf(\"Failure to covert double to BlobAttribute\")\n\t\t\treturn exception.GetErrorByType(types.TGErrorTypeCoercionNotSupported, types.INTERNAL_SERVER_ERROR, errMsg, err.Error())\n\t\t}\n\t\tobj.SetBlob(v)\n\t} else if reflect.TypeOf(value).Kind() == reflect.String {\n\t\tv := []byte(value.(string))\n\t\tobj.SetBlob(v)\n\t} else if reflect.TypeOf(value).Kind() == reflect.Struct {\n\t\tv, err := InputStreamToByteArray(iostream.NewProtocolDataInputStream(value.([]byte)))\n\t\tif err != nil {\n\t\t\tlogger.Error(fmt.Sprint(\"ERROR: Returning BlobAttribute:SetValue - unable to InputStreamToByteArray(iostream.NewProtocolDataInputStream(value.([]byte)))\"))\n\t\t\terrMsg := fmt.Sprintf(\"Failure to covert instream bytes to BlobAttribute\")\n\t\t\treturn exception.GetErrorByType(types.TGErrorTypeCoercionNotSupported, types.INTERNAL_SERVER_ERROR, errMsg, err.Error())\n\t\t}\n\t\tobj.SetBlob(v)\n\t} else {\n\t\tobj.attrValue = value\n\t\tobj.setIsModified(true)\n\t}\n\n\treturn nil\n}", "func NewValue(val interface{}) (*Value, error) {\n\tvar ptr *C.struct__engine_value\n\tvar err error\n\n\t// Determine value type and create PHP value from the concrete type.\n\tv := reflect.ValueOf(val)\n\tswitch v.Kind() {\n\t// Bind integer to PHP int type.\n\tcase reflect.Int:\n\t\tptr, err = C.value_create_long(C.long(v.Int()))\n\t// Bind floating point number to PHP double type.\n\tcase reflect.Float64:\n\t\tptr, err = C.value_create_double(C.double(v.Float()))\n\t// Bind boolean to PHP bool type.\n\tcase reflect.Bool:\n\t\tptr, err = C.value_create_bool(C.bool(v.Bool()))\n\t// Bind string to PHP string type.\n\tcase reflect.String:\n\t\tstr := C.CString(v.String())\n\n\t\tptr, err = C.value_create_string(str)\n\t\tC.free(unsafe.Pointer(str))\n\t// Bind slice to PHP indexed array type.\n\tcase reflect.Slice:\n\t\tif ptr, err = C.value_create_array(C.uint(v.Len())); err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tfor i := 0; i < v.Len(); i++ {\n\t\t\tvs, err := NewValue(v.Index(i).Interface())\n\t\t\tif err != nil {\n\t\t\t\tC.value_destroy(ptr)\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tC.value_array_next_set(ptr, vs.value)\n\t\t}\n\t// Bind map (with integer or string keys) to PHP associative array type.\n\tcase reflect.Map:\n\t\tkt := v.Type().Key().Kind()\n\n\t\tif kt == reflect.Int || kt == reflect.String {\n\t\t\tif ptr, err = C.value_create_array(C.uint(v.Len())); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tfor _, key := range v.MapKeys() {\n\t\t\t\tkv, err := NewValue(v.MapIndex(key).Interface())\n\t\t\t\tif err != nil {\n\t\t\t\t\tC.value_destroy(ptr)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tif kt == reflect.Int {\n\t\t\t\t\tC.value_array_index_set(ptr, C.ulong(key.Int()), kv.value)\n\t\t\t\t} else {\n\t\t\t\t\tstr := C.CString(key.String())\n\n\t\t\t\t\tC.value_array_key_set(ptr, str, kv.value)\n\t\t\t\t\tC.free(unsafe.Pointer(str))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, errInvalidType(val)\n\t\t}\n\t// Bind struct to PHP object (stdClass) type.\n\tcase reflect.Struct:\n\t\tvt := v.Type()\n\t\tif ptr, err = C.value_create_object(); err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tfor i := 0; i < v.NumField(); i++ {\n\t\t\t// Skip unexported fields.\n\t\t\tif vt.Field(i).PkgPath != \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfv, err := NewValue(v.Field(i).Interface())\n\t\t\tif err != nil {\n\t\t\t\tC.value_destroy(ptr)\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tstr := C.CString(vt.Field(i).Name)\n\n\t\t\tC.value_object_property_add(ptr, str, fv.value)\n\t\t\tC.free(unsafe.Pointer(str))\n\t\t}\n\tdefault:\n\t\treturn nil, errInvalidType(val)\n\t}\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to create PHP value from Go value '%v'\", val)\n\t}\n\n\treturn &Value{value: ptr}, nil\n}", "func (m *RegistryKeyState) SetValueType(value *RegistryValueType)() {\n m.valueType = value\n}", "func (e *Env) Set(k string, v interface{}) error {\n\t//fmt.Printf(\"Set(%v,%v)\\n\", k, v)\n\t// BuiltIn variable\n\tif e.isBuiltin(k) {\n\t\tbv := reflect.ValueOf(e.builtin).Elem()\n\t\tbt := reflect.TypeOf(e.builtin).Elem()\n\t\tif f, ok := bt.FieldByName(k); ok {\n\t\t\t/*\n\t\t\t\tif f.Type != reflect.TypeOf(v) {\n\t\t\t\t\treturn fmt.Errorf(\"type of %v must be %v ,not %v.\", f.Name, f.Type, reflect.TypeOf(v))\n\t\t\t\t}\n\t\t\t*/\n\t\t\tswitch reflect.TypeOf(v).Kind() {\n\t\t\tcase f.Type.Kind():\n\t\t\t\tbreak\n\t\t\tcase reflect.Float64:\n\t\t\t\tv = int(v.(float64))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"type of %v must be %v ,not %v\", f.Name, f.Type, reflect.TypeOf(v))\n\t\t\t}\n\t\t\tfv := bv.FieldByName(k)\n\t\t\tif !fv.CanSet() {\n\t\t\t\treturn fmt.Errorf(\"cannot update %v\", f.Name)\n\t\t\t}\n\t\t\tfv.Set(reflect.ValueOf(v))\n\t\t\tif k == \"RS\" {\n\t\t\t\terr := e.setScannerSplit(\"\")\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// global variable\n\tif isGlobalVarName(k) {\n\t\tif _, ok := e.funcArg[k]; ok {\n\t\t\te.funcArg[k] = v\n\t\t\treturn nil\n\t\t}\n\t\tif _, ok := e.global[k]; ok {\n\t\t\te.global[k] = v\n\t\t\treturn nil\n\t\t}\n\t\treturn e.Define(k, v)\n\t}\n\n\t// local variable\n\treturn e.setLocalVar(k, v)\n}", "func (lo *LuaObject) Set(idx interface{}, val interface{}) interface{} {\n L := lo.L\n lo.Push() // the table\n GoToLua(L, nil, valueOf(idx))\n GoToLua(L, nil, valueOf(val))\n L.SetTable(-3)\n L.Pop(1) // the table\n return val\n}", "func (f *FieldHeaderNames) SetValue(val interface{}) {\n\t*f = val.(FieldHeaderNames)\n}", "func setPtrs(structFields []*r.Field, ptrs []interface{}, targetStruct reflect.Value) {\n\tfor index, field := range structFields {\n\t\tif field == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle the case where the embedded struct hasn't been allocated yet\n\t\t// if it's a pointer. Because these are anonymous, if they are nil we\n\t\t// can't access them! We could be smarter here by allocating embedded\n\t\t// pointers (if they aren't allocated already) and traversing the\n\t\t// struct allocating all the way down as necessary\n\t\tif len(field.Index()) > 1 {\n\t\t\telem := targetStruct.FieldByIndex([]int{field.Index()[0]})\n\t\t\tif elem.Kind() == reflect.Ptr && elem.IsNil() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\telem := targetStruct.FieldByIndex(field.Index())\n\t\tif elem.CanSet() {\n\t\t\tdata := reflect.ValueOf(ptrs[index]).Elem()\n\n\t\t\t// To preserve old behaviour, if we got a nil element back, we need\n\t\t\t// to initialize it ourselves\n\t\t\tswitch data.Kind() {\n\t\t\tcase reflect.Map:\n\t\t\t\tif data.IsNil() {\n\t\t\t\t\tdata = reflect.MakeMap(elem.Type())\n\t\t\t\t}\n\t\t\tcase reflect.Slice:\n\t\t\t\tif data.IsNil() {\n\t\t\t\t\tdata = reflect.MakeSlice(elem.Type(), 0, 0)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\telem.Set(data)\n\t\t}\n\t}\n}", "func (m *ModelStructRecord) SetField(name string, value reflect.Value) {\n\tif name == \"\" {\n\t\treturn\n\t}\n\tfieldValue := m.FieldValues[name]\n\t//if value.Kind() == reflect.Ptr {\n\t//\tpanic(\"RecordFieldSetError: value cannot be a ptr\")\n\t//}\n\tif fieldValue.IsValid() == false {\n\t\tm.VirtualFieldValues[name] = reflect.New(m.model.GetFieldWithName(name).StructField().Type).Elem()\n\t\tfieldValue = m.VirtualFieldValues[name]\n\t}\n\t//fieldValue = LoopIndirectAndNew(fieldValue)\n\tsafeSet(fieldValue, value)\n}", "func do(val reflect.Value) error {\n\tvar err error\n\trefType := val.Type()\n\n\t// With refType.Kind() get kind represents the specific kind of type that a Type represents.\n\t// With refType.NumField() obtain the number of fields of the struct\n\t// With refType.Field(position) obtain a struct type's in position\n\tfor i := 0; i < refType.NumField(); i++ {\n\t\tvalue, err := getValue(refType.Field(i))\n\t\tif err != nil {\n\t\t\treturn &EnvError{\n\t\t\t\tKeyName: refType.Field(i).Name,\n\t\t\t\tFieldType: refType.Field(i).Type.String(),\n\t\t\t\tValue: value,\n\t\t\t\tErr: err,\n\t\t\t}\n\t\t}\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tseparator := refType.Field(i).Tag.Get(envSeparator)\n\t\tif err := setValue(val.Field(i), value, separator); err != nil {\n\t\t\treturn &EnvError{\n\t\t\t\tKeyName: refType.Field(i).Name,\n\t\t\t\tFieldType: refType.Field(i).Type.String(),\n\t\t\t\tValue: value,\n\t\t\t\tErr: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn err\n\n}", "func (mdl *Model) Set(key interface{}, value interface{}) error {\n\tif raw, ok := value.(std.Value); ok {\n\t\tvalue = raw\n\t}\n\n\t// Hash model\n\tif std.ModelTypeHash == mdl.GetType() {\n\t\t// hash keys are always strings\n\t\tidx := toString(key)\n\t\tmdl.mux.Lock()\n\t\tdefer mdl.mux.Unlock()\n\t\tif _, ok := mdl.hashIdx[idx]; !ok {\n\t\t\tmdl.hashIdx[idx] = len(mdl.data)\n\t\t\tmdl.idxHash[len(mdl.data)] = idx\n\t\t\tmdl.data = append(mdl.data, value)\n\t\t\treturn nil\n\t\t}\n\t\tmdl.data[mdl.hashIdx[idx]] = value\n\t\treturn nil\n\t}\n\n\t// List model\n\tswitch key.(type) {\n\tcase int, int8, int16, int32, int64,\n\t\tuint, uint8, uint16, uint32, uint64:\n\t\tk := key.(int)\n\t\tmdl.mux.Lock()\n\t\tdefer mdl.mux.Unlock()\n\t\tif k >= len(mdl.data) || k < 0 {\n\t\t\treturn errors.New(InvalidIndex, \"invalid index '%d'\", k)\n\t\t}\n\t\tmdl.data[k] = value\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(InvalidIndexType, \"key '%v' is must be an integer\", key)\n\t}\n}", "func reflectValue(fieldType reflect.Type, fieldValue reflect.Value, v string) (reflect.Value, error) {\n\tswitch k := fieldValue.Kind(); k {\n\tcase reflect.Int16:\n\t\ti, err := strconv.ParseInt(v, 10, 16)\n\t\tif err != nil {\n\t\t\treturn reflect.ValueOf(int16(0)), err\n\t\t}\n\t\treturn reflect.ValueOf(int16(i)), nil\n\tcase reflect.Int32:\n\t\ti, err := strconv.ParseInt(v, 10, 32)\n\t\tif err != nil {\n\t\t\treturn reflect.ValueOf(int32(0)), err\n\t\t}\n\t\treturn reflect.ValueOf(int32(i)), nil\n\tcase reflect.Int64:\n\t\ti, err := strconv.ParseInt(v, 10, 64)\n\t\tif err != nil {\n\t\t\treturn reflect.ValueOf(int64(0)), err\n\t\t}\n\t\treturn reflect.ValueOf(int64(i)), nil\n\tcase reflect.String:\n\t\treturn reflect.ValueOf(v), nil\n\tcase reflect.Bool:\n\t\tb, err := strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn reflect.ValueOf(false), err\n\t\t}\n\t\treturn reflect.ValueOf(bool(b)), nil\n\tcase reflect.Float64:\n\t\tf, err := strconv.ParseFloat(v, 64)\n\t\tif err != nil {\n\t\t\treturn reflect.ValueOf(float64(0)), errors.New(\"error float\")\n\t\t}\n\t\treturn reflect.ValueOf(float64(f)), nil\n\tcase reflect.Slice:\n\t\treturn reflectSliceValue(fieldType, fieldValue, v)\n\tdefault:\n\t\treturn reflect.ValueOf(0), errors.New(\"turbo: not supported kind[\" + k.String() + \"]\")\n\t}\n}", "func (u updater) Set(key, rawValue string, vt string) error {\n\td, ok := Registry[key]\n\tif !ok {\n\t\tif _, ok := retiredSettings[key]; ok {\n\t\t\treturn nil\n\t\t}\n\t\t// Likely a new setting this old node doesn't know about.\n\t\treturn errors.Errorf(\"unknown setting '%s'\", key)\n\t}\n\n\tu.m[key] = struct{}{}\n\n\tif expected := d.Typ(); vt != expected {\n\t\treturn errors.Errorf(\"setting '%s' defined as type %s, not %s\", key, expected, vt)\n\t}\n\n\tswitch setting := d.(type) {\n\tcase *StringSetting:\n\t\treturn setting.set(u.sv, rawValue)\n\tcase *BoolSetting:\n\t\tb, err := strconv.ParseBool(rawValue)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsetting.set(u.sv, b)\n\t\treturn nil\n\tcase numericSetting:\n\t\ti, err := strconv.Atoi(rawValue)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn setting.set(u.sv, int64(i))\n\tcase *FloatSetting:\n\t\tf, err := strconv.ParseFloat(rawValue, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn setting.set(u.sv, f)\n\tcase *DurationSetting:\n\t\td, err := time.ParseDuration(rawValue)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn setting.set(u.sv, d)\n\tcase *EnumSetting:\n\t\ti, err := strconv.Atoi(rawValue)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn setting.set(u.sv, int64(i))\n\tcase *StateMachineSetting:\n\t\treturn setting.set(u.sv, []byte(rawValue))\n\t}\n\treturn nil\n}", "func (x *fastReflection_ServiceCommandDescriptor) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) {\n\tswitch fd.FullName() {\n\tcase \"cosmos.autocli.v1.ServiceCommandDescriptor.service\":\n\t\tx.Service = value.Interface().(string)\n\tcase \"cosmos.autocli.v1.ServiceCommandDescriptor.rpc_command_options\":\n\t\tlv := value.List()\n\t\tclv := lv.(*_ServiceCommandDescriptor_2_list)\n\t\tx.RpcCommandOptions = *clv.list\n\tcase \"cosmos.autocli.v1.ServiceCommandDescriptor.sub_commands\":\n\t\tmv := value.Map()\n\t\tcmv := mv.(*_ServiceCommandDescriptor_3_map)\n\t\tx.SubCommands = *cmv.m\n\tcase \"cosmos.autocli.v1.ServiceCommandDescriptor.enhance_custom_command\":\n\t\tx.EnhanceCustomCommand = value.Bool()\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.autocli.v1.ServiceCommandDescriptor\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.autocli.v1.ServiceCommandDescriptor does not contain field %s\", fd.FullName()))\n\t}\n}", "func visitUnsettableValues(typeOf reflect.Type, original reflect.Value, visitor func(string) string) reflect.Value {\n\tval := reflect.New(typeOf).Elem()\n\texisting := original\n\t// if the value type is interface, we must resolve it to a concrete value prior to setting it back.\n\tif existing.CanInterface() {\n\t\texisting = reflect.ValueOf(existing.Interface())\n\t}\n\tswitch existing.Kind() {\n\tcase reflect.String:\n\t\ts := visitor(existing.String())\n\t\tval.Set(reflect.ValueOf(s))\n\tdefault:\n\t\tif existing.IsValid() && existing.Kind() != reflect.Invalid {\n\t\t\tval.Set(existing)\n\t\t}\n\t\tvisitValue(val, visitor)\n\t}\n\n\treturn val\n}", "func (c StrConv) Set(target interface{}, str string) (ok bool) {\n\tv := reflect.Indirect(reflect.ValueOf(target))\n\treturn c.SetValue(v, str)\n}", "func Defaults(obj interface{}) {\n\tif reflect.TypeOf(obj).Kind() != reflect.Ptr {\n\t\tlog.Panic(\"panic at [yaronsumel/filler] : obj kind passed to Defaults should be Ptr\")\n\t}\n\tv := reflect.TypeOf(obj).Elem()\n\ts := reflect.ValueOf(obj).Elem()\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tcurrentField := v.Field(i)\n\t\ttag := currentField.Tag.Get(defaultsTagName)\n\t\tif tag == emptyTag || tag == ignoreTag {\n\t\t\tcontinue\n\t\t}\n\t\tif s.FieldByName(currentField.Name).CanSet() {\n\t\t\tswitch s.FieldByName(currentField.Name).Kind() {\n\t\t\tcase reflect.Int:\n\t\t\t\ti, _ := strconv.Atoi(tag)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(i))\n\t\t\tcase reflect.Int8:\n\t\t\t\ti, _ := strconv.ParseInt(tag, 10, 8)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(i))\n\t\t\tcase reflect.Int16:\n\t\t\t\ti, _ := strconv.ParseInt(tag, 10, 16)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(i))\n\t\t\tcase reflect.Int32:\n\t\t\t\ti, _ := strconv.ParseInt(tag, 10, 32)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(i))\n\t\t\tcase reflect.Int64:\n\t\t\t\ti, _ := strconv.ParseInt(tag, 10, 64)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(i))\n\t\t\tcase reflect.Uint:\n\t\t\t\tu, _ := strconv.ParseUint(tag, 10, 32)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(u))\n\t\t\tcase reflect.Uint8:\n\t\t\t\tu, _ := strconv.ParseUint(tag, 10, 8)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(u))\n\t\t\tcase reflect.Uint16:\n\t\t\t\tu, _ := strconv.ParseUint(tag, 10, 16)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(u))\n\t\t\tcase reflect.Uint32:\n\t\t\t\tu, _ := strconv.ParseUint(tag, 10, 32)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(u))\n\t\t\tcase reflect.Uint64:\n\t\t\t\tu, _ := strconv.ParseUint(tag, 10, 64)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(u))\n\t\t\tcase reflect.String:\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(tag))\n\t\t\tcase reflect.Bool:\n\t\t\t\tb, _ := strconv.ParseBool(tag)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(b))\n\t\t\tcase reflect.Float32:\n\t\t\t\tf, _ := strconv.ParseFloat(tag, 32)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(f))\n\t\t\tcase reflect.Float64:\n\t\t\t\tf, _ := strconv.ParseFloat(tag, 64)\n\t\t\t\ts.FieldByName(currentField.Name).Set(reflect.ValueOf(f))\n\t\t\t}\n\t\t}\n\t}\n}", "func (vsa *VSA) SetValue(dict *Dictionary, cdr Coder) (err error) {\n\tif vsa.Value != nil { // already set, maybe in application\n\t\treturn\n\t}\n\tda := dict.AttributeWithNumber(vsa.Number, vsa.Vendor)\n\tif da == nil {\n\t\terrStr := fmt.Sprintf(\"DICTIONARY_NOT_FOUND, attribute: <%d>\", vsa.Number)\n\t\tif vsa.Vendor != 0 {\n\t\t\terrStr = fmt.Sprintf(\"DICTIONARY_NOT_FOUND, attribute: <%d>, vendor: <%d>\", vsa.Number, vsa.Vendor)\n\t\t}\n\t\treturn errors.New(errStr)\n\t}\n\tval, strVal, err := cdr.Decode(da.AttributeType, vsa.RawValue)\n\tif err != nil {\n\t\tif err != ErrUnsupportedAttributeType {\n\t\t\treturn err\n\t\t}\n\t\tvsa.Name = ErrUnsupportedAttributeType.Error()\n\t\terr = nil\n\t} else {\n\t\tvsa.Name = da.AttributeName\n\t}\n\tvsa.Type = da.AttributeType\n\tvsa.Value = val\n\tvsa.StringValue = strVal\n\tif vsa.Type == IntegerValue { // Attempty aliasing string value with the one from enum\n\t\tif dv := dict.ValueWithNumber(vsa.Name, uint8(vsa.Value.(uint32)), vsa.Vendor); dv != nil {\n\t\t\tvsa.StringValue = dv.ValueName\n\t\t}\n\t}\n\treturn\n}", "func Do(dst, src interface{}) error {\n\tif err := checkInput(dst, src); err != nil {\n\t\treturn err\n\t}\n\n\tt := reflect.TypeOf(src)\n\tvDst := reflect.ValueOf(dst)\n\tvSrc := reflect.ValueOf(src)\n\n\t// Iterate over all available fields and read the tag value\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tfield := t.Field(i)\n\n\t\tif field.Type.Kind() == reflect.Struct {\n\t\t\t// Pass the address of the interface type to recursion so all supported values get set\n\t\t\t// in entire structure tree\n\t\t\tif err := Do(vDst.Elem().Field(i).Addr().Interface(), vSrc.Field(i).Interface()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// Skip kinds that are not supported\n\t\tif !checkSupportedKind(field.Type.Kind()) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get the field tag value\n\t\ttag, err := newTags(field.Tag.Get(tagOverwrite))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Ignore non tagged fields\n\t\tif !tag.overwrite {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := checkCanSet(vDst.Elem(), field.Name); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif tag.omitempty && vSrc.Field(i).IsZero() {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Overwrite value\n\t\tvDst.Elem().FieldByName(field.Name).Set(vSrc.Field(i))\n\t}\n\n\treturn nil\n}", "func (f *ExtensionField) Set(t protoreflect.ExtensionType, v protoreflect.Value) {\n\tf.typ = t\n\tf.value = v\n\tf.lazy = nil\n}", "func Reflect_Value(v interface{}) *vector_tile.Tile_Value {\n\tvar tv *vector_tile.Tile_Value\n\t//fmt.Print(v)\n\tvv := reflect.ValueOf(v)\n\tkd := vv.Kind()\n\tif (reflect.Float64 == kd) || (reflect.Float32 == kd) {\n\t\t//fmt.Print(v, \"float\", k)\n\t\ttv = Make_Tv_Float(float64(vv.Float()))\n\t\t//hash = Hash_Tv(tv)\n\t} else if (reflect.Int == kd) || (reflect.Int8 == kd) || (reflect.Int16 == kd) || (reflect.Int32 == kd) || (reflect.Int64 == kd) || (reflect.Uint8 == kd) || (reflect.Uint16 == kd) || (reflect.Uint32 == kd) || (reflect.Uint64 == kd) {\n\t\t//fmt.Print(v, \"int\", k)\n\t\ttv = Make_Tv_Int(int(vv.Int()))\n\t\t//hash = Hash_Tv(tv)\n\t} else if reflect.String == kd {\n\t\t//fmt.Print(v, \"str\", k)\n\t\ttv = Make_Tv_String(string(vv.String()))\n\t\t//hash = Hash_Tv(tv)\n\n\t} else {\n\t\ttv := new(vector_tile.Tile_Value)\n\t\tt := \"\"\n\t\ttv.StringValue = &t\n\t}\n\treturn tv\n}", "func PutReflect(b []byte, data interface{}) error {\n\ti := putReflect(b, reflect.ValueOf(data))\n\tif i < 0 {\n\t\treturn errors.New(\"lex.PutReflect: invalid\")\n\t}\n\treturn nil\n}", "func (d *Data) SetData(data *Data) error {\n\tvar err error\n\tfor k, dType := range d.Values {\n\t\tswitch dType {\n\t\tdefault:\n\t\t\td.Data[k] = data.Data[k]\n\t\tcase STRINGPOINTER:\n\t\t\tsp := d.cache[k].(*string)\n\t\t\t*sp = data.Data[k].(string)\n\t\t\td.Data[k] = sp\n\t\tcase INT:\n\t\t\tvar v float64\n\t\t\tv, err = interfaceToFloat(data.Data[k])\n\t\t\td.Data[k] = int(v)\n\t\tcase INTPOINTER:\n\t\t\tvar v float64\n\t\t\tv, err = interfaceToFloat(data.Data[k])\n\t\t\tip := d.cache[k].(*int)\n\t\t\t*ip = int(v)\n\t\t\td.Data[k] = ip\n\t\tcase FUNCPOINTER:\n\t\t\tfp := d.cache[k].(*func())\n\t\t\t*fp = data.unexportedData[k].(func())\n\t\t\td.Data[k] = fp\n\t\tcase FLOAT64:\n\t\t\tvar v float64\n\t\t\tv, err = interfaceToFloat(data.Data[k])\n\t\t\td.Data[k] = v\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func setJSONValue(genericData map[string]interface{}, path []string, value interface{}) error {\n\tcurrentData := genericData\n\tfor index, key := range path {\n\t\tif index == len(path)-1 {\n\t\t\tcurrentData[key] = value\n\t\t} else {\n\t\t\tif currentData[key] == nil {\n\t\t\t\tcurrentData[key] = make(map[string]interface{})\n\t\t\t}\n\t\t\tvar isMap bool\n\t\t\tcurrentData, isMap = currentData[key].(map[string]interface{})\n\t\t\tif !isMap {\n\t\t\t\treturn fmt.Errorf(\"Invalid type for %v\", path[0:index+1])\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (vd *tValueDiffer) writeTypeValue(idx int, v reflect.Value, ht, hv bool) {\n\tv = vd.writeTypeBeforeValue(idx, v, ht)\n\tvd.writeValueAfterType(idx, v, hv)\n}", "func (m *pcpSingletonMetric) set(val interface{}) error {\n\tif !m.t.IsCompatible(val) {\n\t\treturn errors.Errorf(\"value %v is incompatible with MetricType %v\", val, m.t)\n\t}\n\n\tval = m.t.resolve(val)\n\n\tif val != m.val {\n\t\tif m.update != nil {\n\t\t\terr := m.update(val)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tm.val = val\n\t}\n\n\treturn nil\n}", "func hostSetBytes(objId int32, keyId int32, typeId int32, value *byte, size int32)", "func (x *fastReflection_Evidence) Set(fd protoreflect.FieldDescriptor, value protoreflect.Value) {\n\tswitch fd.FullName() {\n\tcase \"tendermint.types.Evidence.duplicate_vote_evidence\":\n\t\tcv := value.Message().Interface().(*DuplicateVoteEvidence)\n\t\tx.Sum = &Evidence_DuplicateVoteEvidence{DuplicateVoteEvidence: cv}\n\tcase \"tendermint.types.Evidence.light_client_attack_evidence\":\n\t\tcv := value.Message().Interface().(*LightClientAttackEvidence)\n\t\tx.Sum = &Evidence_LightClientAttackEvidence{LightClientAttackEvidence: cv}\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: tendermint.types.Evidence\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message tendermint.types.Evidence does not contain field %s\", fd.FullName()))\n\t}\n}", "func (str selfString) makeValue(t reflect.Type) (value reflect.Value, err error) {\n\n\tvar item interface{}\n\tkind := t.Kind()\n\tvalue = reflect.Zero(t)\n\n\tif isScalarKind(kind) {\n\t\tif item, err = str.encodeScalarField(kind); err != nil {\n\t\t\treturn\n\t\t}\n\t\tvalue = reflect.ValueOf(item)\n\n\t} else if isCompoundKind(kind) {\n\t\terr = str.newPackError(\"cannot pack string `\" + str.String() + \"` into field of compound kind \" + kind.String())\n\n\t} else {\n\t\terr = str.newPackError(\"unsupported field kind \" + kind.String())\n\t}\n\n\treturn\n}", "func (c *IssueLabel) SetValue(value interface{}) {\n\tswitch v := value.(type) {\n\tcase string:\n\t\tc.asString = v\n\tcase IssueLabelAsObject:\n\t\tc.issueLabelAsObject = v\n\tdefault:\n\t\tpanic(\"type not acceptable\")\n\t}\n}", "func (access ObjectAccess) Set(row int, val interface{}) {\n access.rawData[access.indices[row]] = val\n}", "func (x *DumpKind) Set(label string) error {\n\tswitch label {\n\tcase \"Version\", \"version\":\n\t\t*x = DumpKindVersion\n\t\treturn nil\n\tcase \"Control\", \"control\":\n\t\t*x = DumpKindControl\n\t\treturn nil\n\tcase \"MsgId\", \"msgid\":\n\t\t*x = DumpKindMsgId\n\t\treturn nil\n\tcase \"TypeMsg\", \"typemsg\":\n\t\t*x = DumpKindTypeMsg\n\t\treturn nil\n\tcase \"ValueMsg\", \"valuemsg\":\n\t\t*x = DumpKindValueMsg\n\t\treturn nil\n\tcase \"MsgLen\", \"msglen\":\n\t\t*x = DumpKindMsgLen\n\t\treturn nil\n\tcase \"AnyMsgLen\", \"anymsglen\":\n\t\t*x = DumpKindAnyMsgLen\n\t\treturn nil\n\tcase \"AnyLensLen\", \"anylenslen\":\n\t\t*x = DumpKindAnyLensLen\n\t\treturn nil\n\tcase \"TypeIdsLen\", \"typeidslen\":\n\t\t*x = DumpKindTypeIdsLen\n\t\treturn nil\n\tcase \"TypeId\", \"typeid\":\n\t\t*x = DumpKindTypeId\n\t\treturn nil\n\tcase \"PrimValue\", \"primvalue\":\n\t\t*x = DumpKindPrimValue\n\t\treturn nil\n\tcase \"ByteLen\", \"bytelen\":\n\t\t*x = DumpKindByteLen\n\t\treturn nil\n\tcase \"ValueLen\", \"valuelen\":\n\t\t*x = DumpKindValueLen\n\t\treturn nil\n\tcase \"Index\", \"index\":\n\t\t*x = DumpKindIndex\n\t\treturn nil\n\tcase \"WireTypeIndex\", \"wiretypeindex\":\n\t\t*x = DumpKindWireTypeIndex\n\t\treturn nil\n\t}\n\t*x = -1\n\treturn fmt.Errorf(\"unknown label %q in vom.DumpKind\", label)\n}", "func makeValue(value interface{}) rpcValue {\n\tvar r rpcValue\n\n\t// empty value\n\tif value == nil {\n\t\treturn r\n\t}\n\n\t// dereference in case of pointer values\n\trefVal := reflect.ValueOf(value)\n\tif refVal.Kind() == reflect.Ptr {\n\t\trefVal = reflect.Indirect(refVal)\n\t\tvalue = refVal.Interface()\n\t}\n\n\tr.value = value\n\tr.kind = nilKind\n\n\tswitch value.(type) {\n\tcase bool:\n\t\tr.kind = booleanKind\n\tcase int, int64, int32, int16, uint, uint64, uint32, uint16, uint8:\n\t\tr.kind = intKind\n\tcase float64, float32:\n\t\tr.kind = doubleKind\n\tcase string:\n\t\tr.kind = stringKind\n\tcase []byte:\n\t\tr.kind = base64Kind\n\tcase time.Time:\n\t\tr.kind = dateTimeKind\n\tdefault:\n\t\tswitch refVal.Kind() {\n\t\tcase reflect.Slice, reflect.Array:\n\t\t\tvar array []rpcValue\n\t\t\tr.value = array // assign nil slice\n\t\t\tr.kind = arrayKind\n\n\t\t\tsize := refVal.Len()\n\t\t\tif size == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tarray = make([]rpcValue, 0, size)\n\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\titem := makeValue(refVal.Index(i).Interface())\n\t\t\t\tarray = append(array, item)\n\t\t\t}\n\t\t\tr.value = array\n\t\tcase reflect.Map:\n\t\t\tvar members []rpcEntry\n\t\t\tr.value = members // assign nil slice\n\t\t\tr.kind = structKind\n\n\t\t\tmapKeys := refVal.MapKeys()\n\t\t\tif len(mapKeys) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tmembers = make([]rpcEntry, 0, len(mapKeys))\n\t\t\tfor _, key := range mapKeys {\n\t\t\t\tentry := rpcEntry{\n\t\t\t\t\tName: fmt.Sprintf(\"%s\", key.Interface()),\n\t\t\t\t\tValue: makeValue(refVal.MapIndex(key).Interface()),\n\t\t\t\t}\n\t\t\t\tmembers = append(members, entry)\n\t\t\t}\n\n\t\t\tr.value = members\n\t\tcase reflect.Struct:\n\t\t\tvar members []rpcEntry\n\t\t\tr.value = members // assign nil slice\n\t\t\tr.kind = structKind\n\n\t\t\tnFields := refVal.NumField()\n\t\t\tif nFields == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\trefType := refVal.Type()\n\t\t\tmembers = make([]rpcEntry, 0, nFields)\n\t\t\tfor i := 0; i < nFields; i++ {\n\t\t\t\t// get the struct field description\n\t\t\t\tfield := refType.Field(i)\n\t\t\t\tentry := rpcEntry{\n\t\t\t\t\tName: field.Name,\n\t\t\t\t\tValue: makeValue(refVal.FieldByName(field.Name).Interface()),\n\t\t\t\t}\n\t\t\t\t// prefer tags if available\n\t\t\t\tif tagName, ok := field.Tag.Lookup(\"rpc\"); ok {\n\t\t\t\t\tentry.Name = tagName\n\t\t\t\t}\n\t\t\t\tmembers = append(members, entry)\n\t\t\t}\n\n\t\t\tr.value = members\n\t\t\tr.kind = structKind\n\t\t}\n\t}\n\treturn r\n}", "func (f BinaryField) Set(v interface{}) FieldAssignment {\n\tswitch v := v.(type) {\n\tcase []byte:\n\t\treturn FieldAssignment{\n\t\t\tField: f,\n\t\t\tValue: Bytes(v),\n\t\t}\n\tdefault:\n\t\treturn FieldAssignment{\n\t\t\tField: f,\n\t\t\tValue: v,\n\t\t}\n\t}\n}", "func (a *ByAttribute) newValue(data interface{}, reflectItems []*modelsNormalization.ReflectStructItem) (reflect.Value, error) {\n\temptyValue := reflect.Value{}\n\tdataKind := system.ReflectValue(data).Kind()\n\n\tswitch dataKind {\n\tcase reflect.Struct:\n\t\treturn a.newStruct(data, reflectItems)\n\tcase reflect.Map:\n\t\treturn a.newMap(data, reflectItems)\n\tdefault:\n\t\treturn emptyValue, fmt.Errorf(\"God %s. Only struct or map can be normalized.\", dataKind)\n\t}\n}", "func reflectValue(obj interface{}) reflect.Value {\n\tv := reflect.ValueOf(obj)\n\tfor v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {\n\t\tv = v.Elem()\n\t}\n\treturn v\n}" ]
[ "0.6907546", "0.68194133", "0.6770028", "0.6657133", "0.65597194", "0.6393843", "0.6316241", "0.6280417", "0.62752694", "0.62395924", "0.6222948", "0.61953694", "0.6170906", "0.61520475", "0.6135036", "0.612724", "0.6100648", "0.6081042", "0.60615283", "0.60114396", "0.60114396", "0.59728175", "0.5956064", "0.5913816", "0.5898973", "0.58662456", "0.5864773", "0.58500403", "0.5785088", "0.57658607", "0.5725446", "0.57216007", "0.5718664", "0.57162803", "0.5709655", "0.56972003", "0.5667099", "0.5658392", "0.5639482", "0.5621645", "0.561781", "0.5604805", "0.55732006", "0.55724156", "0.5525482", "0.5522601", "0.5515764", "0.5512437", "0.5511675", "0.5506081", "0.5504552", "0.5503802", "0.548865", "0.5479736", "0.54527724", "0.54459184", "0.54345775", "0.5434328", "0.5427317", "0.54091644", "0.5405507", "0.540546", "0.5404032", "0.539912", "0.5395012", "0.5382511", "0.5373708", "0.5369004", "0.53637", "0.53516316", "0.5342689", "0.5338028", "0.5337129", "0.5325568", "0.53188246", "0.53141063", "0.530083", "0.5294882", "0.52869964", "0.5277445", "0.5277085", "0.5273227", "0.5272469", "0.52688813", "0.5268665", "0.52594554", "0.52578837", "0.5247009", "0.5246986", "0.52393943", "0.52386874", "0.5235291", "0.5229387", "0.5227543", "0.5225394", "0.52204955", "0.5218348", "0.5216648", "0.5214264", "0.52108717", "0.52103114" ]
0.0
-1
ListPods returns the number of running in the current namespace
func (podInfo *PodInfoHandler) ListPods(w http.ResponseWriter, r *http.Request, p httprouter.Params) { pods, err := podInfo.CoreClient.Pods("").List(metav1.ListOptions{}) if err != nil { log.Printf("error listing pods: %v", err) w.WriteHeader(http.StatusInternalServerError) return } log.Printf("There are %d pods in the cluster\n", len(pods.Items)) resp := models.Response{Message: "OK", PodCount: len(pods.Items)} b, _ := json.Marshal(resp) w.Write(b) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ListPod(token string, url string) (resultado int, pods model.Pods) {\n\tresultado = 0\n\tendpoint := url + apiPods\n\tresultado, resposta := GetRequest(token, endpoint)\n\tdefer resposta.Body.Close()\n\tif resposta.StatusCode == 200 {\n\t\tcorpo, err := ioutil.ReadAll(resposta.Body)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[ListPod] Erro ao ler o conteudo da pagina. Erro: \", err.Error())\n\t\t\tresultado = 1\n\t\t\treturn resultado, pods\n\t\t}\n\t\tpods = model.Pods{}\n\t\terr = json.Unmarshal(corpo, &pods)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[ListPod] Erro ao converter o retorno JSON do Servidor. Erro: \", err.Error())\n\t\t\tresultado = 1\n\t\t}\n\t} else {\n\t\tresultado = 1\n\t}\n\treturn resultado, pods\n}", "func (m *PodRepository) List(n string) (resource.Pods, error) {\n\targs := m.Called(n)\n\treturn args.Get(0).(resource.Pods), args.Error(1)\n}", "func (oc *OpenshiftClient) ListPods(projectName string) (*corev1.PodList, error) {\n\tpath := fmt.Sprintf(OpenshiftPathListPods, projectName)\n\tresp, err := oc.GetRequest(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error occurred performing oc get request : %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tfoundPods := &corev1.PodList{}\n\tif err = json.Unmarshal(respBody, &foundPods); err != nil {\n\t\treturn nil, fmt.Errorf(\"error occurred while unmarshalling pod list: %w\", err)\n\t}\n\n\treturn foundPods, nil\n}", "func (v *VictimBase) numberOfRunningPods(clientset kube.Interface) (int, error) {\n\tpods, err := v.RunningPods(clientset)\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"Failed to get running pods for victim %s %s\", v.kind, v.name)\n\t}\n\n\treturn len(pods), nil\n}", "func countPods(clientSet *kubernetes.Clientset, nodeName string) uint32 {\n\tvar fieldSelector string\n\tif len(nodeName) > 0 {\n\t\tfieldSelector = \"spec.nodeName=\" + nodeName\n\t}\n\tpods, err := clientSet.CoreV1().Pods(\"\").List(context.TODO(), metav1.ListOptions{\n\t\tFieldSelector: fieldSelector,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn uint32(len(pods.Items))\n}", "func (client Client) ListPods(labelQuery map[string]string) (api.PodList, error) {\n\tpath := \"pods\"\n\tif labelQuery != nil && len(labelQuery) > 0 {\n\t\tpath += \"?labels=\" + EncodeLabelQuery(labelQuery)\n\t}\n\tvar result api.PodList\n\t_, err := client.rawRequest(\"GET\", path, nil, &result)\n\treturn result, err\n}", "func GetPods(c *gin.Context) {\n\tconnection := c.MustGet(\"clientset\").(kubernetes.Clientset)\n\tnamespaces, _ := connection.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})\n\n\tvar podsListArray []v1.PodList\n\tfor namespaceIndex := range namespaces.Items {\n\t\tpods, _ := connection.CoreV1().Pods(namespaces.Items[namespaceIndex].Name).List(context.TODO(), metav1.ListOptions{})\n\t\tpodsListArray = append(podsListArray, *pods)\n\t}\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"result\": podsListArray,\n\t})\n}", "func listPods(ctx context.Context, c client.Client, rokku *rokkuv1alpha1.Rokku) ([]rokkuv1alpha1.PodStatus, error) {\n\tpodList := &corev1.PodList{}\n\tlabelSelector := labels.SelectorFromSet(k8s.LabelsForRokku(rokku.Name))\n\tlistOps := &client.ListOptions{Namespace: rokku.Namespace, LabelSelector: labelSelector}\n\terr := c.List(ctx, podList, listOps)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pods []rokkuv1alpha1.PodStatus\n\n\tfor _, p := range podList.Items {\n\t\tif p.Status.PodIP == \"\" {\n\t\t\tp.Status.PodIP = \"<pending>\"\n\t\t}\n\n\t\tif p.Status.HostIP == \"\" {\n\t\t\tp.Status.HostIP = \"<pending>\"\n\t\t}\n\n\t\tpods = append(pods, rokkuv1alpha1.PodStatus{\n\t\t\tName: p.Name,\n\t\t\tPodIP: p.Status.PodIP,\n\t\t\tHostIP: p.Status.HostIP,\n\t\t})\n\t}\n\tsort.Slice(pods, func(i, j int) bool {\n\t\treturn pods[i].Name < pods[j].Name\n\t})\n\n\treturn pods, nil\n}", "func ListPods(t testing.TestingT, options *KubectlOptions, filters metav1.ListOptions) []corev1.Pod {\n\tpods, err := ListPodsE(t, options, filters)\n\trequire.NoError(t, err)\n\treturn pods\n}", "func (k *KubeAPI) ListPods(namespace string) (*v1.PodList, error) {\n\treturn k.Client.CoreV1().Pods(namespace).List(metav1.ListOptions{})\n}", "func listPods(nginx *v1alpha1.Nginx) ([]v1alpha1.NginxPod, error) {\n\tpodList := &corev1.PodList{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Pod\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t}\n\n\tlabelSelector := labels.SelectorFromSet(k8s.LabelsForNginx(nginx.Name)).String()\n\tlistOps := &metav1.ListOptions{LabelSelector: labelSelector}\n\terr := sdk.List(nginx.Namespace, podList, sdk.WithListOptions(listOps))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pods []v1alpha1.NginxPod\n\tfor _, p := range podList.Items {\n\t\tif p.Status.PodIP == \"\" {\n\t\t\tp.Status.PodIP = \"<pending>\"\n\t\t}\n\t\tpods = append(pods, v1alpha1.NginxPod{\n\t\t\tName: p.Name,\n\t\t\tPodIP: p.Status.PodIP,\n\t\t})\n\t}\n\tsort.Slice(pods, func(i, j int) bool {\n\t\treturn pods[i].Name < pods[j].Name\n\t})\n\n\treturn pods, nil\n}", "func (p *Pod) List(ctx context.Context, ns string) ([]runtime.Object, error) {\n\too, err := p.Resource.List(ctx, ns)\n\tif err != nil {\n\t\treturn oo, err\n\t}\n\n\tvar pmx client.PodsMetricsMap\n\tif withMx, ok := ctx.Value(internal.KeyWithMetrics).(bool); withMx || !ok {\n\t\tpmx, _ = client.DialMetrics(p.Client()).FetchPodsMetricsMap(ctx, ns)\n\t}\n\tsel, _ := ctx.Value(internal.KeyFields).(string)\n\tfsel, err := labels.ConvertSelectorToLabelsMap(sel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnodeName := fsel[\"spec.nodeName\"]\n\n\tres := make([]runtime.Object, 0, len(oo))\n\tfor _, o := range oo {\n\t\tu, ok := o.(*unstructured.Unstructured)\n\t\tif !ok {\n\t\t\treturn res, fmt.Errorf(\"expecting *unstructured.Unstructured but got `%T\", o)\n\t\t}\n\t\tfqn := extractFQN(o)\n\t\tif nodeName == \"\" {\n\t\t\tres = append(res, &render.PodWithMetrics{Raw: u, MX: pmx[fqn]})\n\t\t\tcontinue\n\t\t}\n\n\t\tspec, ok := u.Object[\"spec\"].(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn res, fmt.Errorf(\"expecting interface map but got `%T\", o)\n\t\t}\n\t\tif spec[\"nodeName\"] == nodeName {\n\t\t\tres = append(res, &render.PodWithMetrics{Raw: u, MX: pmx[fqn]})\n\t\t}\n\t}\n\n\treturn res, nil\n}", "func (k *KubernetesScheduler) ListPods(selector labels.Selector) (*api.PodList, error) {\n\tlog.V(2).Infof(\"List pods for '%v'\\n\", selector)\n\n\tk.RLock()\n\tdefer k.RUnlock()\n\n\tvar result []api.Pod\n\tfor _, task := range k.runningTasks {\n\t\tpod := task.Pod\n\n\t\tvar l labels.Set = pod.Labels\n\t\tif selector.Matches(l) || selector.Empty() {\n\t\t\tresult = append(result, *pod)\n\t\t}\n\t}\n\n\t// TODO(nnielsen): Refactor tasks append for the three lists.\n\tfor _, task := range k.pendingTasks {\n\t\tpod := task.Pod\n\n\t\tvar l labels.Set = pod.Labels\n\t\tif selector.Matches(l) || selector.Empty() {\n\t\t\tresult = append(result, *pod)\n\t\t}\n\t}\n\n\t// TODO(nnielsen): Wire up check in finished tasks\n\n\tmatches := &api.PodList{Items: result}\n\tlog.V(2).Infof(\"Returning pods: '%v'\\n\", matches)\n\n\treturn matches, nil\n}", "func ListPods(k8s *Client, ns string, selector *LabelSelector) ([]v1.Pod, error) {\n\tpodsSvc := k8s.CoreV1().Pods(ns)\n\tpods, err := podsSvc.List(metav1.ListOptions{LabelSelector: metav1.FormatLabelSelector(selector)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pods.Items, nil\n}", "func podList() *v1.PodList {\n\treturn &v1.PodList{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Pod\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t}\n}", "func podList() *v1.PodList {\n\treturn &v1.PodList{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Pod\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t}\n}", "func ListPodProjeto(token string, url string, projeto string) (resultado int, pods model.Pods) {\n\tresultado = 0\n\tendpoint := url + apiPods + \"namespaces/\" + projeto + \"/pods\"\n\tresultado, resposta := GetRequest(token, endpoint)\n\tdefer resposta.Body.Close()\n\tif resposta.StatusCode == 200 {\n\t\tcorpo, err := ioutil.ReadAll(resposta.Body)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[ListPodProjeto] Erro ao ler o conteudo da pagina. Erro: \", err.Error())\n\t\t\tresultado = 1\n\t\t\treturn resultado, pods\n\t\t}\n\t\tpods = model.Pods{}\n\t\terr = json.Unmarshal(corpo, &pods)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[ListPodProjeto] Erro ao converter o retorno JSON do Servidor. Erro: \", err.Error())\n\t\t\tresultado = 1\n\t\t}\n\t} else {\n\t\tresultado = 1\n\t}\n\treturn resultado, pods\n}", "func ForPodsRunning(clName string, c kubernetes.Interface, namespace, selector string, replicas int) error {\n\tctx := context.Background()\n\tlog.Debugf(\"Waiting for pods to be running. label: %q, namespace: %q, replicas: %v, duration: %v, *types: %s.\", selector, namespace, replicas, defaults.WaitDurationResources, clName)\n\tpodsContext, cancel := context.WithTimeout(ctx, defaults.WaitDurationResources)\n\twait.Until(func() {\n\t\tpodList, err := c.CoreV1().Pods(namespace).List(metav1.ListOptions{\n\t\t\tLabelSelector: selector,\n\t\t\tFieldSelector: \"status.phase=Running\",\n\t\t})\n\t\tif err == nil && len(podList.Items) == replicas {\n\t\t\tlog.Infof(\"✔ All pods with label: %q are running for %s.\", selector, clName)\n\t\t\tcancel()\n\t\t} else {\n\t\t\tlog.Debugf(\"Still waiting for pods. label: %q, namespace: %q, replicas: %v, cluster: %s.\", selector, namespace, replicas, clName)\n\t\t}\n\t}, 15*time.Second, podsContext.Done())\n\n\terr := podsContext.Err()\n\tif err != nil && err != context.Canceled {\n\t\treturn errors.Wrap(err, \"Error waiting for pods to be running.\")\n\t}\n\treturn nil\n}", "func (o *InstanceStatusKubernetes) GetPods() []KubernetesPod {\n\tif o == nil || o.Pods == nil {\n\t\tvar ret []KubernetesPod\n\t\treturn ret\n\t}\n\treturn *o.Pods\n}", "func listPods(client *kubernetes.Clientset, fieldSelector string, labelSelector string) ([]v1.Pod, error) {\n\tlog := log.WithFields(logrus.Fields{\n\t\t\"fieldSelector\": fieldSelector,\n\t\t\"labelSelector\": labelSelector,\n\t})\n\n\tlog.Debug(\"List pods\")\n\tpodList, err := client.CoreV1().Pods(metav1.NamespaceAll).List(metav1.ListOptions{\n\t\tFieldSelector: fieldSelector,\n\t\tLabelSelector: labelSelector,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn podList.Items, nil\n}", "func (c mockK8sClient) GetPods(workload *kubernetes.Workload) ([]corev1.Pod, error) {\n\tvar pods []corev1.Pod\n\tfor i := int32(0); i < c.Counts.NumPods; i++ {\n\t\tpods = append(pods, corev1.Pod{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: fmt.Sprintf(\"%s-%d\", workload.Name, i),\n\t\t\t\tNamespace: workload.Namespace,\n\t\t\t},\n\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\tKind: \"Pod\",\n\t\t\t},\n\t\t\tSpec: workload.PodTemplateSpec.Spec,\n\t\t\tStatus: corev1.PodStatus{\n\t\t\t\tPhase: corev1.PodRunning,\n\t\t\t},\n\t\t})\n\t}\n\treturn pods, nil\n}", "func Pods(namespace string) ([]corev1.Pod, error) {\n\tclientset, err := kubernetesutil.GetClientset()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpods, err := clientset.CoreV1().Pods(namespace).List(context.Background(), metav1.ListOptions{})\n\treturn pods.Items, err\n}", "func List(input ListInput) *corev1.PodList {\n\tExpect(input.Lister).NotTo(BeNil(), \"input.Lister is required for Pod.List\")\n\tExpect(input.Namespace).NotTo(BeNil(), \"input.Namespace is required for Pod.List\")\n\tExpect(len(input.Labels) == 0).NotTo(BeTrue(), \"input.Labels is required for Pod.List\")\n\n\tBy(fmt.Sprintf(\"Listing pods with labels %v in %s namespace\", input.Labels, input.Namespace))\n\n\tpods := &corev1.PodList{}\n\tExpect(input.Lister.List(context.TODO(), pods, client.InNamespace(input.Namespace), client.MatchingLabels(input.Labels))).Should(Succeed())\n\n\treturn pods\n}", "func List(input ListInput) *corev1.PodList {\n\tExpect(input.Lister).NotTo(BeNil(), \"input.Lister is required for Pod.List\")\n\tExpect(input.Namespace).NotTo(BeNil(), \"input.Namespace is required for Pod.List\")\n\tExpect(len(input.Labels) == 0).NotTo(BeTrue(), \"input.Labels is required for Pod.List\")\n\n\tBy(fmt.Sprintf(\"Listing pods with labels %v in %s namespace\", input.Labels, input.Namespace))\n\n\tpods := &corev1.PodList{}\n\tExpect(input.Lister.List(context.TODO(), pods, client.InNamespace(input.Namespace), client.MatchingLabels(input.Labels))).Should(Succeed())\n\n\treturn pods\n}", "func (o ApplicationSpecRolloutplanRolloutbatchesOutput) PodList() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationSpecRolloutplanRolloutbatches) []string { return v.PodList }).(pulumi.StringArrayOutput)\n}", "func getControllerPods(clientSet kubernetes.Interface, namespace string) (*corev1.PodList, error) {\n\tlabelSelector := metav1.LabelSelector{MatchLabels: map[string]string{constants.AppLabel: constants.OSMControllerName}}\n\tpodClient := clientSet.CoreV1().Pods(namespace)\n\tlistOptions := metav1.ListOptions{\n\t\tLabelSelector: labels.Set(labelSelector.MatchLabels).String(),\n\t}\n\treturn podClient.List(context.TODO(), metav1.ListOptions{LabelSelector: listOptions.LabelSelector})\n}", "func (h *KubernetesHelper) CheckPods(ctx context.Context, namespace string, deploymentName string, replicas int) error {\n\tvar checkedPods []corev1.Pod\n\n\terr := h.retryFor(60*time.Minute, func() error {\n\t\tcheckedPods = []corev1.Pod{}\n\t\tpods, err := h.GetPodsForDeployment(ctx, namespace, deploymentName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar deploymentReplicas int\n\t\tfor _, pod := range pods {\n\t\t\tcheckedPods = append(checkedPods, pod)\n\n\t\t\tdeploymentReplicas++\n\t\t\tif pod.Status.Phase != \"Running\" {\n\t\t\t\treturn fmt.Errorf(\"Pod [%s] in namespace [%s] is not running\",\n\t\t\t\t\tpod.Name, pod.Namespace)\n\t\t\t}\n\t\t\tfor _, container := range pod.Status.ContainerStatuses {\n\t\t\t\tif !container.Ready {\n\t\t\t\t\treturn fmt.Errorf(\"Container [%s] in pod [%s] in namespace [%s] is not running\",\n\t\t\t\t\t\tcontainer.Name, pod.Name, pod.Namespace)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif deploymentReplicas != replicas {\n\t\t\treturn fmt.Errorf(\"Expected there to be [%d] pods in deployment [%s] in namespace [%s], but found [%d]\",\n\t\t\t\treplicas, deploymentName, namespace, deploymentReplicas)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, pod := range checkedPods {\n\t\tfor _, status := range append(pod.Status.ContainerStatuses, pod.Status.InitContainerStatuses...) {\n\t\t\terrStr := fmt.Sprintf(\"Container [%s] in pod [%s] in namespace [%s] has restart count [%d]\",\n\t\t\t\tstatus.Name, pod.Name, pod.Namespace, status.RestartCount)\n\t\t\tif status.RestartCount == 1 {\n\t\t\t\treturn &RestartCountError{errStr}\n\t\t\t}\n\t\t\tif status.RestartCount > 1 {\n\t\t\t\treturn errors.New(errStr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Client) PodList(opts metav1.ListOptions) ([]v1.Pod, error) {\n\tvar podList []v1.Pod\n\n\tfor _, ns := range c.namespaces {\n\t\tpods, err := c.API.CoreV1().Pods(ns).List(c.ctx, opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, pod := range pods.Items {\n\t\t\tpodList = appendPod(podList, pod)\n\t\t}\n\t}\n\n\tsort.Slice(podList, func(i, j int) bool {\n\t\treturn podList[i].Name < podList[j].Name\n\t})\n\n\treturn podList, nil\n}", "func (v *VictimBase) RunningPods(clientset kube.Interface) (runningPods []v1.Pod, err error) {\n\tpods, err := v.Pods(clientset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, pod := range pods {\n\t\tif pod.Status.Phase == v1.PodRunning {\n\t\t\trunningPods = append(runningPods, pod)\n\t\t}\n\t}\n\n\treturn runningPods, nil\n}", "func (v *VictimBase) RunningPods(clientset kube.Interface) (runningPods []v1.Pod, err error) {\n\tpods, err := v.Pods(clientset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, pod := range pods {\n\t\tif pod.Status.Phase == v1.PodRunning {\n\t\t\trunningPods = append(runningPods, pod)\n\t\t}\n\t}\n\n\treturn runningPods, nil\n}", "func (p *ZunProvider) GetPods(context.Context) ([]*v1.Pod, error) {\n\tpager := zun_container.List(p.ZunClient, nil)\n\tpages := 0\n\terr := pager.EachPage(func(page pagination.Page) (bool, error) {\n\t\tpages++\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpods := make([]*v1.Pod, 0, pages)\n\terr = pager.EachPage(func(page pagination.Page) (bool, error) {\n\t\tcontainerList, err := zun_container.ExtractContainers(page)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tfor _, m := range containerList {\n\t\t\tc := m\n\t\t\ttemp := new(PodOTemplate)\n\t\t\t//for _, v := range podsDB {\n\t\t\t//\tif v.ContainerID == c.UUID {\n\t\t\t//\t\ttemp = v.Podinfo\n\t\t\t//\t}\n\t\t\t//}\n\t\t\tif zunPod := PodQueryByContainerId(c.UUID); zunPod != nil {\n\t\t\t\ttemp = zunPodToPodinfo(zunPod)\n\t\t\t}\n\t\t\tp, err := containerToPod(&c, temp)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpods = append(pods, p)\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pods, nil\n\n}", "func PodList() *corev1.PodList {\n\treturn &corev1.PodList{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Pod\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t}\n}", "func countPendingPods(cs clientset.Interface, ns string, pods []v1.Pod) int {\n\tpendingPodCount := 0\n\tfor _, p := range pods {\n\t\tif p.Status.Phase == v1.PodPending {\n\t\t\tpendingPodCount++\n\t\t}\n\t}\n\n\treturn pendingPodCount\n}", "func podPorts(job *paddlev1.TrainingJob, podType PodType) []corev1.ContainerPort {\n\n\tvar portsTotal = 0\n\tvar basePort int32 = 0\n\tports := make([]corev1.ContainerPort, 0)\n\n\tif job.Spec.FrameWork == nil {\n\n\t\tif job.Spec.IsNccl && TRAINER == podType ||\n\t\t\t!job.Spec.IsNccl && PSERVER == podType {\n\n\t\t\tbasePort = int32(job.Spec.Port)\n\t\t\tportsTotal = job.Spec.PortsNum + job.Spec.PortsNumForSparse\n\n\t\t\tfor i := 0; i < portsTotal; i++ {\n\t\t\t\tports = append(ports, corev1.ContainerPort{\n\t\t\t\t\tName: fmt.Sprintf(\"jobport-%d\", basePort),\n\t\t\t\t\tContainerPort: basePort,\n\t\t\t\t})\n\t\t\t\tbasePort++\n\t\t\t}\n\n\t\t\treturn ports\n\t\t}\n\t\treturn nil\n\t}\n\n\tframework := *job.Spec.FrameWork\n\n\tif framework.Type == paddlev1.Multi {\n\n\t\tif PSERVER == podType {\n\n\t\t\tportsTotal = job.Spec.PortsNum + job.Spec.PortsNumForSparse\n\t\t\tbasePort = int32(job.Spec.Port)\n\n\t\t} else if TRAINER == podType {\n\n\t\t\tif paddlev1.TensorFlow != framework.Name {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tportsTotal = job.Spec.TrainerPortsNum\n\t\t\tbasePort = int32(job.Spec.TrainerPort)\n\n\t\t}\n\n\t\tfor i := 0; i < portsTotal; i++ {\n\t\t\tports = append(ports, corev1.ContainerPort{\n\t\t\t\tName: fmt.Sprintf(\"jobport-%d\", basePort),\n\t\t\t\tContainerPort: basePort,\n\t\t\t})\n\t\t\tbasePort++\n\t\t}\n\t\treturn ports\n\t}\n\n\tif framework.Type == paddlev1.Nccl2 {\n\n\t\tif TRAINER != podType {\n\t\t\treturn nil\n\t\t}\n\n\t\tbasePort = int32(job.Spec.TrainerPort)\n\t\tportsTotal = job.Spec.TrainerPortsNum\n\n\t\tfor i := 0; i < portsTotal; i++ {\n\t\t\tports = append(ports, corev1.ContainerPort{\n\t\t\t\tName: fmt.Sprintf(\"jobport-%d\", basePort),\n\t\t\t\tContainerPort: basePort,\n\t\t\t})\n\t\t\tbasePort++\n\t\t}\n\n\t\treturn ports\n\n\t}\n\n\treturn nil\n}", "func PrintAllPods() {\n\tcfg := &etcd.ClientConfig{\n\t\tConfig: &clientv3.Config{\n\t\t\tEndpoints: []string{\"127.0.0.1:32379\"},\n\t\t},\n\t\tOpTimeout: 1 * time.Second,\n\t}\n\t// Create connection to etcd.\n\tdb, err := etcd.NewEtcdConnectionWithBytes(*cfg, logrus.DefaultLogger())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\titr, err := db.ListValues(\"/vnf-agent/contiv-ksr/allocatedIDs/\")\n\tif err != nil {\n\t\tfmt.Printf(\"Error getting values\")\n\t\treturn\n\t}\n\tfor {\n\t\tkv, stop := itr.GetNext()\n\t\tif stop {\n\t\t\tfmt.Println()\n\t\t\tbreak\n\t\t}\n\t\tbuf := kv.GetValue()\n\t\tnodeInfo := &nodeinfomodel.NodeInfo{}\n\t\terr = json.Unmarshal(buf, nodeInfo)\n\t\tfmt.Println(\"\\n\" + nodeInfo.Name + \":\")\n\t\tfmt.Println(\"--------------\")\n\n\t\tPrintPodsPerNode(nodeInfo.ManagementIpAddress)\n\t}\n\tdb.Close()\n}", "func getOSMControllerPods(clientSet kubernetes.Interface, ns string) *corev1.PodList {\n\tlabelSelector := metav1.LabelSelector{MatchLabels: map[string]string{constants.AppLabel: constants.OSMControllerName}}\n\tlistOptions := metav1.ListOptions{\n\t\tLabelSelector: labels.Set(labelSelector.MatchLabels).String(),\n\t}\n\tpodList, _ := clientSet.CoreV1().Pods(ns).List(context.TODO(), listOptions)\n\treturn podList\n}", "func ListPodsOnANode(\n\tctx context.Context,\n\tclient clientset.Interface,\n\tnode *v1.Node,\n\topts ...func(opts *Options),\n) ([]*v1.Pod, error) {\n\toptions := &Options{}\n\tfor _, opt := range opts {\n\t\topt(options)\n\t}\n\n\tpods := make([]*v1.Pod, 0)\n\n\tfieldSelectorString := \"spec.nodeName=\" + node.Name + \",status.phase!=\" + string(v1.PodSucceeded) + \",status.phase!=\" + string(v1.PodFailed)\n\n\tlabelSelectorString := \"\"\n\tif options.labelSelector != nil {\n\t\tselector, err := metav1.LabelSelectorAsSelector(options.labelSelector)\n\t\tif err != nil {\n\t\t\treturn []*v1.Pod{}, err\n\t\t}\n\t\tlabelSelectorString = selector.String()\n\t}\n\n\tif len(options.includedNamespaces) > 0 {\n\t\tfieldSelector, err := fields.ParseSelector(fieldSelectorString)\n\t\tif err != nil {\n\t\t\treturn []*v1.Pod{}, err\n\t\t}\n\n\t\tfor _, namespace := range options.includedNamespaces {\n\t\t\tpodList, err := client.CoreV1().Pods(namespace).List(ctx,\n\t\t\t\tmetav1.ListOptions{\n\t\t\t\t\tFieldSelector: fieldSelector.String(),\n\t\t\t\t\tLabelSelector: labelSelectorString,\n\t\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn []*v1.Pod{}, err\n\t\t\t}\n\t\t\tfor i := range podList.Items {\n\t\t\t\tif options.filter != nil && !options.filter(&podList.Items[i]) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tpods = append(pods, &podList.Items[i])\n\t\t\t}\n\t\t}\n\t\treturn pods, nil\n\t}\n\n\tif len(options.excludedNamespaces) > 0 {\n\t\tfor _, namespace := range options.excludedNamespaces {\n\t\t\tfieldSelectorString += \",metadata.namespace!=\" + namespace\n\t\t}\n\t}\n\n\tfieldSelector, err := fields.ParseSelector(fieldSelectorString)\n\tif err != nil {\n\t\treturn []*v1.Pod{}, err\n\t}\n\n\t// INFO(jchaloup): field selectors do not work properly with listers\n\t// Once the descheduler switches to pod listers (through informers),\n\t// We need to flip to client-side filtering.\n\tpodList, err := client.CoreV1().Pods(v1.NamespaceAll).List(ctx,\n\t\tmetav1.ListOptions{\n\t\t\tFieldSelector: fieldSelector.String(),\n\t\t\tLabelSelector: labelSelectorString,\n\t\t})\n\tif err != nil {\n\t\treturn []*v1.Pod{}, err\n\t}\n\n\tfor i := range podList.Items {\n\t\t// fake client does not support field selectors\n\t\t// so let's filter based on the node name as well (quite cheap)\n\t\tif podList.Items[i].Spec.NodeName != node.Name {\n\t\t\tcontinue\n\t\t}\n\t\tif options.filter != nil && !options.filter(&podList.Items[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tpods = append(pods, &podList.Items[i])\n\t}\n\treturn pods, nil\n}", "func WaitForNumberOfPods(c clientset.Interface, ns string, num int, timeout time.Duration) (pods *v1.PodList, err error) {\n\tactualNum := 0\n\terr = wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\tpods, err = c.CoreV1().Pods(ns).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn handleWaitingAPIError(err, false, \"listing pods\")\n\t\t}\n\t\tactualNum = len(pods.Items)\n\t\treturn actualNum == num, nil\n\t})\n\treturn pods, maybeTimeoutError(err, \"waiting for there to be exactly %d pods in namespace (last seen %d)\", num, actualNum)\n}", "func podsCount(cache kubeCache, now time.Time) []types.MetricPoint {\n\ttype podLabels struct {\n\t\tState string\n\t\tKind string\n\t\tName string\n\t\tNamespace string\n\t}\n\n\tpodsCountByLabels := make(map[podLabels]int, len(cache.pods))\n\n\tfor _, pod := range cache.pods {\n\t\tkind, name := podOwner(pod, cache.replicasetOwnerByUID)\n\n\t\tlabels := podLabels{\n\t\t\tState: strings.ToLower(string(podPhase(pod))),\n\t\t\tKind: strings.ToLower(kind),\n\t\t\tName: strings.ToLower(name),\n\t\t\tNamespace: podNamespace(pod),\n\t\t}\n\n\t\tpodsCountByLabels[labels]++\n\t}\n\n\tpoints := make([]types.MetricPoint, 0, len(podsCountByLabels))\n\n\tfor podLabels, count := range podsCountByLabels {\n\t\tlabels := map[string]string{\n\t\t\ttypes.LabelName: \"kubernetes_pods_count\",\n\t\t\ttypes.LabelState: podLabels.State,\n\t\t\ttypes.LabelNamespace: podLabels.Namespace,\n\t\t\ttypes.LabelOwnerKind: podLabels.Kind,\n\t\t\ttypes.LabelOwnerName: podLabels.Name,\n\t\t}\n\n\t\tpoints = append(points, types.MetricPoint{\n\t\t\tPoint: types.Point{Time: now, Value: float64(count)},\n\t\t\tLabels: labels,\n\t\t})\n\t}\n\n\treturn points\n}", "func PodListHandler(_ context.Context, list *corev1.PodList, opts Options) (component.Component, error) {\n\tif list == nil {\n\t\treturn nil, errors.New(\"list is nil\")\n\t}\n\n\tcols := podColsWithLabels\n\tif opts.DisableLabels {\n\t\tcols = podColsWithOutLabels\n\t}\n\n\ttable := component.NewTable(\"Pods\", \"We couldn't find any pods!\", cols)\n\taddPodTableFilters(table)\n\n\tfor i := range list.Items {\n\t\trow := component.TableRow{}\n\t\tnameLink, err := opts.Link.ForObject(&list.Items[i], list.Items[i].Name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trow[\"Name\"] = nameLink\n\n\t\tif !opts.DisableLabels {\n\t\t\trow[\"Labels\"] = component.NewLabels(list.Items[i].Labels)\n\t\t}\n\n\t\treadyCounter := 0\n\t\tfor _, c := range list.Items[i].Status.ContainerStatuses {\n\t\t\tif c.Ready {\n\t\t\t\treadyCounter++\n\t\t\t}\n\t\t}\n\t\tready := fmt.Sprintf(\"%d/%d\", readyCounter, len(list.Items[i].Spec.Containers))\n\t\trow[\"Ready\"] = component.NewText(ready)\n\n\t\trow[\"Phase\"] = component.NewText(string(list.Items[i].Status.Phase))\n\n\t\trestartCounter := 0\n\t\tfor _, c := range list.Items[i].Status.ContainerStatuses {\n\t\t\trestartCounter += int(c.RestartCount)\n\t\t}\n\t\trestarts := fmt.Sprintf(\"%d\", restartCounter)\n\t\trow[\"Restarts\"] = component.NewText(restarts)\n\n\t\tnodeComponent, err := podNode(&list.Items[i], opts.Link)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trow[\"Node\"] = nodeComponent\n\n\t\tts := list.Items[i].CreationTimestamp.Time\n\t\trow[\"Age\"] = component.NewTimestamp(ts)\n\n\t\ttable.Add(row)\n\t}\n\n\ttable.Sort(\"Name\", false)\n\n\treturn table, nil\n}", "func getPodVersions(podList []string, cobraCmd *cobra.Command) map[string]*versionInfo {\n\toutMap := make(map[string]*versionInfo)\n\tcmd := exec.Command(\"kubectl\", \"get\", \"pods\", \"--all-namespaces\", \"-o\", \"jsonpath={range .items[*]}{\\\"{\\\\\\\"name\\\\\\\":\\\\\\\"\\\"}{.status.containerStatuses[].name}{\\\"\\\\\\\",\\\"}{\\\"\\\\\\\"version\\\\\\\":\\\\\\\"\\\"}{.status.containerStatuses[].image}{\\\"\\\\\\\",\\\"}{\\\"\\\\\\\"id\\\\\\\":\\\\\\\"\\\"}{.status.containerStatuses[].imageID}{\\\"\\\\\\\"}\\\\n\\\"}\")\n\toutput, err := utils.ExecuteCmd(cmd, cobraCmd)\n\tif err != nil {\n\t\tfmt.Println(\"Error getting pods version\\n\", err)\n\t} else {\n\t\tpods := strings.Split(output, \"\\n\")\n\t\tfor i := range pods {\n\n\t\t\tvi := new(versionInfo)\n\t\t\terr := json.Unmarshal([]byte(pods[i]), &vi)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsvcName := getSvcName(vi.Name)\n\t\t\tif svcName != \"\" && contains(podList, svcName) {\n\t\t\t\toutMap[svcName] = vi\n\n\t\t\t\t// Build ID (custom docker image label)\n\t\t\t\tcmd := exec.Command(\"docker\", \"image\", \"inspect\", \"--format\", \"{{ index .Config.Labels \\\"MeepVersion\\\"}}\", vi.Version)\n\t\t\t\tvi.BuildID, _ = utils.ExecuteCmd(cmd, cobraCmd)\n\t\t\t\tvi.BuildID = strings.TrimSuffix(vi.BuildID, \"\\n\")\n\n\t\t\t\t// // Image name\n\t\t\t\t// tv := strings.Split(vi.Version, \":\")\n\t\t\t\t// vi.Version = tv[len(tv)-1]\n\n\t\t\t\t// Image ID\n\t\t\t\ttid := strings.Split(vi.VersionID, \":\")\n\t\t\t\tvi.VersionID = tid[len(tid)-1]\n\t\t\t}\n\t\t}\n\t}\n\treturn outMap\n}", "func (client *Client) GetPods(namespace string, params map[string]string) (*v1.PodList, error) {\n\treq := client.Get().\n\t\tResource(\"pods\").\n\t\tNamespace(namespace)\n\tfor k, v := range params {\n\t\treq.Param(k, v)\n\t}\n\n\tres := req.Do()\n\tif res.Error() != nil {\n\t\treturn nil, fmt.Errorf(\"unable to retrieve Pods: %v\", res.Error())\n\t}\n\tlist := &v1.PodList{}\n\tif err := res.Into(list); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse PodList: %v\", res.Error())\n\t}\n\treturn list, nil\n}", "func (tj *TensorFlowJob) AllPods() []v1.Pod {\n\treturn tj.pods\n}", "func (m *podMetrics) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {\n\tpods, err := m.pods(ctx, options)\n\tif err != nil {\n\t\treturn &metrics.PodMetricsList{}, err\n\t}\n\tms, err := m.getMetrics(pods...)\n\tif err != nil {\n\t\tnamespace := genericapirequest.NamespaceValue(ctx)\n\t\tklog.ErrorS(err, \"Failed reading pods metrics\", \"namespace\", klog.KRef(\"\", namespace))\n\t\treturn &metrics.PodMetricsList{}, fmt.Errorf(\"failed reading pods metrics: %w\", err)\n\t}\n\treturn &metrics.PodMetricsList{Items: ms}, nil\n}", "func TestDaemon_ListWorkloads(t *testing.T) {\n\td, start, clean, _, _, _ := mockDaemon(t)\n\tstart()\n\tdefer clean()\n\n\tctx := context.Background()\n\n\t// No namespace\n\ts, err := d.ListServices(ctx, \"\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %s\", err.Error())\n\t}\n\tif len(s) != 2 {\n\t\tt.Fatalf(\"Expected %v but got %v\", 2, len(s))\n\t}\n\n\t// Just namespace\n\ts, err = d.ListServices(ctx, ns)\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %s\", err.Error())\n\t}\n\tif 1 != len(s) {\n\t\tt.Fatalf(\"Expected %v but got %v\", 1, len(s))\n\t}\n\n\t// Invalid NS\n\ts, err = d.ListServices(ctx, invalidNS)\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %s\", err.Error())\n\t}\n\tif len(s) != 0 {\n\t\tt.Fatalf(\"Expected %v but got %v\", 0, len(s))\n\t}\n}", "func PodCounter(clientSet *kubernetes.Clientset, nodeName string) (totalPodsCluster uint32, totalPodsLocal uint32) {\n\t// get pods in all nodes by omitting node\n\ttotalPodsCluster = countPods(clientSet, \"\")\n\t// Or specify to get pods on a particular node\n\ttotalPodsLocal = countPods(clientSet, nodeName)\n\tfmt.Printf(\"There are %d pods in the cluster\\n\", totalPodsCluster)\n\tfmt.Printf(\"There are %d pods on node %s\\n\", totalPodsLocal, nodeName)\n\n\treturn totalPodsCluster, totalPodsLocal\n\t// Examples for error handling:\n\t// - Use helper functions e.g. errors.IsNotFound()\n\t// - And/or cast to StatusError and use its properties like e.g. ErrStatus.Message\n\t//_, err = clientset.CoreV1().Pods(\"default\").Get(context.TODO(), \"example-xxxxx\", metav1.GetOptions{})\n\t//if errors.IsNotFound(err) {\n\t//\tfmt.Printf(\"Pod example-xxxxx not found in default namespace\\n\")\n\t//} else if statusError, isStatus := err.(*errors.StatusError); isStatus {\n\t//\tfmt.Printf(\"Error getting pod %v\\n\", statusError.ErrStatus.Message)\n\t//} else if err != nil {\n\t//\tpanic(err.Error())\n\t//} else {\n\t//\tfmt.Printf(\"Found example-xxxxx pod in default namespace\\n\")\n\t//}\n\n}", "func (t *Task) annotatePods(client k8sclient.Client) error {\n\tfor _, ns := range t.namespaces() {\n\t\tlist := corev1.PodList{}\n\t\toptions := k8sclient.InNamespace(ns)\n\t\terr := client.List(context.TODO(), options, &list)\n\t\tif err != nil {\n\t\t\tlog.Trace(err)\n\t\t\treturn err\n\t\t}\n\t\tfor _, pod := range list.Items {\n\t\t\tif pod.Labels == nil {\n\t\t\t\tpod.Labels = make(map[string]string)\n\t\t\t}\n\t\t\t// Skip stage pods.\n\t\t\tcLabel, _ := t.Owner.GetCorrelationLabel()\n\t\t\tif _, found := pod.Labels[cLabel]; found {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Skip stateless pods.\n\t\t\tif len(pod.Spec.Volumes) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Annotate PVCs.\n\t\t\tvolumes, err := t.annotatePVCs(client, pod)\n\t\t\tif err != nil {\n\t\t\t\tlog.Trace(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif len(volumes) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Restic annotation used to specify volumes.\n\t\t\tif pod.Annotations == nil {\n\t\t\t\tpod.Annotations = make(map[string]string)\n\t\t\t}\n\t\t\tpod.Annotations[ResticPvBackupAnnotation] = strings.Join(volumes, \",\")\n\t\t\t// Add label used by stage backup label selector.\n\t\t\tif pod.Labels == nil {\n\t\t\t\tpod.Labels = make(map[string]string)\n\t\t\t}\n\t\t\tpod.Labels[IncludedInStageBackupLabel] = t.UID()\n\t\t\t// Update\n\t\t\terr = client.Update(context.TODO(), &pod)\n\t\t\tif err != nil {\n\t\t\t\tlog.Trace(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.Info(\n\t\t\t\t\"Pod annotations/labels added.\",\n\t\t\t\t\"ns\",\n\t\t\t\tpod.Namespace,\n\t\t\t\t\"name\",\n\t\t\t\tpod.Name)\n\t\t}\n\t}\n\n\treturn nil\n}", "func ListPod() ([]PodStatus, error) {\n\tdir, err := os.Open(configStoragePath)\n\tif err != nil {\n\t\treturn []PodStatus{}, err\n\t}\n\n\tdefer dir.Close()\n\n\tpodsID, err := dir.Readdirnames(0)\n\tif err != nil {\n\t\treturn []PodStatus{}, err\n\t}\n\n\tvar podStatusList []PodStatus\n\n\tfor _, podID := range podsID {\n\t\tpodStatus, err := StatusPod(podID)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tpodStatusList = append(podStatusList, podStatus)\n\t}\n\n\treturn podStatusList, nil\n}", "func WaitForPodsRunning(kubeClientSet kubernetes.Interface, expectedReplicas int, namespace string, opts metav1.ListOptions) (*v1.PodList, error) {\n\tvar pods *v1.PodList\n\terr := wait.PollImmediate(1*time.Second, time.Minute*5, func() (bool, error) {\n\t\tpl, err := kubeClientSet.CoreV1().Pods(namespace).List(context.TODO(), opts)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\n\t\tr := 0\n\t\tfor i := range pl.Items {\n\t\t\tif pl.Items[i].Status.Phase == v1.PodRunning {\n\t\t\t\tr++\n\t\t\t}\n\t\t}\n\n\t\tif r == expectedReplicas {\n\t\t\tpods = pl\n\t\t\treturn true, nil\n\t\t}\n\n\t\treturn false, nil\n\t})\n\treturn pods, err\n}", "func (m *kubeGenericRuntimeManager) GetPods(ctx context.Context, all bool) ([]*kubecontainer.Pod, error) {\n\tpods := make(map[kubetypes.UID]*kubecontainer.Pod)\n\tsandboxes, err := m.getKubeletSandboxes(ctx, all)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := range sandboxes {\n\t\ts := sandboxes[i]\n\t\tif s.Metadata == nil {\n\t\t\tklog.V(4).InfoS(\"Sandbox does not have metadata\", \"sandbox\", s)\n\t\t\tcontinue\n\t\t}\n\t\tpodUID := kubetypes.UID(s.Metadata.Uid)\n\t\tif _, ok := pods[podUID]; !ok {\n\t\t\tpods[podUID] = &kubecontainer.Pod{\n\t\t\t\tID: podUID,\n\t\t\t\tName: s.Metadata.Name,\n\t\t\t\tNamespace: s.Metadata.Namespace,\n\t\t\t}\n\t\t}\n\t\tp := pods[podUID]\n\t\tconverted, err := m.sandboxToKubeContainer(s)\n\t\tif err != nil {\n\t\t\tklog.V(4).InfoS(\"Convert sandbox of pod failed\", \"runtimeName\", m.runtimeName, \"sandbox\", s, \"podUID\", podUID, \"err\", err)\n\t\t\tcontinue\n\t\t}\n\t\tp.Sandboxes = append(p.Sandboxes, converted)\n\t\tp.CreatedAt = uint64(s.GetCreatedAt())\n\t}\n\n\tcontainers, err := m.getKubeletContainers(ctx, all)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := range containers {\n\t\tc := containers[i]\n\t\tif c.Metadata == nil {\n\t\t\tklog.V(4).InfoS(\"Container does not have metadata\", \"container\", c)\n\t\t\tcontinue\n\t\t}\n\n\t\tlabelledInfo := getContainerInfoFromLabels(c.Labels)\n\t\tpod, found := pods[labelledInfo.PodUID]\n\t\tif !found {\n\t\t\tpod = &kubecontainer.Pod{\n\t\t\t\tID: labelledInfo.PodUID,\n\t\t\t\tName: labelledInfo.PodName,\n\t\t\t\tNamespace: labelledInfo.PodNamespace,\n\t\t\t}\n\t\t\tpods[labelledInfo.PodUID] = pod\n\t\t}\n\n\t\tconverted, err := m.toKubeContainer(c)\n\t\tif err != nil {\n\t\t\tklog.V(4).InfoS(\"Convert container of pod failed\", \"runtimeName\", m.runtimeName, \"container\", c, \"podUID\", labelledInfo.PodUID, \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tpod.Containers = append(pod.Containers, converted)\n\t}\n\n\t// Convert map to list.\n\tvar result []*kubecontainer.Pod\n\tfor _, pod := range pods {\n\t\tresult = append(result, pod)\n\t}\n\n\t// There are scenarios where multiple pods are running in parallel having\n\t// the same name, because one of them have not been fully terminated yet.\n\t// To avoid unexpected behavior on container name based search (for example\n\t// by calling *Kubelet.findContainer() without specifying a pod ID), we now\n\t// return the list of pods ordered by their creation time.\n\tsort.SliceStable(result, func(i, j int) bool {\n\t\treturn result[i].CreatedAt > result[j].CreatedAt\n\t})\n\tklog.V(4).InfoS(\"Retrieved pods from runtime\", \"all\", all)\n\treturn result, nil\n}", "func (s myPodNamespaceLister) List(selector labels.Selector) (ret []*v1.MyPod, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1.MyPod))\n\t})\n\treturn ret, err\n}", "func (in *IstioClient) GetNamespacePods(namespace string) (*v1.PodList, error) {\n\treturn in.k8s.CoreV1().Pods(namespace).List(emptyListOptions)\n}", "func PodList(pods ...kapi.Pod) kapi.PodList {\n\treturn kapi.PodList{\n\t\tItems: pods,\n\t}\n}", "func (cluster *Cluster) LoadPods(namespace string) ([]bitesize.Pod, error) {\n\tclient := &k8s.Client{\n\t\tNamespace: namespace,\n\t\tInterface: cluster.Interface,\n\t\tTPRClient: cluster.TPRClient,\n\t}\n\n\tvar deployedPods []bitesize.Pod\n\tpods, err := client.Pod().List()\n\tif err != nil {\n\t\tlog.Errorf(\"Error loading kubernetes pods: %s\", err.Error())\n\t}\n\n\tfor _, pod := range pods {\n\t\tlogs, err := client.Pod().GetLogs(pod.ObjectMeta.Name)\n\t\tmessage := \"\"\n\t\tif err != nil {\n\t\t\tmessage = fmt.Sprintf(\"Error retrieving Pod Logs: %s\", err.Error())\n\n\t\t}\n\t\tpodval := bitesize.Pod{\n\t\t\tName: pod.ObjectMeta.Name,\n\t\t\tPhase: pod.Status.Phase,\n\t\t\tStartTime: pod.Status.StartTime.String(),\n\t\t\tMessage: message,\n\t\t\tLogs: logs,\n\t\t}\n\t\tdeployedPods = append(deployedPods, podval)\n\t}\n\treturn deployedPods, err\n}", "func getPodList() *v1.PodList {\n\treturn &v1.PodList{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Pod\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t}\n}", "func (s *githubService) Pods(env, branch string) ([]string, error) {\n\t_, directoryContent, _, err := s.getContents(env, branch, \"pods\")\n\tif err != nil {\n\t\tif errResp, ok := err.(*github.ErrorResponse); ok {\n\t\t\tif errResp.Response.StatusCode == 404 {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t}\n\t\treturn nil, err\n\t}\n\tvar pods []string\n\tfor _, content := range directoryContent {\n\t\tparts := strings.Split(*content.Name, \".\")\n\t\tif len(parts) != 2 || parts[1] != \"yaml\" {\n\t\t\tcontinue\n\t\t}\n\t\tpods = append(pods, parts[0])\n\t}\n\treturn pods, nil\n}", "func GetPods() []*Pod {\n\tif len(Pods) > 0 {\n\t\treturn Pods\n\t}\n\tfor _, v := range GetKinds(GetPodByFile, \"pod\") {\n\t\tPods = append(Pods, v.(*Pod))\n\t}\n\treturn Pods\n}", "func (k *Deployment) GetPods() []*Pod {\n\tvar found []*Pod\n\tfor _, v := range GetPods() {\n\t\tif LabelContains(v.Labels, k.Selectors) && v.Namespace == k.Namespace {\n\t\t\tfound = append(found, v)\n\t\t}\n\t}\n\treturn found\n}", "func (in *instance) getPods(tainr *types.Container) ([]corev1.Pod, error) {\n\tpods, err := in.cli.CoreV1().Pods(in.namespace).List(context.TODO(), metav1.ListOptions{\n\t\tLabelSelector: in.getPodsLabelSelector(tainr),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres := []corev1.Pod{}\n\tfor _, p := range pods.Items {\n\t\tif p.ObjectMeta.DeletionTimestamp != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, p)\n\t}\n\treturn res, nil\n}", "func (o *InstanceStatusKubernetes) HasPods() bool {\n\tif o != nil && o.Pods != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func checkPods(podClient v1.CoreV1Interface, logger *log.Logger, filters ...PodPredicate) ([]kubev1.Pod, error) {\n\tlogger = logging.CreateNewStdLoggerOrUseExistingLogger(logger)\n\n\tlogger.Print(\"Checking that all Pods are running or completed...\")\n\n\tlist, err := podClient.Pods(metav1.NamespaceAll).List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting pod list: %v\", err)\n\t}\n\n\tif len(list.Items) == 0 {\n\t\treturn nil, fmt.Errorf(\"pod list is empty. this should NOT happen\")\n\t}\n\n\tpods := filterPods(list, filters...)\n\n\t// Keep track of all pending pods that are not associated with a job\n\t// and store all pods associated with a job for further analysis\n\tpendingPods := []kubev1.Pod{}\n\tjobPods := []kubev1.Pod{}\n\tfor _, pod := range pods.Items {\n\t\tif IsNotControlledByJob(pod) {\n\t\t\t// Completed pod not associated with a job, e.g. a standalone pod\n\t\t\tif pod.Status.Phase == kubev1.PodSucceeded {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif pod.Status.Phase != kubev1.PodPending {\n\t\t\t\treturn nil, fmt.Errorf(\"pod %s/%s in unexpected phase %s: reason: %s message: %s\", pod.Namespace, pod.Name, pod.Status.Phase, pod.Status.Reason, pod.Status.Message)\n\t\t\t}\n\t\t\tlogger.Printf(\"pod %s/%s is not ready. Phase: %s, Reason: %s, Message: %s\", pod.Namespace, pod.Name, pod.Status.Phase, pod.Status.Reason, pod.Status.Message)\n\t\t\tpendingPods = append(pendingPods, pod)\n\t\t} else {\n\t\t\tjobPods = append(jobPods, pod)\n\t\t}\n\t}\n\n\tpendingJobPods, err := checkJobPods(jobPods, logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogger.Printf(\"%v pods are currently not running or complete:\", len(pendingPods)+len(pendingJobPods))\n\n\treturn append(pendingPods, pendingJobPods...), nil\n}", "func (o *InstanceStatusKubernetes) GetPodsOk() (*[]KubernetesPod, bool) {\n\tif o == nil || o.Pods == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Pods, true\n}", "func getPodsFromDeployment(namespace, deploymentName string, clientset *kubernetes.Clientset) (*corev1.PodList, error) {\n\tctx := context.TODO()\n\tdeployment, err := clientset.AppsV1().Deployments(namespace).Get(ctx, deploymentName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tset := labels.Set(deployment.GetLabels())\n\tlistOptions := metav1.ListOptions{LabelSelector: set.AsSelector().String()}\n\n\treturn clientset.CoreV1().Pods(namespace).List(ctx, listOptions)\n}", "func (p *SingletonClientGenerator) PodList(nodeName string, podFilter types.PodFilterFunc) ([]apiv1.Pod, error) {\n\tvar pods *apiv1.PodList\n\n\tkubeclient, err := p.KubeClient()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx := p.newRequestContext()\n\tdefer ctx.Cancel()\n\n\tif pods, err = kubeclient.CoreV1().Pods(metav1.NamespaceAll).List(ctx, metav1.ListOptions{\n\t\tFieldSelector: fields.SelectorFromSet(fields.Set{\"spec.nodeName\": nodeName}).String(),\n\t}); err != nil {\n\t\treturn nil, fmt.Errorf(constantes.ErrPodListReturnError, nodeName, err)\n\t}\n\n\tinclude := make([]apiv1.Pod, 0, len(pods.Items))\n\n\tfor _, pod := range pods.Items {\n\t\tpasses, err := podFilter(pod)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot filter pods, reason: %v\", err)\n\t\t}\n\t\tif passes {\n\t\t\tinclude = append(include, pod)\n\t\t}\n\t}\n\n\treturn include, nil\n}", "func (sink *influxdbSink) GetPodsFromNamespace(namespace string) ([]string, error) {\n\tif !nameAllowedChars.MatchString(namespace) {\n\t\treturn nil, fmt.Errorf(\"Invalid namespace name %q\", namespace)\n\t}\n\t// This is a bit difficult for the influx query language, so we cheat a bit here --\n\t// we just get all series for the uptime measurement for pods which match our namespace\n\t// (any measurement should work here, though)\n\tq := fmt.Sprintf(\"SHOW SERIES FROM %q WHERE %s = '%s' AND type = '%s'\", core.MetricUptime.MetricDescriptor.Name, core.LabelNamespaceName.Key, namespace, core.MetricSetTypePod)\n\treturn sink.stringListQueryCol(q, core.LabelPodName.Key, fmt.Sprintf(\"Unable to list pods in namespace %q\", namespace))\n}", "func GetPodList(cs clientset.Interface, ns string) (*v1.PodList, error) {\n\tvar pods *v1.PodList\n\tvar err error\n\tif wait.PollImmediate(poll, singleCallTimeout, func() (bool, error) {\n\t\tpods, err = cs.CoreV1().Pods(ns).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\tif IsRetryableAPIError(err) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\treturn true, nil\n\t}) != nil {\n\t\treturn pods, err\n\t}\n\treturn pods, nil\n}", "func kubeList(namespace string, target string) ([]string, error) {\n\tkubeCli := &install.CmdKubectl{}\n\tline, err := kubeCli.KubectlOut(nil, \"-n\", namespace, \"get\", target)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar toReturn []string\n\tfor _, line := range strings.Split(strings.TrimSuffix(string(line), \"\\n\"), \"\\n\") {\n\t\tif strings.HasPrefix(line, \"NAME\") || strings.HasPrefix(line, \"No resources found\") {\n\t\t\tcontinue // skip header line and cases where there are no resources\n\t\t}\n\t\tif split := strings.Split(line, \" \"); len(split) > 1 {\n\t\t\ttoReturn = append(toReturn, split[0])\n\t\t}\n\t}\n\treturn toReturn, nil\n}", "func podsRestartCount(cache kubeCache, now time.Time) []types.MetricPoint {\n\tpoints := make([]types.MetricPoint, 0, len(cache.pods))\n\n\tfor _, pod := range cache.pods {\n\t\tkind, name := podOwner(pod, cache.replicasetOwnerByUID)\n\n\t\tlabels := map[string]string{\n\t\t\ttypes.LabelName: \"kubernetes_pods_restart_count\",\n\t\t\ttypes.LabelOwnerKind: strings.ToLower(kind),\n\t\t\ttypes.LabelOwnerName: strings.ToLower(name),\n\t\t\ttypes.LabelPodName: pod.Name,\n\t\t\ttypes.LabelNamespace: pod.Namespace,\n\t\t}\n\n\t\t// The restart count of a pod is the sum of the restart counts of its containers.\n\t\trestartCount := int32(0)\n\n\t\tfor _, container := range pod.Status.ContainerStatuses {\n\t\t\trestartCount += container.RestartCount\n\t\t}\n\n\t\tpoints = append(points, types.MetricPoint{\n\t\t\tPoint: types.Point{Time: now, Value: float64(restartCount)},\n\t\t\tLabels: labels,\n\t\t})\n\t}\n\n\treturn points\n}", "func (k *k8sUtil) Pods() (k8sCoreV1.PodInterface, error) {\n\tvar cs *kubernetes.Clientset\n\n\tinC, err := k.InCluster()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tns, err := k.NS()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif inC {\n\t\tcs, err = k.inClusterCS()\n\t} else {\n\t\tcs, err = k.outClusterCS()\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cs.CoreV1().Pods(ns), nil\n}", "func Pods(c context.Context, namespace string) ([]Object, error) {\n\tls, err := pods(c, namespace).List(c, meta.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tis := ls.Items\n\tos := make([]Object, len(is))\n\tfor i := range is {\n\t\tos[i] = Pod(&is[i])\n\t}\n\treturn os, nil\n}", "func (o MetricStatusOutput) Pods() PodsMetricStatusPtrOutput {\n\treturn o.ApplyT(func(v MetricStatus) *PodsMetricStatus { return v.Pods }).(PodsMetricStatusPtrOutput)\n}", "func (o MetricStatusOutput) Pods() PodsMetricStatusPtrOutput {\n\treturn o.ApplyT(func(v MetricStatus) *PodsMetricStatus { return v.Pods }).(PodsMetricStatusPtrOutput)\n}", "func (c *ClientSetClient) ListPods(node *v1.Node) (*v1.PodList, error) {\n\treturn c.ListPodsByOptions(metav1.NamespaceAll, metav1.ListOptions{\n\t\tFieldSelector: fields.SelectorFromSet(fields.Set{\"spec.nodeName\": node.Name}).String()})\n}", "func (crdRC *crdRequestController) getAllPods(cntxt context.Context, node string) (*corev1.PodList, error) {\n\tvar (\n\t\tpods *corev1.PodList\n\t\terr error\n\t)\n\n\tif pods, err = crdRC.directAPIClient.ListPods(cntxt, allNamespaces, node); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn pods, nil\n}", "func GetKubeletPods(c *client.Client, node string) (*api.PodList, error) {\n\tresult := &api.PodList{}\n\tif err := nodeProxyRequest(c, node, \"runningpods\").Into(result); err != nil {\n\t\treturn &api.PodList{}, err\n\t}\n\treturn result, nil\n}", "func (m *kubeGenericRuntimeManager) GetPods(all bool) ([]*kubecontainer.Pod, error) {\n\tpods := make(map[kubetypes.UID]*kubecontainer.Pod)\n\tsandboxes, err := m.getKubeletSandboxes(all)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := range sandboxes {\n\t\ts := sandboxes[i]\n\t\tif s.Metadata == nil {\n\t\t\tklog.V(4).Infof(\"Sandbox does not have metadata: %+v\", s)\n\t\t\tcontinue\n\t\t}\n\t\tpodUID := kubetypes.UID(s.Metadata.Uid)\n\t\tif _, ok := pods[podUID]; !ok {\n\t\t\tpods[podUID] = &kubecontainer.Pod{\n\t\t\t\tID: podUID,\n\t\t\t\tName: s.Metadata.Name,\n\t\t\t\tNamespace: s.Metadata.Namespace,\n\t\t\t\tTenant: s.Metadata.Tenant,\n\t\t\t}\n\t\t}\n\t\tp := pods[podUID]\n\t\tconverted, err := m.sandboxToKubeContainer(s)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Convert %q sandbox %v of pod %q failed: %v\", m.runtimeName, s, podUID, err)\n\t\t\tcontinue\n\t\t}\n\t\tp.Sandboxes = append(p.Sandboxes, converted)\n\t}\n\n\tcontainers, err := m.getKubeletContainers(all)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := range containers {\n\t\tc := containers[i]\n\t\tif c.Metadata == nil {\n\t\t\tklog.V(4).Infof(\"Container does not have metadata: %+v\", c)\n\t\t\tcontinue\n\t\t}\n\n\t\tlabelledInfo := getContainerInfoFromLabels(c.Labels)\n\t\tpod, found := pods[labelledInfo.PodUID]\n\t\tif !found {\n\t\t\tpod = &kubecontainer.Pod{\n\t\t\t\tID: labelledInfo.PodUID,\n\t\t\t\tName: labelledInfo.PodName,\n\t\t\t\tNamespace: labelledInfo.PodNamespace,\n\t\t\t\tTenant: labelledInfo.PodTenant,\n\t\t\t}\n\t\t\tpods[labelledInfo.PodUID] = pod\n\t\t}\n\n\t\tconverted, err := m.toKubeContainer(c)\n\t\tif err != nil {\n\t\t\tklog.V(4).Infof(\"Convert %s container %v of pod %q failed: %v\", m.runtimeName, c, labelledInfo.PodUID, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tpod.Containers = append(pod.Containers, converted)\n\t}\n\n\t// Convert map to list.\n\tvar result []*kubecontainer.Pod\n\tfor _, pod := range pods {\n\t\tresult = append(result, pod)\n\t}\n\n\treturn result, nil\n}", "func (in *IstioClient) GetPods(namespace, labelSelector string) ([]v1.Pod, error) {\n\t// An empty selector is ambiguous in the go client, could mean either \"select all\" or \"select none\"\n\t// Here we assume empty == select all\n\t// (see also https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors)\n\tpods, err := in.k8s.CoreV1().Pods(namespace).List(meta_v1.ListOptions{LabelSelector: labelSelector})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pods.Items, nil\n}", "func (self *basicPodManager) GetPods() []api.Pod {\n\tself.lock.RLock()\n\tdefer self.lock.RUnlock()\n\treturn self.convertMapToPods(self.podByUID)\n}", "func WaitForPodsRunning(c clientset.Interface, ns string, num int, timeout time.Duration) error {\n\tmatched := 0\n\terr := wait.PollImmediate(poll, timeout, func() (done bool, err error) {\n\t\tpods, err := c.CoreV1().Pods(ns).List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn handleWaitingAPIError(err, true, \"listing pods\")\n\t\t}\n\t\tmatched = 0\n\t\tfor _, pod := range pods.Items {\n\t\t\tif ready, _ := testutils.PodRunningReady(&pod); ready {\n\t\t\t\tmatched++\n\t\t\t}\n\t\t}\n\t\tif matched == num {\n\t\t\treturn true, nil\n\t\t}\n\t\tframework.Logf(\"expect %d pods are running, but got %v\", num, matched)\n\t\treturn false, nil\n\t})\n\treturn maybeTimeoutError(err, \"waiting for pods to be running (want %v, matched %d)\", num, matched)\n}", "func (r *RuntimeServer) GetAppPods(ctx context.Context, re *pb.ServiceRequest) (*pb.ServiceAppPodList, error) {\n\tapp := r.store.GetAppService(re.ServiceId)\n\tif app == nil {\n\t\treturn nil, ErrAppServiceNotFound\n\t}\n\n\tpods := app.GetPods(false)\n\tvar oldpods, newpods []*pb.ServiceAppPod\n\tfor _, pod := range pods {\n\t\tif v1.IsPodTerminated(pod) {\n\t\t\tcontinue\n\t\t}\n\t\t// Exception pod information due to node loss is no longer displayed\n\t\tif v1.IsPodNodeLost(pod) {\n\t\t\tcontinue\n\t\t}\n\t\tvar containers = make(map[string]*pb.Container, len(pod.Spec.Containers))\n\t\tvolumes := make([]string, 0)\n\t\tfor _, container := range pod.Spec.Containers {\n\t\t\tcontainers[container.Name] = &pb.Container{\n\t\t\t\tContainerName: container.Name,\n\t\t\t\tMemoryLimit: container.Resources.Limits.Memory().Value(),\n\t\t\t\tCpuRequest: container.Resources.Requests.Cpu().MilliValue(),\n\t\t\t}\n\t\t\tfor _, vm := range container.VolumeMounts {\n\t\t\t\tvolumes = append(volumes, vm.Name)\n\t\t\t}\n\t\t}\n\n\t\tsapod := &pb.ServiceAppPod{\n\t\t\tPodIp: pod.Status.PodIP,\n\t\t\tPodName: pod.Name,\n\t\t\tContainers: containers,\n\t\t\tPodVolumes: volumes,\n\t\t}\n\t\tpodStatus := &pb.PodStatus{}\n\t\twutil.DescribePodStatus(r.clientset, pod, podStatus, k8sutil.DefListEventsByPod)\n\t\tsapod.PodStatus = podStatus.Type.String()\n\t\tif app.DistinguishPod(pod) {\n\t\t\tnewpods = append(newpods, sapod)\n\t\t} else {\n\t\t\toldpods = append(oldpods, sapod)\n\t\t}\n\t}\n\n\treturn &pb.ServiceAppPodList{\n\t\tOldPods: oldpods,\n\t\tNewPods: newpods,\n\t}, nil\n}", "func PodCount() (int, error) {\n\treturn getValue(podsWatched)\n}", "func getKubeletPods(ctx context.Context, c clientset.Interface, node string) (*v1.PodList, error) {\n\tvar client restclient.Result\n\tfinished := make(chan struct{}, 1)\n\tgo func() {\n\t\t// call chain tends to hang in some cases when Node is not ready. Add an artificial timeout for this call. #22165\n\t\tclient = c.CoreV1().RESTClient().Get().\n\t\t\tResource(\"nodes\").\n\t\t\tSubResource(\"proxy\").\n\t\t\tName(fmt.Sprintf(\"%v:%v\", node, framework.KubeletPort)).\n\t\t\tSuffix(\"pods\").\n\t\t\tDo(ctx)\n\n\t\tfinished <- struct{}{}\n\t}()\n\tselect {\n\tcase <-finished:\n\t\tresult := &v1.PodList{}\n\t\tif err := client.Into(result); err != nil {\n\t\t\treturn &v1.PodList{}, err\n\t\t}\n\t\treturn result, nil\n\tcase <-time.After(framework.PodGetTimeout):\n\t\treturn &v1.PodList{}, fmt.Errorf(\"Waiting up to %v for getting the list of pods\", framework.PodGetTimeout)\n\t}\n}", "func PrintPodsPerNode(input string) {\n\thostIP := ResolveNodeOrIP(input)\n\tcfg := &etcd.ClientConfig{\n\t\tConfig: &clientv3.Config{\n\t\t\tEndpoints: []string{\"127.0.0.1:32379\"},\n\t\t},\n\t\tOpTimeout: 1 * time.Second,\n\t}\n\tlogger := logrus.DefaultLogger()\n\tlogger.SetLevel(logging.FatalLevel)\n\tw := tabwriter.NewWriter(os.Stdout, 0, 8, 0, '\\t', 0)\n\t// Create connection to etcd.\n\tdb, err := etcd.NewEtcdConnectionWithBytes(*cfg, logger)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\titr, err := db.ListValues(\"/vnf-agent/contiv-ksr/k8s/pod/\")\n\tif err != nil {\n\t\tfmt.Printf(\"Error getting values\")\n\t\treturn\n\t}\n\tfmt.Fprintf(w, \"name\\tip_address\\thost_ip_addr\\ttap_ip\\toutgoing_idx\\ttag\\n\")\n\n\tfor {\n\t\tkv, stop := itr.GetNext()\n\t\tif stop {\n\t\t\tbreak\n\t\t}\n\t\tbuf := kv.GetValue()\n\t\tpodInfo := &pod.Pod{}\n\t\terr = json.Unmarshal(buf, podInfo)\n\t\tif podInfo.HostIpAddress != hostIP || podInfo.IpAddress == hostIP {\n\t\t\tcontinue\n\t\t}\n\t\tif ipAddress, ifIndex, tag, err := printTapInterfaces(podInfo); err == nil {\n\t\t\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\t%d\\t%s\\n\",\n\t\t\t\tpodInfo.Name,\n\t\t\t\tpodInfo.IpAddress,\n\t\t\t\tpodInfo.HostIpAddress,\n\t\t\t\tipAddress,\n\t\t\t\tifIndex,\n\t\t\t\ttag)\n\n\t\t} else {\n\t\t\tfmt.Printf(\"error %s\\n\", err)\n\t\t}\n\t}\n\tw.Flush()\n\tdb.Close()\n}", "func getPodsInfoFromTask(cluster *imec_db.DB_INFRASTRUCTURE_CLUSTER, result map[string]interface{}, appPort int, appProtocol string) []structs.DB_TASK_POD {\n\tlog.Println(pathLOG + \"COMPSs [getPodsInfoFromTask] Getting info from pods ...\")\n\n\t// items\n\titems := result[\"items\"].([]interface{})\n\tlog.Println(pathLOG + \"COMPSs [getPodsInfoFromTask] Total pods = \" + strconv.Itoa(len(items)))\n\n\t// final res\n\tvar lres []structs.DB_TASK_POD\n\n\t// iterate json (response)\n\tfor _, item := range items { // \"items\" element ==> PODS INFO\n\t\t/* DB_TASK_POD:\n\t\t{\n\t\t\tName string `json:\"name,omitempty\"`\n\t\t\tIP string `json:\"ip,omitempty\"` // IP accessed by external apps\n\t\t\tHostIP string `json:\"hostIp,omitempty\"` // node IP\n\t\t\tPodIP string `json:\"podIp,omitempty\"` // internal IP created by Kubernetes / Openshift\n\t\t\tStatus string `json:\"status,omitempty\"` // running, unknown\n\t\t\tPort int `json:\"port,omitempty\"` // port exposed in Kubernetes / Openshift\n\t\t\tTargetPort int `json:\"targetPort,omitempty\"` // application port\n\t\t}\n\t\t*/\n\t\tpodData := &structs.DB_TASK_POD{}\n\t\tpodData.IP = urls.GetHostIP(cluster) // cfg.Config.Clusters[clusterIndex].HostIP\n\t\tpodData.Port = adapt_common.NewRPort()\n\t\tpodData.TargetPort = appPort\n\t\tpodData.Protocol = appProtocol\n\n\t\t// \"metadata\" element\n\t\tfor key1, value1 := range item.(map[string]interface{}) {\n\t\t\tif key1 == \"metadata\" {\n\t\t\t\tfor key2, value2 := range value1.(map[string]interface{}) {\n\t\t\t\t\tif key2 == \"name\" {\n\t\t\t\t\t\tpodData.Name = value2.(string) // Pod name\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if key1 == \"status\" {\n\t\t\t\tfor key2, value2 := range value1.(map[string]interface{}) {\n\t\t\t\t\tif key2 == \"podIP\" {\n\t\t\t\t\t\tpodData.PodIP = value2.(string) // IP address from pod\n\t\t\t\t\t} else if key2 == \"hostIP\" {\n\t\t\t\t\t\tpodData.HostIP = urls.GetHostIP(cluster) // value2.(string) // IP address from node\n\t\t\t\t\t} else if key2 == \"phase\" {\n\t\t\t\t\t\tpodData.Status = value2.(string) // Status / Phase from pod\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlog.Debug(pathLOG + \"COMPSs [getPodsInfoFromTask] POD \" + podData.Name)\n\t\tlog.Debug(pathLOG + \"COMPSs [getPodsInfoFromTask] - PodIP: \" + podData.PodIP)\n\t\tlog.Debug(pathLOG + \"COMPSs [getPodsInfoFromTask] - HostIP: \" + podData.HostIP)\n\t\tlog.Debug(pathLOG + \"COMPSs [getPodsInfoFromTask] - Status: \" + podData.Status)\n\t\tlog.Debug(pathLOG + \"COMPSs [getPodsInfoFromTask] - Port: \" + strconv.Itoa(podData.Port))\n\t\tlog.Debug(pathLOG + \"COMPSs [getPodsInfoFromTask] - TargetPort: \" + strconv.Itoa(podData.TargetPort))\n\n\t\tlres = append(lres, *podData)\n\t}\n\n\tlog.Println(pathLOG + \"COMPSs [getPodsInfoFromTask] Total pods response = \" + strconv.Itoa(len(lres)))\n\n\treturn lres\n}", "func Pods(context string) ([]v1.Pod, error) {\n\tcs, err := getClientSet(context)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctxConfig, ok := config.Contexts[context]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"no context named %s\", context)\n\t}\n\n\tresp, err := cs.Pods(ctxConfig.Namespace).List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.Items, nil\n}", "func GetPodsWithNamespace(c *gin.Context) {\n\tnamespace := c.Param(\"namespace\")\n\tconnection := c.MustGet(\"clientset\").(kubernetes.Clientset)\n\tpods, _ := connection.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{})\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"result\": pods,\n\t})\n}", "func CreatePods(f *framework.Framework, appName string, ns string, labels map[string]string, spec v1.PodSpec, maxCount int, tuning *TuningSetType) {\n\tfor i := 0; i < maxCount; i++ {\n\t\tframework.Logf(\"%v/%v : Creating pod\", i+1, maxCount)\n\t\t// Retry on pod creation failure\n\t\tfor retryCount := 0; retryCount < maxRetries; retryCount++ {\n\t\t\t_, err := f.ClientSet.Core().Pods(ns).Create(&v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: fmt.Sprintf(appName+\"-pod-%v\", i),\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: spec,\n\t\t\t})\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tframework.ExpectNoError(err)\n\t\t}\n\t\tif tuning != nil {\n\t\t\t// If a rate limit has been defined we wait for N ms between creation\n\t\t\tif tuning.Pods.RateLimit.Delay != 0 {\n\t\t\t\tframework.Logf(\"Sleeping %d ms between podcreation.\", tuning.Pods.RateLimit.Delay)\n\t\t\t\ttime.Sleep(tuning.Pods.RateLimit.Delay * time.Millisecond)\n\t\t\t}\n\t\t\t// If a stepping tuningset has been defined in the config, we wait for the step of pods to be created, and pause\n\t\t\tif tuning.Pods.Stepping.StepSize != 0 && (i+1)%tuning.Pods.Stepping.StepSize == 0 {\n\t\t\t\tverifyRunning := f.NewClusterVerification(\n\t\t\t\t\t&v1.Namespace{\n\t\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\t\t\tName: ns,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tStatus: v1.NamespaceStatus{},\n\t\t\t\t\t},\n\t\t\t\t\tframework.PodStateVerification{\n\t\t\t\t\t\tSelectors: labels,\n\t\t\t\t\t\tValidPhases: []v1.PodPhase{v1.PodRunning},\n\t\t\t\t\t},\n\t\t\t\t)\n\n\t\t\t\tpods, err := verifyRunning.WaitFor(i+1, tuning.Pods.Stepping.Timeout*time.Second)\n\t\t\t\tif err != nil {\n\t\t\t\t\tframework.Failf(\"Error in wait... %v\", err)\n\t\t\t\t} else if len(pods) < i+1 {\n\t\t\t\t\tframework.Failf(\"Only got %v out of %v\", len(pods), i+1)\n\t\t\t\t}\n\n\t\t\t\tframework.Logf(\"We have created %d pods and are now sleeping for %d seconds\", i+1, tuning.Pods.Stepping.Pause)\n\t\t\t\ttime.Sleep(tuning.Pods.Stepping.Pause * time.Second)\n\t\t\t}\n\t\t}\n\t}\n}", "func GetPods(contextName string, namespace string) []corev1.Pod {\n\n\tctxReceiver, ok := contextReceivers[contextName]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tnsReceiver, ok := ctxReceiver.namespaceReceivers[namespace]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treceiver := nsReceiver.podEventReceiver\n\tif receiver == nil {\n\t\treturn nil\n\t}\n\n\treturn receiver.getPods()\n}", "func (c *Cluster) checkPods() error {\n\tif err := c.reconcileSize(); err != nil {\n\t\treturn err\n\t}\n\treturn c.reconcileVersion()\n}", "func (o MetricStatusPatchOutput) Pods() PodsMetricStatusPatchPtrOutput {\n\treturn o.ApplyT(func(v MetricStatusPatch) *PodsMetricStatusPatch { return v.Pods }).(PodsMetricStatusPatchPtrOutput)\n}", "func (o MetricStatusPatchOutput) Pods() PodsMetricStatusPatchPtrOutput {\n\treturn o.ApplyT(func(v MetricStatusPatch) *PodsMetricStatusPatch { return v.Pods }).(PodsMetricStatusPatchPtrOutput)\n}", "func (nvsdc *NuageVsdClient) GetPodInterfaces(podName string) (*[]vspk.ContainerInterface, error) {\n\t//iterates over a list of containers with name matching the podName and then gets its interface elements.\n\tresult := make([]vspk.Container, 0, 100)\n\tvar interfaces []vspk.ContainerInterface\n\te := api.RESTError{}\n\tnvsdc.session.Header.Add(\"X-Nuage-PageSize\", \"100\")\n\n\tpage := 0\n\tnvsdc.session.Header.Add(\"X-Nuage-Page\", strconv.Itoa(page))\n\t// guarantee that the headers are cleared so that we don't change the\n\t// behavior of other functions\n\tdefer nvsdc.session.Header.Del(\"X-Nuage-PageSize\")\n\tdefer nvsdc.session.Header.Del(\"X-Nuage-Page\")\n\tfor {\n\t\tnvsdc.session.Header.Add(\"X-Nuage-Filter\", `name == \"`+podName+`\"`)\n\t\tresp, err := nvsdc.session.Get(nvsdc.url+\"domains/\"+nvsdc.domainID+\"/containers\",\n\t\t\tnil, &result, &e)\n\t\tnvsdc.session.Header.Del(\"X-Nuage-Filter\")\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Error when getting containers matching %s: %s\", podName, err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif resp.Status() == http.StatusNoContent || resp.HttpResponse().Header.Get(\"x-nuage-count\") == \"0\" {\n\t\t\tif page == 0 {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\treturn &interfaces, nil\n\t\t\t}\n\t\t} else if resp.Status() == http.StatusOK {\n\t\t\t// Add all the items on this page to the list\n\t\t\tfor _, container := range result {\n\t\t\t\tif interfaceList, err := nvsdc.GetInterfaces(container.ID); err != nil {\n\t\t\t\t\tglog.Errorf(\"Unable to get container interfaces for container %s\", container.ID)\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tfor _, intf := range *interfaceList {\n\t\t\t\t\t\tinterfaces = append(interfaces, intf)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If there's less than 100 items in the page, we must've reached\n\t\t\t// the last page. Break here instead of getting the next\n\t\t\t// (guaranteed empty) page.\n\t\t\tif count, err := strconv.Atoi(resp.HttpResponse().Header.Get(\"x-nuage-count\")); err == nil {\n\t\t\t\tif count < 100 {\n\t\t\t\t\treturn &interfaces, nil\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Something went wrong with parsing the x-nuage-count header\n\t\t\t\treturn nil, errors.New(\"Invalid X-Nuage-Count: \" + err.Error())\n\t\t\t}\n\t\t\t// Update headers to get the next page\n\t\t\tpage++\n\t\t\tnvsdc.session.Header.Set(\"X-Nuage-Page\", strconv.Itoa(page))\n\t\t} else {\n\t\t\t// Something went wrong\n\t\t\treturn nil, VsdErrorResponse(resp, &e)\n\t\t}\n\t}\n\treturn nil, errors.New(\"Unable to fetch pods in the domain and their interfaces\")\n}", "func NewPodsWidget(apiClient *api.Client, filter api.Filter, sortorder api.Sort, termWidth, termHeight int) *PodsWidget {\n\ttable := NewTable()\n\ttable.Header = []string{\"NAMESPACE\", \"POD\", \"READY\", \"STATUS\", \"RESTARTS\", \"CPU\", \"CPU MAX\", \"MEMORY\", \"MEMORY MAX\", \"IP\", \"AGE\"}\n\ttable.UniqueCol = 1\n\n\ttable.SetRect(0, 0, termWidth, termHeight)\n\n\ttable.ColWidths = []int{20, helpers.MaxInt(table.Inner.Dx()-150, 40), 10, 20, 10, 15, 15, 15, 15, 20, 10}\n\ttable.ColResizer = func() {\n\t\ttable.ColWidths = []int{20, helpers.MaxInt(table.Inner.Dx()-150, 40), 10, 20, 10, 15, 15, 15, 15, 20, 10}\n\t}\n\n\ttable.Border = false\n\ttable.BorderStyle = ui.NewStyle(ui.ColorClear)\n\n\treturn &PodsWidget{\n\t\ttable,\n\n\t\tapiClient,\n\t\tfilter,\n\t\tfalse,\n\t\tsortorder,\n\t}\n}", "func (as *AlamedaScaler) GetMonitoredPods() []*AlamedaPod {\n\tpods := make([]*AlamedaPod, 0)\n\n\tfor _, alamedaResource := range as.Status.AlamedaController.Deployments {\n\t\tfor _, pod := range alamedaResource.Pods {\n\t\t\tcpPod := pod\n\t\t\tpods = append(pods, &cpPod)\n\t\t}\n\t}\n\n\tfor _, alamedaResource := range as.Status.AlamedaController.DeploymentConfigs {\n\t\tfor _, pod := range alamedaResource.Pods {\n\t\t\tcpPod := pod\n\t\t\tpods = append(pods, &cpPod)\n\t\t}\n\t}\n\n\tfor _, alamedaResource := range as.Status.AlamedaController.StatefulSets {\n\t\tfor _, pod := range alamedaResource.Pods {\n\t\t\tcpPod := pod\n\t\t\tpods = append(pods, &cpPod)\n\t\t}\n\t}\n\n\treturn pods\n}", "func RetrievePodList(client *kubernetes.Clientset, options metav1.ListOptions) *corev1.PodList {\n\tpods, err := client.CoreV1().Pods(metav1.NamespaceAll).List(options)\n\tif err != nil {\n\t\tlog.Errorf(\"failed to retrieve pods: %v\", err)\n\t\treturn nil\n\t}\n\treturn pods\n}", "func List(namespace string, c kubernetes.Interface) ([]appsv1.Deployment, error) {\n\tdList, err := c.AppsV1().Deployments(namespace).List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dList.Items, nil\n}", "func (s *Server) ListPodsByNodeName(ctx context.Context, in *datahub_v1alpha1.ListPodsByNodeNamesRequest) (*datahub_v1alpha1.ListPodsResponse, error) {\n\tscope.Debug(\"Request received from ListPodsByNodeName grpc function: \" + utils.InterfaceToString(in))\n\n\treturn &datahub_v1alpha1.ListPodsResponse{\n\t\tStatus: &status.Status{\n\t\t\tCode: int32(code.Code_OK),\n\t\t\tMessage: \"This function is deprecated.\",\n\t\t},\n\t}, nil\n}", "func getPodInfos(sdk sdkAPI, namespace, name string) ([]PodInfo, error) {\n\tappID := edgelbDcos.PoolAppID(namespace, name)\n\tlbNames, _, err := getPoolLbNames(sdk, appID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not reach the pool scheduler with name '%s/%s'.\\nWas the pool recently installed, updated, or uninstalled? It may still be initializing, wait a bit and try again\", namespace, name)\n\t}\n\tstatuses := []PodInfo{}\n\tfor _, lbName := range lbNames {\n\t\toutput, outputErr := sdk.podHandleInfo(appID, lbName)\n\t\tif outputErr != nil {\n\t\t\tfmt.Printf(\"%s\\n\", string(output))\n\t\t\treturn nil, outputErr\n\t\t}\n\t\tpodInfo, parseErr := parsePodInfo(output, lbName)\n\t\tif parseErr != nil {\n\t\t\treturn nil, parseErr\n\t\t}\n\t\tstatuses = append(statuses, podInfo)\n\t}\n\treturn statuses, nil\n}", "func (kc *k8sCluster) findNumK8sObjects() map[string]int {\n\tobjectMap := make(map[string]int)\n\tvar numServices, numEndpoints, numPods int\n\n\tkc.accLock.Lock()\n\tobjectMap[\"namespaces\"] = len(kc.watchers)\n\tfor _, watcher := range kc.watchers {\n\t\tnumServices += len(watcher.Services)\n\t\tnumEndpoints += len(watcher.Endpoints)\n\t\tnumPods += len(watcher.Pods)\n\t}\n\tkc.accLock.Unlock()\n\n\tobjectMap[\"services\"] = numServices\n\tobjectMap[\"endpoints\"] = numEndpoints\n\tobjectMap[\"pods\"] = numPods\n\treturn objectMap\n}", "func (s *PodStore) List() []*v1.Pod {\n\tobjects := s.Store.List()\n\tpods := make([]*v1.Pod, 0, len(objects))\n\tfor _, o := range objects {\n\t\tpods = append(pods, o.(*v1.Pod))\n\t}\n\treturn pods\n}" ]
[ "0.6969159", "0.6899663", "0.67352915", "0.6526848", "0.64330655", "0.6380531", "0.63721454", "0.6298754", "0.6271113", "0.6268417", "0.62265736", "0.62258464", "0.61918414", "0.6163917", "0.6134161", "0.6134161", "0.6105759", "0.6101063", "0.6034912", "0.59714705", "0.5960049", "0.59005594", "0.58654714", "0.58654714", "0.5852951", "0.584638", "0.584282", "0.5838525", "0.5798012", "0.5798012", "0.5791592", "0.5779509", "0.5759339", "0.574046", "0.57358694", "0.57275504", "0.57149845", "0.5665208", "0.56601804", "0.5656336", "0.56233394", "0.5619749", "0.5595791", "0.558868", "0.55629694", "0.55585414", "0.55584997", "0.5539178", "0.5534823", "0.55267787", "0.5526057", "0.55240774", "0.55189073", "0.55069774", "0.55002934", "0.5484242", "0.5465579", "0.5461128", "0.5460385", "0.5454062", "0.5449516", "0.54371136", "0.5428375", "0.54244286", "0.541524", "0.5400536", "0.5399791", "0.539051", "0.53875357", "0.5387047", "0.5383541", "0.5383541", "0.5378014", "0.5365212", "0.5362356", "0.53596914", "0.53513616", "0.53505474", "0.53500974", "0.5348889", "0.5326951", "0.5318342", "0.5311804", "0.5307333", "0.52760106", "0.52500236", "0.5244376", "0.5235815", "0.5234219", "0.5218699", "0.5218699", "0.5215092", "0.52143705", "0.52107227", "0.5207433", "0.5203835", "0.51904047", "0.5182991", "0.51804584", "0.51798654" ]
0.66986716
3
Deprecated: Use ShareType.Descriptor instead.
func (ShareType) EnumDescriptor() ([]byte, []int) { return file_share_distro_proto_rawDescGZIP(), []int{0} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*FileShare) Descriptor() ([]byte, []int) {\n\treturn file_share_share_proto_rawDescGZIP(), []int{0}\n}", "func (*ShareDistribution) Descriptor() ([]byte, []int) {\n\treturn file_share_distro_proto_rawDescGZIP(), []int{0}\n}", "func (*ShareSaveRequest) Descriptor() ([]byte, []int) {\n\treturn file_share_share_proto_rawDescGZIP(), []int{1}\n}", "func (*TargetImpressionShare) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v14_common_bidding_proto_rawDescGZIP(), []int{11}\n}", "func (*CrOSSelectShareTargetRequest) Descriptor() ([]byte, []int) {\n\treturn file_nearby_share_service_proto_rawDescGZIP(), []int{6}\n}", "func (*SharesOutstanding) Descriptor() ([]byte, []int) {\n\treturn file_openfeed_proto_rawDescGZIP(), []int{46}\n}", "func (Type) EnumDescriptor() ([]byte, []int) {\n\treturn file_github_com_getamis_alice_crypto_tss_addshare_message_proto_rawDescGZIP(), []int{0}\n}", "func (msg MsgSetShareHolder) Type() string { return \"set_shareholder\" }", "func (m *Manager) Share(ctx context.Context, md *provider.ResourceInfo, g *collaboration.ShareGrant) (*collaboration.Share, error) {\n\tif err := m.initialize(); err != nil {\n\t\treturn nil, err\n\t}\n\tuser := ctxpkg.ContextMustGetUser(ctx)\n\t// do not allow share to myself or the owner if share is for a user\n\tif g.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_USER &&\n\t\t(utils.UserEqual(g.Grantee.GetUserId(), user.Id) || utils.UserEqual(g.Grantee.GetUserId(), md.Owner)) {\n\t\treturn nil, errtypes.BadRequest(\"cs3: owner/creator and grantee are the same\")\n\t}\n\tts := utils.TSNow()\n\n\tshare := &collaboration.Share{\n\t\tId: &collaboration.ShareId{\n\t\t\tOpaqueId: uuid.NewString(),\n\t\t},\n\t\tResourceId: md.Id,\n\t\tPermissions: g.Permissions,\n\t\tGrantee: g.Grantee,\n\t\tOwner: md.Owner,\n\t\tCreator: user.Id,\n\t\tCtime: ts,\n\t\tMtime: ts,\n\t}\n\n\terr := m.persistShare(ctx, share)\n\treturn share, err\n}", "func (sm *Manager) Share(ctx context.Context, md *provider.ResourceId, g *ocm.ShareGrant, name string,\n\tpi *ocmprovider.ProviderInfo, pm string, owner *userpb.UserId, token string, st ocm.Share_ShareType) (*ocm.Share, error) {\n\n\t// Since both OCMCore and OCMShareProvider use the same package, we distinguish\n\t// between calls received from them on the basis of whether they provide info\n\t// about the remote provider on which the share is to be created.\n\t// If this info is provided, this call is on the owner's mesh provider and so\n\t// we call the CreateOCMCoreShare method on the remote provider as well,\n\t// else this is received from another provider and we only create a local share.\n\tvar isOwnersMeshProvider bool\n\tvar apiMethod string\n\tvar username string\n\tif pi != nil {\n\t\tisOwnersMeshProvider = true\n\t\tapiMethod = \"addSentShare\"\n\t\tusername = getUsername(ctx)\n\t\ttoken = randSeq(10)\n\t} else {\n\t\tapiMethod = \"addReceivedShare\"\n\t\tusername = g.Grantee.GetUserId().OpaqueId\n\t}\n\n\tvar userID *userpb.UserId\n\tif !isOwnersMeshProvider {\n\t\t// Since this call is on the remote provider, the owner of the resource is expected to be specified.\n\t\tif owner == nil {\n\t\t\treturn nil, errors.New(\"nextcloud: owner of resource not provided\")\n\t\t}\n\t\tuserID = owner\n\t} else {\n\t\tuserID = ctxpkg.ContextMustGetUser(ctx).GetId()\n\t}\n\n\t// do not allow share to myself if share is for a user\n\tif g.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_USER && utils.UserEqual(g.Grantee.GetUserId(), userID) {\n\t\treturn nil, errors.New(\"nextcloud: user and grantee are the same\")\n\t}\n\n\ts := &ocm.Share{\n\t\tName: name,\n\t\tResourceId: md,\n\t\tPermissions: g.Permissions,\n\t\tGrantee: g.Grantee,\n\t\tOwner: userID,\n\t\tCreator: userID,\n\t\tShareType: st,\n\t}\n\n\tvar encShare []byte\n\tvar err error\n\n\tif isOwnersMeshProvider {\n\t\t// adding the webdav sharedSecret in the Grantee because Share itself doesn't have an Opaque field,\n\t\t// see https://cs3org.github.io/cs3apis/#cs3.storage.provider.v1beta1.Grantee\n\t\t// and https://cs3org.github.io/cs3apis/#cs3.sharing.ocm.v1beta1.Share\n\t\ts.Grantee.Opaque = &typespb.Opaque{\n\t\t\tMap: map[string]*typespb.OpaqueEntry{\n\t\t\t\t\"sharedSecret\": {\n\t\t\t\t\tDecoder: \"plain\",\n\t\t\t\t\tValue: []byte(token),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\tencShare, err = utils.MarshalProtoV1ToJSON(s)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\t// adding the webdav sharedSecret and remote share id (called the \"ProviderID\" in OCM) in the Grantee because Share itself doesn't have an Opaque field,\n\t\t// see https://cs3org.github.io/cs3apis/#cs3.storage.provider.v1beta1.Grantee\n\t\t// and https://cs3org.github.io/cs3apis/#cs3.sharing.ocm.v1beta1.Share\n\t\ts.Grantee.Opaque = &typespb.Opaque{\n\t\t\tMap: map[string]*typespb.OpaqueEntry{\n\t\t\t\t\"sharedSecret\": {\n\t\t\t\t\tDecoder: \"plain\",\n\t\t\t\t\tValue: []byte(token),\n\t\t\t\t},\n\t\t\t\t\"remoteShareId\": {\n\t\t\t\t\tDecoder: \"plain\",\n\t\t\t\t\tValue: g.Grantee.Opaque.Map[\"remoteShareId\"].Value,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\tencShare, err = utils.MarshalProtoV1ToJSON(&ocm.ReceivedShare{\n\t\t\tShare: s,\n\t\t\tState: ocm.ShareState_SHARE_STATE_PENDING,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t_, body, err := sm.do(ctx, Action{apiMethod, string(encShare)}, username)\n\n\ts.Id = &ocm.ShareId{\n\t\tOpaqueId: string(body),\n\t}\n\tnow := time.Now().UnixNano()\n\ts.Ctime = &typespb.Timestamp{\n\t\tSeconds: uint64(now / 1000000000),\n\t\tNanos: uint32(now % 1000000000),\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif isOwnersMeshProvider {\n\t\t// token, ok := ctxpkg.ContextGetToken(ctx)\n\t\t// if !ok {\n\t\t// \treturn nil, errors.New(\"Could not get token from context\")\n\t\t// }\n\t\tvar protocol map[string]interface{}\n\t\tif st == ocm.Share_SHARE_TYPE_TRANSFER {\n\t\t\tprotocol = map[string]interface{}{\n\t\t\t\t\"name\": \"datatx\",\n\t\t\t\t\"options\": map[string]string{\n\t\t\t\t\t\"permissions\": pm,\n\t\t\t\t\t\"token\": token, // FIXME: Where is the token for datatx generated?\n\t\t\t\t},\n\t\t\t}\n\t\t} else {\n\t\t\tprotocol = map[string]interface{}{\n\t\t\t\t\"name\": \"webdav\",\n\t\t\t\t\"options\": map[string]string{\n\t\t\t\t\t\"permissions\": pm,\n\t\t\t\t\t\"sharedSecret\": token,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\trequestBodyMap := map[string]interface{}{\n\t\t\t\"shareWith\": g.Grantee.GetUserId().OpaqueId,\n\t\t\t\"name\": name,\n\t\t\t\"providerId\": s.Id.OpaqueId,\n\t\t\t\"owner\": userID.OpaqueId,\n\t\t\t\"protocol\": protocol,\n\t\t\t\"meshProvider\": userID.Idp, // FIXME: move this into the 'owner' string?\n\t\t}\n\t\terr = sender.Send(requestBodyMap, pi)\n\t\tif err != nil {\n\t\t\terr = errors.Wrap(err, \"error sending OCM POST\")\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn s, nil\n}", "func (*RegenerateShareableLinkIdRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v8_services_third_party_app_analytics_link_service_proto_rawDescGZIP(), []int{1}\n}", "func (*CreateOCMCoreShareRequest) Descriptor() ([]byte, []int) {\n\treturn file_cs3_ocm_core_v1beta1_ocm_core_api_proto_rawDescGZIP(), []int{0}\n}", "func (m ShareCommon) Type() string {\n\treturn CodeShareCommon\n}", "func (*BodyOldPeer) Descriptor() ([]byte, []int) {\n\treturn file_github_com_getamis_alice_crypto_tss_addshare_message_proto_rawDescGZIP(), []int{1}\n}", "func (*DelShareAccountRequest) Descriptor() ([]byte, []int) {\n\treturn file_box_account_proto_rawDescGZIP(), []int{4}\n}", "func (*SocialMedia) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{4}\n}", "func (*CreateOCMCoreShareResponse) Descriptor() ([]byte, []int) {\n\treturn file_cs3_ocm_core_v1beta1_ocm_core_api_proto_rawDescGZIP(), []int{1}\n}", "func (*RegenerateShareableLinkIdResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v8_services_third_party_app_analytics_link_service_proto_rawDescGZIP(), []int{2}\n}", "func isShareable(mode string) bool {\n\treturn mode == \"shareable\"\n}", "func (*ListShareAccountResponse) Descriptor() ([]byte, []int) {\n\treturn file_box_account_proto_rawDescGZIP(), []int{7}\n}", "func (msg MsgDeleteShareHolder) Type() string { return \"delete_shareholder\" }", "func (*DelShareAccountResponse) Descriptor() ([]byte, []int) {\n\treturn file_box_account_proto_rawDescGZIP(), []int{5}\n}", "func PublicShare2ShareData(share *link.PublicShare, r *http.Request, publicURL string) *ShareData {\n\tsd := &ShareData{\n\t\t// share.permissions are mapped below\n\t\t// Displaynames are added later\n\t\tShareType: ShareTypePublicLink,\n\t\tToken: share.Token,\n\t\tName: share.DisplayName,\n\t\tMailSend: 0,\n\t\tURL: publicURL + path.Join(\"/\", \"s/\"+share.Token),\n\t\tUIDOwner: LocalUserIDToString(share.Creator),\n\t\tUIDFileOwner: LocalUserIDToString(share.Owner),\n\t\tQuicklink: share.Quicklink,\n\t}\n\tif share.Id != nil {\n\t\tsd.ID = share.Id.OpaqueId\n\t}\n\n\tif s := share.GetPermissions().GetPermissions(); s != nil {\n\t\tsd.Permissions = RoleFromResourcePermissions(share.GetPermissions().GetPermissions(), true).OCSPermissions()\n\t}\n\n\tif share.Expiration != nil {\n\t\tsd.Expiration = timestampToExpiration(share.Expiration)\n\t}\n\tif share.Ctime != nil {\n\t\tsd.STime = share.Ctime.Seconds // TODO CS3 api birth time = btime\n\t}\n\n\t// hide password\n\tif share.PasswordProtected {\n\t\tsd.ShareWith = \"***redacted***\"\n\t\tsd.ShareWithDisplayname = \"***redacted***\"\n\t}\n\n\treturn sd\n}", "func (*Message) Descriptor() ([]byte, []int) {\n\treturn file_github_com_getamis_alice_crypto_tss_addshare_message_proto_rawDescGZIP(), []int{0}\n}", "func (*ShortSocial) Descriptor() ([]byte, []int) {\n\treturn file_parser_company_proto_rawDescGZIP(), []int{33}\n}", "func (*DisconnectRequest) Descriptor() ([]byte, []int) {\n\treturn file_authorization_proto_rawDescGZIP(), []int{1}\n}", "func (*Link) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{2}\n}", "func (*Disconnect) Descriptor() ([]byte, []int) {\n\treturn file_uni_proto_rawDescGZIP(), []int{11}\n}", "func (*DataPermission) Descriptor() ([]byte, []int) {\n\treturn file_api_sso_api_proto_rawDescGZIP(), []int{1}\n}", "func (*Attribution) Descriptor() ([]byte, []int) {\n\treturn file_ml_metadata_proto_metadata_store_proto_rawDescGZIP(), []int{9}\n}", "func (*CMsgSocialFeedRequest) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{304}\n}", "func IsShare(share int) bool {\n\treturn share == int(ShareInGame) || share == int(SharePrivate)\n}", "func (instance *Host) GetShare(ctx context.Context, shareRef string) (_ *propertiesv1.HostShare, ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif valid.IsNil(instance) {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\n\t// instance.RLock()\n\t// defer instance.RUnlock()\n\n\tvar (\n\t\thostShare *propertiesv1.HostShare\n\t\t// ok bool\n\t)\n\terr := instance.Inspect(ctx, func(_ data.Clonable, props *serialize.JSONProperties) fail.Error {\n\t\treturn props.Inspect(\n\t\t\thostproperty.SharesV1, func(clonable data.Clonable) fail.Error {\n\t\t\t\tsharesV1, ok := clonable.(*propertiesv1.HostShares)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fail.InconsistentError(\n\t\t\t\t\t\t\"'*propertiesv1.HostShares' expected, '%s' provided\", reflect.TypeOf(clonable).String(),\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tif item, ok := sharesV1.ByID[shareRef]; ok {\n\t\t\t\t\tcloned, cerr := item.Clone()\n\t\t\t\t\tif cerr != nil {\n\t\t\t\t\t\treturn fail.Wrap(cerr)\n\t\t\t\t\t}\n\t\t\t\t\thostShare, ok = cloned.(*propertiesv1.HostShare)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn fail.InconsistentError(\"item should be a *propertiesv1.HostShare\")\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tif item, ok := sharesV1.ByName[shareRef]; ok {\n\t\t\t\t\tcloned, cerr := sharesV1.ByID[item].Clone()\n\t\t\t\t\tif cerr != nil {\n\t\t\t\t\t\treturn fail.Wrap(cerr)\n\t\t\t\t\t}\n\t\t\t\t\thostShare, ok = cloned.(*propertiesv1.HostShare)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn fail.InconsistentError(\"hostShare should be a *propertiesv1.HostShare\")\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn fail.NotFoundError(\n\t\t\t\t\t\"share '%s' not found in server '%s' metadata\", shareRef, instance.GetName(),\n\t\t\t\t)\n\t\t\t},\n\t\t)\n\t})\n\terr = debug.InjectPlannedFail(err)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn hostShare, nil\n}", "func (*QuitShareAccountRequest) Descriptor() ([]byte, []int) {\n\treturn file_box_account_proto_rawDescGZIP(), []int{8}\n}", "func (*BodyNewBk) Descriptor() ([]byte, []int) {\n\treturn file_github_com_getamis_alice_crypto_tss_addshare_message_proto_rawDescGZIP(), []int{2}\n}", "func (*Permission) Descriptor() ([]byte, []int) {\n\treturn file_ocis_messages_settings_v0_settings_proto_rawDescGZIP(), []int{12}\n}", "func (*MoveSecurityGroupMetadata) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_security_group_service_proto_rawDescGZIP(), []int{16}\n}", "func (c FieldsCollection) Share() *models.Field {\n\treturn c.MustGet(\"Share\")\n}", "func (*Social) Descriptor() ([]byte, []int) {\n\treturn file_parser_company_proto_rawDescGZIP(), []int{32}\n}", "func (*SharedInterestsRequests) Descriptor() ([]byte, []int) {\n\treturn file_api_protobuf_spec_connection_resource_v1_proto_rawDescGZIP(), []int{13}\n}", "func (*LinkFacebookRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{54}\n}", "func (*LinkSteamRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{55}\n}", "func (*UrlType) Descriptor() ([]byte, []int) {\n\treturn file_ur_proto_rawDescGZIP(), []int{0}\n}", "func (SubjectAlternativeNameType) EnumDescriptor() ([]byte, []int) {\n\treturn file_sigstore_common_proto_rawDescGZIP(), []int{2}\n}", "func (*ProviderID) Descriptor() ([]byte, []int) {\n\treturn file_synerex_proto_rawDescGZIP(), []int{13}\n}", "func (*OldUrl) Descriptor() ([]byte, []int) {\n\treturn file_cutter_proto_rawDescGZIP(), []int{0}\n}", "func ShareUpdated(r *collaboration.UpdateShareResponse, req *collaboration.UpdateShareRequest, executant *user.UserId) events.ShareUpdated {\n\tupdated := \"\"\n\tif req.Field.GetPermissions() != nil {\n\t\tupdated = \"permissions\"\n\t} else if req.Field.GetDisplayName() != \"\" {\n\t\tupdated = \"displayname\"\n\t}\n\treturn events.ShareUpdated{\n\t\tExecutant: executant,\n\t\tShareID: r.Share.Id,\n\t\tItemID: r.Share.ResourceId,\n\t\tPermissions: r.Share.Permissions,\n\t\tGranteeUserID: r.Share.GetGrantee().GetUserId(),\n\t\tGranteeGroupID: r.Share.GetGrantee().GetGroupId(),\n\t\tSharer: r.Share.Creator,\n\t\tMTime: r.Share.Mtime,\n\t\tUpdated: updated,\n\t}\n}", "func (EBroadcastChatPermission) EnumDescriptor() ([]byte, []int) {\n\treturn file_steammessages_broadcast_steamclient_proto_rawDescGZIP(), []int{1}\n}", "func (*UpdateNetworkRequest_DelegatedNetID) Descriptor() ([]byte, []int) {\n\treturn file_packetbroker_api_iam_v1_service_proto_rawDescGZIP(), []int{8, 0}\n}", "func (*Staking_TransferOwnership) Descriptor() ([]byte, []int) {\n\treturn file_IoTeX_proto_rawDescGZIP(), []int{1, 5}\n}", "func NewShare(v interface{}) Elem {\n\treturn driver.NewShare(v)\n}", "func (*TrustedDelegation) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_swarming_proto_config_pools_proto_rawDescGZIP(), []int{3}\n}", "func (*SymLinkRequest) Descriptor() ([]byte, []int) {\n\treturn file_IOService_proto_rawDescGZIP(), []int{42}\n}", "func (*AuthorizationID2) Descriptor() ([]byte, []int) {\n\treturn file_sa_proto_rawDescGZIP(), []int{32}\n}", "func (StorageType) EnumDescriptor() ([]byte, []int) {\n\treturn file_task_proto_rawDescGZIP(), []int{2}\n}", "func (PermissionType) EnumDescriptor() ([]byte, []int) {\n\treturn file_pkg_common_permissions_proto_rawDescGZIP(), []int{1}\n}", "func (Span_Link_Type) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 3, 0}\n}", "func ShareFromString(share string) (Share, bool) {\n\tswitch share {\n\tcase \"inGame\":\n\t\treturn ShareInGame, true\n\tcase \"private\":\n\t\treturn SharePrivate, true\n\tdefault:\n\t\treturn ShareInGame, false\n\t}\n}", "func (*Uri) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{15}\n}", "func (*UpdateSecurityGroupMetadata) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_security_group_service_proto_rawDescGZIP(), []int{7}\n}", "func (*StorageAccess) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_dataplex_v1_metadata_proto_rawDescGZIP(), []int{15}\n}", "func (*Snippet_Segment) Descriptor() ([]byte, []int) {\n\treturn file_metadata_metadata_proto_rawDescGZIP(), []int{1, 0}\n}", "func (SubscriberQuotaUpdate_Type) EnumDescriptor() ([]byte, []int) {\n\treturn file_pipelined_proto_rawDescGZIP(), []int{14, 0}\n}", "func (*Permission) Descriptor() ([]byte, []int) {\n\treturn file_proto_fandncloud_service_user_user_proto_rawDescGZIP(), []int{6}\n}", "func (*Access) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_clickhouse_v1_cluster_proto_rawDescGZIP(), []int{9}\n}", "func (*LinksRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_bucketsd_pb_bucketsd_proto_rawDescGZIP(), []int{8}\n}", "func (Snippet_Segment_SegmentType) EnumDescriptor() ([]byte, []int) {\n\treturn file_metadata_metadata_proto_rawDescGZIP(), []int{1, 0, 0}\n}", "func VRFShareProvider() datastore.Entity {\n\tvrfs := &VRFShare{}\n\treturn vrfs\n}", "func (*AuthorizationIDs) Descriptor() ([]byte, []int) {\n\treturn file_sa_proto_rawDescGZIP(), []int{31}\n}", "func (IdpProviderType) EnumDescriptor() ([]byte, []int) {\n\treturn file_management_proto_rawDescGZIP(), []int{38}\n}", "func (*CNETMsg_Disconnect) Descriptor() ([]byte, []int) {\n\treturn file_artifact_networkbasetypes_proto_rawDescGZIP(), []int{7}\n}", "func (*DeleteSecurityGroupMetadata) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_vpc_v1_security_group_service_proto_rawDescGZIP(), []int{12}\n}", "func (*TopicWise) Descriptor() ([]byte, []int) {\n\treturn file_service_proto_rawDescGZIP(), []int{4}\n}", "func (MarketSummary_SummaryType) EnumDescriptor() ([]byte, []int) {\n\treturn file_openfeed_proto_rawDescGZIP(), []int{48, 1}\n}", "func (*Secret) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_datatransfer_v1_endpoint_common_proto_rawDescGZIP(), []int{1}\n}", "func (*SharedInterestsResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_protobuf_spec_connection_resource_v1_proto_rawDescGZIP(), []int{12}\n}", "func (*BodyCompute) Descriptor() ([]byte, []int) {\n\treturn file_github_com_getamis_alice_crypto_tss_addshare_message_proto_rawDescGZIP(), []int{3}\n}", "func (*Link) Descriptor() ([]byte, []int) {\n\treturn file_pkg_webview_view_proto_rawDescGZIP(), []int{4}\n}", "func (*SystemTypeExtension) Descriptor() ([]byte, []int) {\n\treturn file_ml_metadata_proto_metadata_store_proto_rawDescGZIP(), []int{0}\n}", "func (*Audience) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_retail_v2_common_proto_rawDescGZIP(), []int{0}\n}", "func (*OrgIamPolicy) Descriptor() ([]byte, []int) {\n\treturn file_management_proto_rawDescGZIP(), []int{47}\n}", "func (m *AndroidWorkProfileGeneralDeviceConfiguration) SetWorkProfileDataSharingType(value *AndroidWorkProfileCrossProfileDataSharingType)() {\n m.workProfileDataSharingType = value\n}", "func (*HoverRegistrationOptions) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{110}\n}", "func (*PushPathAccessRolesRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_bucketsd_pb_bucketsd_proto_rawDescGZIP(), []int{31}\n}", "func (*TypeInformation) Descriptor() ([]byte, []int) {\n\treturn file_authzed_api_v0_namespace_proto_rawDescGZIP(), []int{3}\n}", "func (*PAgentUriStat) Descriptor() ([]byte, []int) {\n\treturn file_v1_Stat_proto_rawDescGZIP(), []int{22}\n}", "func (*AuthorizationID) Descriptor() ([]byte, []int) {\n\treturn file_sa_proto_rawDescGZIP(), []int{2}\n}", "func (*Connect) Descriptor() ([]byte, []int) {\n\treturn file_service_proto_rawDescGZIP(), []int{2}\n}", "func (*Permission) Descriptor() ([]byte, []int) {\n\treturn file_protodef_user_user_proto_rawDescGZIP(), []int{18}\n}", "func (*SetUrlRsp) Descriptor() ([]byte, []int) {\n\treturn file_short_url_proto_rawDescGZIP(), []int{1}\n}", "func (*Common_UserLink) Descriptor() ([]byte, []int) {\n\treturn file_proto_common_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*DirectUrlSettings) Descriptor() ([]byte, []int) {\n\treturn file_directurls_proto_rawDescGZIP(), []int{0}\n}", "func (*IamPolicyAnalysisQuery_AccessSelector) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_asset_v1_asset_service_proto_rawDescGZIP(), []int{26, 2}\n}", "func (*SMPrivateChat) Descriptor() ([]byte, []int) {\n\treturn file_chat_proto_rawDescGZIP(), []int{11}\n}", "func (*SocialFollowers) Descriptor() ([]byte, []int) {\n\treturn file_person_person_proto_rawDescGZIP(), []int{0}\n}", "func (Host_Type) EnumDescriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_clickhouse_v1_cluster_proto_rawDescGZIP(), []int{6, 0}\n}", "func (*JoinToken) Descriptor() ([]byte, []int) {\n\treturn file_spire_server_datastore_datastore_proto_rawDescGZIP(), []int{54}\n}", "func (*Feed) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_asset_v1_asset_service_proto_rawDescGZIP(), []int{21}\n}", "func (*Friend) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{37}\n}", "func (gb *CurrentGrantBuilder) Share(n string) GrantExecutable {\n\treturn &CurrentGrantExecutable{\n\t\tgrantName: gb.qualifiedName,\n\t\tgrantType: gb.grantType,\n\t\tgranteeName: n,\n\t\tgranteeType: shareType,\n\t}\n}" ]
[ "0.6478613", "0.64235455", "0.62816375", "0.6172562", "0.6044849", "0.60314584", "0.59462136", "0.5939892", "0.5929568", "0.5887795", "0.588171", "0.58685476", "0.58246434", "0.58026844", "0.57739806", "0.5765248", "0.5746607", "0.57274985", "0.57250035", "0.56246614", "0.5624403", "0.5598285", "0.559512", "0.55333614", "0.54635596", "0.54618096", "0.54538566", "0.5450871", "0.54461396", "0.5434864", "0.53651565", "0.53592557", "0.5338068", "0.5324694", "0.53204983", "0.53074133", "0.53066385", "0.5304913", "0.5292759", "0.5269076", "0.5268612", "0.52653813", "0.5251432", "0.5248014", "0.5248004", "0.5244779", "0.52320343", "0.52276295", "0.52241826", "0.52191955", "0.5217793", "0.5215416", "0.52056825", "0.52014405", "0.51970434", "0.5196279", "0.5194037", "0.51884454", "0.5187779", "0.5185685", "0.5182161", "0.51800966", "0.5178943", "0.517593", "0.5172478", "0.517044", "0.51673234", "0.51668614", "0.51667166", "0.51658016", "0.5160974", "0.515523", "0.5152793", "0.5144995", "0.51439434", "0.51421976", "0.51402885", "0.5139941", "0.51354057", "0.5131639", "0.5128259", "0.512384", "0.5121584", "0.5117417", "0.5115612", "0.5115256", "0.5111947", "0.5108349", "0.51073706", "0.51070154", "0.51063097", "0.5105959", "0.510552", "0.5104585", "0.51035184", "0.5102486", "0.51022065", "0.5101137", "0.50979686", "0.5095724" ]
0.6611507
0
Deprecated: Use ShareDistribution.ProtoReflect.Descriptor instead.
func (*ShareDistribution) Descriptor() ([]byte, []int) { return file_share_distro_proto_rawDescGZIP(), []int{0} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*BodyOldPeer) Descriptor() ([]byte, []int) {\n\treturn file_github_com_getamis_alice_crypto_tss_addshare_message_proto_rawDescGZIP(), []int{1}\n}", "func (*ResourceManifest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_gkehub_v1_membership_proto_rawDescGZIP(), []int{4}\n}", "func (*PatchCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{161}\n}", "func (*DistributionChange) Descriptor() ([]byte, []int) {\n\treturn edgelq_applications_proto_v1alpha2_distribution_change_proto_rawDescGZIP(), []int{0}\n}", "func (*Deprecation) Descriptor() ([]byte, []int) {\n\treturn file_external_cfgmgmt_response_nodes_proto_rawDescGZIP(), []int{8}\n}", "func (*GetDelegationTokenResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{4}\n}", "func (*GetDelegationTokenRequestProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{3}\n}", "func (*AddPeerRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{8}\n}", "func (*NetProtoTalker) Descriptor() ([]byte, []int) {\n\treturn file_pkg_smgrpc_smgrpc_proto_rawDescGZIP(), []int{1}\n}", "func (*DistributionChange_Removed) Descriptor() ([]byte, []int) {\n\treturn edgelq_applications_proto_v1alpha2_distribution_change_proto_rawDescGZIP(), []int{0, 3}\n}", "func (*CredentialsProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{2}\n}", "func (*CMsgSocialFeedRequest) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{304}\n}", "func (*Dist) Descriptor() ([]byte, []int) {\n\treturn file_github_com_google_cloudprober_metrics_proto_dist_proto_rawDescGZIP(), []int{0}\n}", "func (*CancelDelegationTokenResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{8}\n}", "func (*DistributionChange_Added) Descriptor() ([]byte, []int) {\n\treturn edgelq_applications_proto_v1alpha2_distribution_change_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*DeleteCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{162}\n}", "func (*Embed) Descriptor() ([]byte, []int) {\n\treturn file_chat_v1_messages_proto_rawDescGZIP(), []int{2}\n}", "func (*Disconnect) Descriptor() ([]byte, []int) {\n\treturn file_uni_proto_rawDescGZIP(), []int{11}\n}", "func (*RenewDelegationTokenResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{6}\n}", "func (*Message) Descriptor() ([]byte, []int) {\n\treturn file_github_com_getamis_alice_crypto_tss_addshare_message_proto_rawDescGZIP(), []int{0}\n}", "func (*TokenProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{0}\n}", "func (*TargetImpressionShare) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v14_common_bidding_proto_rawDescGZIP(), []int{11}\n}", "func (*Link) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{2}\n}", "func (*CancelDelegationTokenRequestProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{7}\n}", "func (*SignedExportMessage) Descriptor() ([]byte, []int) {\n\treturn file_fpc_key_dist_proto_rawDescGZIP(), []int{3}\n}", "func (*Message12796) Descriptor() ([]byte, []int) {\n\treturn file_datasets_google_message4_benchmark_message4_2_proto_rawDescGZIP(), []int{1}\n}", "func (*RenewDelegationTokenRequestProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{5}\n}", "func (*DisconnectRequest) Descriptor() ([]byte, []int) {\n\treturn file_authorization_proto_rawDescGZIP(), []int{1}\n}", "func (*Membership) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_gkehub_v1_membership_proto_rawDescGZIP(), []int{0}\n}", "func (*Listen) Descriptor() ([]byte, []int) {\n\treturn file_pkg_smgrpc_smgrpc_proto_rawDescGZIP(), []int{4}\n}", "func (*NetRateTalker) Descriptor() ([]byte, []int) {\n\treturn file_pkg_smgrpc_smgrpc_proto_rawDescGZIP(), []int{2}\n}", "func (*TraceProto) Descriptor() ([]byte, []int) {\n\treturn file_internal_tracing_extended_extended_trace_proto_rawDescGZIP(), []int{0}\n}", "func (*DistributionChange_Modified) Descriptor() ([]byte, []int) {\n\treturn edgelq_applications_proto_v1alpha2_distribution_change_proto_rawDescGZIP(), []int{0, 1}\n}", "func (*DirectiveUndelegate) Descriptor() ([]byte, []int) {\n\treturn file_Harmony_proto_rawDescGZIP(), []int{10}\n}", "func (*SocialMedia) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{4}\n}", "func (*PublishDiagnosticsRequest) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{100}\n}", "func (*FeedbackMetrics) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{12}\n}", "func (*Attribution) Descriptor() ([]byte, []int) {\n\treturn file_ml_metadata_proto_metadata_store_proto_rawDescGZIP(), []int{9}\n}", "func (*AnalysisMessageWeakSchema_ArgType) Descriptor() ([]byte, []int) {\n\treturn file_analysis_v1alpha1_message_proto_rawDescGZIP(), []int{1, 0}\n}", "func (*UpdateNetworkRequest_DelegatedNetID) Descriptor() ([]byte, []int) {\n\treturn file_packetbroker_api_iam_v1_service_proto_rawDescGZIP(), []int{8, 0}\n}", "func (*TrustedDelegation) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_swarming_proto_config_pools_proto_rawDescGZIP(), []int{3}\n}", "func (*RelationTupleDelta) Descriptor() ([]byte, []int) {\n\treturn file_ory_keto_acl_v1alpha1_write_service_proto_rawDescGZIP(), []int{1}\n}", "func (*RegenerateShareableLinkIdRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v8_services_third_party_app_analytics_link_service_proto_rawDescGZIP(), []int{1}\n}", "func ProtoFromDescriptor(d protoreflect.Descriptor) proto.Message {\n\tswitch d := d.(type) {\n\tcase protoreflect.FileDescriptor:\n\t\treturn ProtoFromFileDescriptor(d)\n\tcase protoreflect.MessageDescriptor:\n\t\treturn ProtoFromMessageDescriptor(d)\n\tcase protoreflect.FieldDescriptor:\n\t\treturn ProtoFromFieldDescriptor(d)\n\tcase protoreflect.OneofDescriptor:\n\t\treturn ProtoFromOneofDescriptor(d)\n\tcase protoreflect.EnumDescriptor:\n\t\treturn ProtoFromEnumDescriptor(d)\n\tcase protoreflect.EnumValueDescriptor:\n\t\treturn ProtoFromEnumValueDescriptor(d)\n\tcase protoreflect.ServiceDescriptor:\n\t\treturn ProtoFromServiceDescriptor(d)\n\tcase protoreflect.MethodDescriptor:\n\t\treturn ProtoFromMethodDescriptor(d)\n\tdefault:\n\t\t// WTF??\n\t\tif res, ok := d.(DescriptorProtoWrapper); ok {\n\t\t\treturn res.AsProto()\n\t\t}\n\t\treturn nil\n\t}\n}", "func (*DataPermission) Descriptor() ([]byte, []int) {\n\treturn file_api_sso_api_proto_rawDescGZIP(), []int{1}\n}", "func (*Description) Descriptor() ([]byte, []int) {\n\treturn file_Harmony_proto_rawDescGZIP(), []int{4}\n}", "func (*Instance) Descriptor() ([]byte, []int) {\n\treturn file_cloudprovider_externalgrpc_protos_externalgrpc_proto_rawDescGZIP(), []int{28}\n}", "func (*SMPrivateChat) Descriptor() ([]byte, []int) {\n\treturn file_chat_proto_rawDescGZIP(), []int{11}\n}", "func (*PrivateVisibility) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_dns_v1_dns_zone_proto_rawDescGZIP(), []int{2}\n}", "func (*CredentialAttribute) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{9}\n}", "func (*AnalysisMessageWeakSchema) Descriptor() ([]byte, []int) {\n\treturn file_analysis_v1alpha1_message_proto_rawDescGZIP(), []int{1}\n}", "func (*DelShareAccountRequest) Descriptor() ([]byte, []int) {\n\treturn file_box_account_proto_rawDescGZIP(), []int{4}\n}", "func (*CredentialsKVProto) Descriptor() ([]byte, []int) {\n\treturn file_Security_proto_rawDescGZIP(), []int{1}\n}", "func (*AddPeerResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{30}\n}", "func (*DetachMetadataRequest) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_cipd_api_cipd_v1_repo_proto_rawDescGZIP(), []int{22}\n}", "func (*Span_Link) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 3}\n}", "func (x *fastReflection_SendEnabled) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_SendEnabled\n}", "func (*StandardProtocols) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{54}\n}", "func (*RefreshServiceAclRequestProto) Descriptor() ([]byte, []int) {\n\treturn file_RefreshAuthorizationPolicyProtocol_proto_rawDescGZIP(), []int{0}\n}", "func (*Permission) Descriptor() ([]byte, []int) {\n\treturn file_ocis_messages_settings_v0_settings_proto_rawDescGZIP(), []int{12}\n}", "func (*MaximizeConversions) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v14_common_bidding_proto_rawDescGZIP(), []int{6}\n}", "func (*Message6024) Descriptor() ([]byte, []int) {\n\treturn file_datasets_google_message4_benchmark_message4_2_proto_rawDescGZIP(), []int{26}\n}", "func (*ExportMessage) Descriptor() ([]byte, []int) {\n\treturn file_fpc_key_dist_proto_rawDescGZIP(), []int{2}\n}", "func (*UseChannel) Descriptor() ([]byte, []int) {\n\treturn file_chatMsg_msg_proto_rawDescGZIP(), []int{7}\n}", "func (*SignatureInfo) Descriptor() ([]byte, []int) {\n\treturn file_proto_covidshieldv1_proto_rawDescGZIP(), []int{6}\n}", "func (*SubscriberQuotaUpdate) Descriptor() ([]byte, []int) {\n\treturn file_pipelined_proto_rawDescGZIP(), []int{14}\n}", "func (*OnTargetAudienceMetrics) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{19}\n}", "func (*Domain) Descriptor() ([]byte, []int) {\n\treturn file_management_proto_rawDescGZIP(), []int{51}\n}", "func (*Domain) Descriptor() ([]byte, []int) {\n\treturn file_management_proto_rawDescGZIP(), []int{51}\n}", "func (*EvictWritersResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{11}\n}", "func (*UpdatePermissionRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_role_pb_request_proto_rawDescGZIP(), []int{9}\n}", "func (*Modifier) Descriptor() ([]byte, []int) {\n\treturn file_FillerGame_proto_rawDescGZIP(), []int{6}\n}", "func (*PermissionRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_casbin_proto_rawDescGZIP(), []int{13}\n}", "func (*Trickle) Descriptor() ([]byte, []int) {\n\treturn file_cmd_server_grpc_proto_sfu_proto_rawDescGZIP(), []int{4}\n}", "func (*CMPrivateChat) Descriptor() ([]byte, []int) {\n\treturn file_chat_proto_rawDescGZIP(), []int{10}\n}", "func (*Peer) Descriptor() ([]byte, []int) {\n\treturn file_service_proto_rawDescGZIP(), []int{4}\n}", "func (*Decl) Descriptor() ([]byte, []int) {\n\treturn file_google_api_expr_v1alpha1_checked_proto_rawDescGZIP(), []int{2}\n}", "func (*DistributionChange_Current) Descriptor() ([]byte, []int) {\n\treturn edgelq_applications_proto_v1alpha2_distribution_change_proto_rawDescGZIP(), []int{0, 2}\n}", "func (*Module) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{3}\n}", "func (*PrivateApiCF) Descriptor() ([]byte, []int) {\n\treturn file_pkg_kascfg_kascfg_proto_rawDescGZIP(), []int{24}\n}", "func (*Friend) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{37}\n}", "func (Type) EnumDescriptor() ([]byte, []int) {\n\treturn file_github_com_getamis_alice_crypto_tss_addshare_message_proto_rawDescGZIP(), []int{0}\n}", "func (*Permission) Descriptor() ([]byte, []int) {\n\treturn file_protodef_user_user_proto_rawDescGZIP(), []int{18}\n}", "func (*TopicWise) Descriptor() ([]byte, []int) {\n\treturn file_service_proto_rawDescGZIP(), []int{4}\n}", "func (*CMsgRefreshPartnerAccountLink) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{65}\n}", "func (*StaleReadRequestTypeProto) Descriptor() ([]byte, []int) {\n\treturn file_raft_proto_rawDescGZIP(), []int{24}\n}", "func (*DescribePermissionRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_role_pb_request_proto_rawDescGZIP(), []int{6}\n}", "func (*GenerateProductMixIdeasRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{7}\n}", "func (*DecreaseAllowance) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{6}\n}", "func (*Permission) Descriptor() ([]byte, []int) {\n\treturn file_proto_fandncloud_service_user_user_proto_rawDescGZIP(), []int{6}\n}", "func (*DirectiveDelegate) Descriptor() ([]byte, []int) {\n\treturn file_Harmony_proto_rawDescGZIP(), []int{9}\n}", "func (x *fastReflection_LightClientAttackEvidence) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_LightClientAttackEvidence\n}", "func (*Embed_EmbedField) Descriptor() ([]byte, []int) {\n\treturn file_chat_v1_messages_proto_rawDescGZIP(), []int{2, 1}\n}", "func (*Ref) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_cipd_api_cipd_v1_repo_proto_rawDescGZIP(), []int{13}\n}", "func (*KubernetesResource) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_gkehub_v1_membership_proto_rawDescGZIP(), []int{2}\n}", "func (*WithWellKnownTypes) Descriptor() ([]byte, []int) {\n\treturn file_testing_proto_rawDescGZIP(), []int{1}\n}", "func (*CMsgConsumableUsage) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{46}\n}", "func (x *fastReflection_MsgFundCommunityPool) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgFundCommunityPool\n}", "func (*ResourceOptions) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_gkehub_v1_membership_proto_rawDescGZIP(), []int{3}\n}", "func (*FileShare) Descriptor() ([]byte, []int) {\n\treturn file_share_share_proto_rawDescGZIP(), []int{0}\n}" ]
[ "0.67036504", "0.6569697", "0.6526817", "0.65024304", "0.6499678", "0.6484286", "0.64665836", "0.64648074", "0.6448334", "0.6447736", "0.64468926", "0.6445642", "0.64218575", "0.6412172", "0.64099705", "0.6405386", "0.6403372", "0.638953", "0.6384298", "0.63774955", "0.6370877", "0.63644266", "0.63533866", "0.6348682", "0.63437474", "0.633692", "0.6328666", "0.6314358", "0.6311303", "0.6311153", "0.62936455", "0.629114", "0.62911123", "0.62841123", "0.62835807", "0.6283561", "0.627785", "0.62767184", "0.6272553", "0.6271881", "0.6271394", "0.6270416", "0.62676847", "0.62623125", "0.62580687", "0.6257591", "0.62565875", "0.6255703", "0.62546015", "0.62528235", "0.62516856", "0.6250829", "0.62499714", "0.6244857", "0.6241852", "0.6239081", "0.62375796", "0.6235631", "0.62344337", "0.62339", "0.6231461", "0.62313896", "0.6230959", "0.6229175", "0.62281287", "0.62279755", "0.6225477", "0.622063", "0.622063", "0.6219817", "0.6218984", "0.6217609", "0.6217014", "0.62152636", "0.62146795", "0.6213453", "0.62098557", "0.62093854", "0.6207308", "0.62069726", "0.6205894", "0.6205757", "0.6204686", "0.62006724", "0.61998343", "0.6192182", "0.6188837", "0.61868227", "0.61862826", "0.61861336", "0.6185336", "0.6180862", "0.61784655", "0.6175735", "0.6175365", "0.6173916", "0.61731815", "0.6172953", "0.6171881", "0.6171406" ]
0.66709244
1
NewCredentialRepository instance of CredentialRepository
func NewCredentialRepository(db *pgxpool.Pool) CredentialRepository { return &repo{ DB: db, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(c *config.Config) (*Repository, error) {\n\tDBURL := fmt.Sprintf(\"host=%s port=%d user=%s dbname=%s sslmode=disable password=%s\",\n\t\tc.Database.DBHost,\n\t\tc.Database.DBPort,\n\t\tc.Database.DBUser,\n\t\tc.Database.DBName,\n\t\tc.Database.DBPassword)\n\n\tdb, err := gorm.Open(dbDriver, DBURL)\n\tif err != nil {\n\t\tfmt.Printf(\"Unable to connect to database, %v\", err)\n\t\tdefer db.Close()\n\t\treturn nil, err\n\t}\n\n\tdb.LogMode(true)\n\n\tuserRepository := UserRepository{db}\n\n\tr := &Repository{db: db, UserRepository: &userRepository}\n\treturn r, nil\n}", "func New() backing.Repo {\n\treturn &Repo{}\n}", "func NewAuthRepo() IAuthRepository {\n\tdb := Connect()\n\treturn AuthRepository{db}\n}", "func NewCredentialCommand(io ui.IO, clientFactory ClientFactory, credentialStore CredentialConfig) *CredentialCommand {\n\treturn &CredentialCommand{\n\t\tio: io,\n\t\tclientFactory: clientFactory,\n\t\tcredentialStore: credentialStore,\n\t}\n}", "func NewCredential(config *Config) (credential Credential, err error) {\n\tif config == nil {\n\t\tconfig, err = defaultChain.resolve()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\treturn NewCredential(config)\n\t}\n\tswitch tea.StringValue(config.Type) {\n\tcase \"access_key\":\n\t\terr = checkAccessKey(config)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tcredential = newAccessKeyCredential(tea.StringValue(config.AccessKeyId), tea.StringValue(config.AccessKeySecret))\n\tcase \"sts\":\n\t\terr = checkSTS(config)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tcredential = newStsTokenCredential(tea.StringValue(config.AccessKeyId), tea.StringValue(config.AccessKeySecret), tea.StringValue(config.SecurityToken))\n\tcase \"ecs_ram_role\":\n\t\tcheckEcsRAMRole(config)\n\t\truntime := &utils.Runtime{\n\t\t\tHost: tea.StringValue(config.Host),\n\t\t\tProxy: tea.StringValue(config.Proxy),\n\t\t\tReadTimeout: tea.IntValue(config.Timeout),\n\t\t\tConnectTimeout: tea.IntValue(config.ConnectTimeout),\n\t\t}\n\t\tcredential = newEcsRAMRoleCredential(tea.StringValue(config.RoleName), runtime)\n\tcase \"ram_role_arn\":\n\t\terr = checkRAMRoleArn(config)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\truntime := &utils.Runtime{\n\t\t\tHost: tea.StringValue(config.Host),\n\t\t\tProxy: tea.StringValue(config.Proxy),\n\t\t\tReadTimeout: tea.IntValue(config.Timeout),\n\t\t\tConnectTimeout: tea.IntValue(config.ConnectTimeout),\n\t\t}\n\t\tcredential = newRAMRoleArnCredential(tea.StringValue(config.AccessKeyId), tea.StringValue(config.AccessKeySecret), tea.StringValue(config.RoleArn), tea.StringValue(config.RoleSessionName), tea.StringValue(config.Policy), tea.IntValue(config.RoleSessionExpiration), runtime)\n\tcase \"rsa_key_pair\":\n\t\terr = checkRSAKeyPair(config)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tfile, err1 := os.Open(tea.StringValue(config.PrivateKeyFile))\n\t\tif err1 != nil {\n\t\t\terr = fmt.Errorf(\"InvalidPath: Can not open PrivateKeyFile, err is %s\", err1.Error())\n\t\t\treturn\n\t\t}\n\t\tdefer file.Close()\n\t\tvar privateKey string\n\t\tscan := bufio.NewScanner(file)\n\t\tfor scan.Scan() {\n\t\t\tif strings.HasPrefix(scan.Text(), \"----\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tprivateKey += scan.Text() + \"\\n\"\n\t\t}\n\t\truntime := &utils.Runtime{\n\t\t\tHost: tea.StringValue(config.Host),\n\t\t\tProxy: tea.StringValue(config.Proxy),\n\t\t\tReadTimeout: tea.IntValue(config.Timeout),\n\t\t\tConnectTimeout: tea.IntValue(config.ConnectTimeout),\n\t\t}\n\t\tcredential = newRsaKeyPairCredential(privateKey, tea.StringValue(config.PublicKeyId), tea.IntValue(config.SessionExpiration), runtime)\n\tcase \"bearer\":\n\t\tif tea.StringValue(config.BearerToken) == \"\" {\n\t\t\terr = errors.New(\"BearerToken cannot be empty\")\n\t\t\treturn\n\t\t}\n\t\tcredential = newBearerTokenCredential(tea.StringValue(config.BearerToken))\n\tdefault:\n\t\terr = errors.New(\"Invalid type option, support: access_key, sts, ecs_ram_role, ram_role_arn, rsa_key_pair\")\n\t\treturn\n\t}\n\treturn credential, nil\n}", "func NewRepository(MongoClient *mongo.Client) Repository {\n\treturn &repository{\n\t\tdatabaseAccess{\n\t\t\tdb: MongoClient,\n\t\t},\n\t}\n}", "func NewCredentialReconciler(helm helm.Client) *CredentialReconciler {\n\treturn &CredentialReconciler{\n\t\thelm: helm,\n\t\tresourceCache: make(map[kindWithGroup]metav1.APIResource),\n\t}\n}", "func NewCredentialService(repo repo.CredentialRepo) service.CredentialService {\n\treturn &credentialService{repo}\n}", "func (s *server) newRepoClient(ctx context.Context, storageName string) (gitalypb.RepositoryServiceClient, error) {\n\tgitalyServerInfo, err := storage.ExtractGitalyServer(ctx, storageName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconn, err := s.conns.Dial(ctx, gitalyServerInfo.Address, gitalyServerInfo.Token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gitalypb.NewRepositoryServiceClient(conn), nil\n}", "func newRepository() Repository {\n\tif cfg == nil {\n\t\tpanic(fmt.Errorf(\"missing configuration\"))\n\t}\n\tif log == nil {\n\t\tpanic(fmt.Errorf(\"missing logger\"))\n\t}\n\n\tp2p.SetConfig(cfg)\n\tp2p.SetLogger(log)\n\n\t// create connections\n\tcaBridge, dbBridge, rpcBridge, geoBridge, err := connect(cfg, log)\n\tif err != nil {\n\t\tlog.Fatal(\"repository init failed\")\n\t\treturn nil\n\t}\n\n\t// construct the proxy instance\n\tp := proxy{\n\t\tcache: caBridge,\n\t\tdb: dbBridge,\n\t\trpc: rpcBridge,\n\t\tgeoip: geoBridge,\n\t\tlog: log,\n\t\tcfg: cfg,\n\n\t\t// get the map of governance contracts\n\t\tgovContracts: governanceContractsMap(cfg.Governance),\n\n\t\t// keep reference to the SOL compiler\n\t\tsolCompiler: cfg.Compiler.DefaultSolCompilerPath,\n\t}\n\n\t// return the proxy\n\treturn &p\n}", "func New(cfg config.DataConfig, repository model.Repository) (*GitRepo, error) {\n\tr, err := g2g.OpenRepository(repository.ClonePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &GitRepo{Repository: repository, cfg: cfg, r: r}, nil\n}", "func NewRepository(repoName string) *Repository {\n\n\tclientIndex := model.ByEquality(\"ClientId\")\n\tclientIndex.Unique = true\n\t//\tuserIndex := model.ByEquality(\"UserId\")\n\t//\tuserIndex.Unique = true\n\n\treturn &Repository{\n\t\tName: repoName,\n\t\tmesssages: model.NewTable(store.DefaultStore, repoName, model.Indexes(clientIndex), nil),\n\t}\n}", "func newRepository(\n\tid borges.RepositoryID,\n\tsto storage.Storer,\n\tfs billy.Filesystem,\n\tm borges.Mode,\n\ttransactional bool,\n\tl *Location,\n) (*Repository, error) {\n\trepo, err := git.Open(sto, nil)\n\tif err != nil {\n\t\tif err == git.ErrRepositoryNotExists {\n\t\t\trepo, err = git.Init(sto, nil)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, borges.ErrLocationNotExists.Wrap(err, id)\n\t\t}\n\t}\n\n\treturn &Repository{\n\t\tid: id,\n\t\trepo: repo,\n\t\ts: sto,\n\t\tfs: fs,\n\t\tmode: m,\n\t\ttransactional: transactional,\n\t\tlocation: l,\n\t\tcreateVersion: -1,\n\t}, nil\n}", "func NewCredentials(build build.Build) Credentials {\n\treturn Credentials{build.Buildpack, build.Layers.HelperLayer(\"google-stackdriver-credentials\", \"Google Stackdriver Credentials\")}\n}", "func (g *GitCredential) Clone() GitCredential {\n\tclone := GitCredential{}\n\n\tvalue := reflect.ValueOf(g).Elem()\n\ttypeOfT := value.Type()\n\tfor i := 0; i < value.NumField(); i++ {\n\t\tfield := value.Field(i)\n\t\tvalue := field.String()\n\t\tv := reflect.ValueOf(&clone).Elem().FieldByName(typeOfT.Field(i).Name)\n\t\tv.SetString(value)\n\t}\n\n\treturn clone\n}", "func New(ctx context.Context, provider config.Provider, configClient config.Client, options ...Option) (Client, error) {\n\treturn newRepositoryClient(ctx, provider, configClient, options...)\n}", "func initCredential() error {\n\tcredential = map[string]string{\n\t\t\"leedev\": \"Go123\",\n\t\t\"guest\": \"xxx\"}\n\n\treturn nil\n}", "func NewRepository(namespace string, k8sClient client.Client, connDecryptToken string) conn_repository.Repository {\n\treturn &k8sConnectionRepository{\n\t\tnamespace: namespace,\n\t\tk8sClient: k8sClient,\n\t\tconnDecryptToken: connDecryptToken,\n\t}\n}", "func NewRepository(e *Enclave) (r *Repository) {\n\tr = &Repository{\n\t\tEnclave: e,\n\t}\n\treturn r\n}", "func New() *Repository {\n\tr := &Repository{}\n\tr.buildChain()\n\treturn r\n}", "func NewRepository(db middleware.Pool) *Repository {\n\treturn &Repository{Database: db}\n}", "func New(repo rel.Repository) UserRepository {\n\treturn userRepository{\n\t\trepository: repo,\n\t}\n}", "func NewRepository(url, user, password string) *Repository {\n\tconst (\n\t\tnameMd5 = \"md5\"\n\t\tnameSha1 = \"sha1\"\n\t)\n\n\tshaOneAndMdFive := make(map[string]*repositoryHash)\n\n\tshaOneAndMdFive[nameMd5] = &repositoryHash{\n\t\tsuffix: nameMd5,\n\t\thash: func() hash.Hash { return md5.New() },\n\t}\n\n\tshaOneAndMdFive[nameSha1] = &repositoryHash{\n\t\tsuffix: nameSha1,\n\t\thash: func() hash.Hash { return sha1.New() },\n\t}\n\n\treturn &Repository{\n\t\turl: url,\n\t\tuser: user,\n\t\tpassword: password,\n\t\tclient: &http.Client{},\n\t\thash: shaOneAndMdFive}\n\n}", "func newUserRepo(db *sql.DB) *userRepo {\n\treturn &userRepo{\n\t\tdb: db,\n\t}\n}", "func New() *Credentials {\n\tc := Credentials{}\n\tc.whitelist = make(map[string]struct{}, 1)\n\treturn &c\n}", "func (ska *SharedKeyCredentials) newSharedKeyCredential() (*SharedKeyCredentials, error) {\n\tif err := ska.setAccountInfo(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ska, nil\n}", "func New() (Repo, error) {\n\t// Open the my.db data file in your current directory.\n\t// It will be created if it doesn't exist.\n\tlogrus.Infof(\"Using database file %s\\n\", conf.Options.DB.ConnectString)\n\tdb, err := bolt.Open(conf.Options.DB.ConnectString, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(\"users\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"teams\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"teamusers\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"oauth\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"channels\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"joinslack\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"convicted\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := &repo{\n\t\tdb: db,\n\t\tstop: make(chan bool),\n\t}\n\tgo r.cleanOAuthState()\n\treturn r, nil\n}", "func New() *Repository {\n\treturn &Repository{\n\t\tagents: map[string]*adagio.Agent{},\n\t\truns: map[string]runState{},\n\t\tclaims: map[string]struct {\n\t\t\trun *adagio.Run\n\t\t\tnode *adagio.Node\n\t\t}{},\n\t\tlisteners: listenerSet{},\n\t}\n}", "func (s *credentialService) Create(ctx context.Context, credType string,\n\tconsumerUsernameOrID *string,\n\tcredential interface{}) (json.RawMessage, error) {\n\n\tif isEmptyString(consumerUsernameOrID) {\n\t\treturn nil, errors.New(\"consumerUsernameOrID cannot be nil\")\n\t}\n\n\tsubPath, ok := credPath[credType]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unknown credential type: %v\", credType)\n\t}\n\tendpoint := \"/consumers/\" + *consumerUsernameOrID + \"/\" + subPath\n\tmethod := \"POST\"\n\tif credential != nil {\n\t\tif id, ok := credential.(id); ok {\n\t\t\tif !reflect.ValueOf(id).IsNil() {\n\t\t\t\tuuid := id.id()\n\t\t\t\tif !isEmptyString(uuid) {\n\t\t\t\t\tendpoint = endpoint + \"/\" + *uuid\n\t\t\t\t\tmethod = \"PUT\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treq, err := s.client.NewRequest(method, endpoint, nil, credential)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar createdCredential json.RawMessage\n\t_, err = s.client.Do(ctx, req, &createdCredential)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn createdCredential, nil\n}", "func newGreetingRepository(db *sql.DB) engine.GreetingRepository {\n\treturn &greetingRepository{db}\n}", "func New(db *gorm.DB) *Repository {\n\treturn &Repository{\n\t\tdb: db,\n\t}\n}", "func New(db *gorm.DB) *Repository {\n\treturn &Repository{\n\t\tdb: db,\n\t}\n}", "func New(db *gorm.DB) *Repository {\n\treturn &Repository{\n\t\tdb: db,\n\t}\n}", "func New(db *bolt.DB) Repository {\n\treturn Repository{\n\t\tdb: db,\n\t}\n}", "func New() (Credential, error) {\n\t_, err := os.Stat(confPath)\n\tif os.IsNotExist(err) {\n\t\terr := makeCredential()\n\t\tif err != nil {\n\t\t\treturn Credential{}, nil\n\t\t}\n\t}\n\tc, err := parseConf()\n\treturn c, err\n}", "func NewCredentials() *Credentials {\n\t// TODO savefile\n\treturn &Credentials{users: map[string]string{}}\n}", "func CreateGitCredential(lines []string) (GitCredential, error) {\n\tvar credential GitCredential\n\n\tif lines == nil {\n\t\treturn credential, errors.New(\"no data lines provided\")\n\t}\n\n\tfieldMap, err := stringhelpers.ExtractKeyValuePairs(lines, \"=\")\n\tif err != nil {\n\t\treturn credential, errors.Wrap(err, \"unable to extract git credential parameters\")\n\t}\n\n\tdata, err := json.Marshal(fieldMap)\n\tif err != nil {\n\t\treturn GitCredential{}, errors.Wrapf(err, \"unable to marshal git credential data\")\n\t}\n\n\terr = json.Unmarshal(data, &credential)\n\tif err != nil {\n\t\treturn GitCredential{}, errors.Wrapf(err, \"unable unmarshal git credential data\")\n\t}\n\n\treturn credential, nil\n}", "func NewRepository(funcs template.FuncMap) *Repository {\n\trepo := Repository{\n\t\tfiles: make(map[string]string),\n\t\ttemplates: make(map[string]*template.Template),\n\t\tfuncs: funcs,\n\t}\n\n\tif repo.funcs == nil {\n\t\trepo.funcs = make(template.FuncMap)\n\t}\n\n\treturn &repo\n}", "func NewRepository(collection Collection) BasicRepository {\n\treturn &basicRepositoryUsecase{\n\t\tcollectionName: collection,\n\t}\n}", "func NewRepository(db *sql.DB) *repository {\n\treturn &repository{db: db}\n}", "func New(prototype Aggregate, opts ...Option) *Repository {\n\tt := reflect.TypeOf(prototype)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\n\tr := &Repository{\n\t\tprototype: t,\n\t\tstore: newMemoryStore(),\n\t\tserializer: NewJSONSerializer(),\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(r)\n\t}\n\n\treturn r\n}", "func NewRepository(db *gorm.DB) *Repository {\n\treturn &Repository{db}\n}", "func NewRepository(db *gorm.DB) *Repository {\n\treturn &Repository{db}\n}", "func writeNewCredential(credential *credentials.KeyCreator, passphrase string, credentialFile *configdir.CredentialFile) error {\n\texportKey := credential.Key\n\tif passphrase != \"\" {\n\t\texportKey = exportKey.Passphrase(credentials.FromString(passphrase))\n\t}\n\n\tencodedCredential, err := exportKey.Export()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn credentialFile.Write(encodedCredential)\n}", "func NewCredentialConfig(io ui.IO) CredentialConfig {\n\treturn &credentialConfig{\n\t\tio: io,\n\t}\n}", "func NewRepo() contact.UserRepo {\n\treturn &userRepo{}\n}", "func NewRepository(db *sql.DB) Repository {\n\treturn &repoSvc{\n\t\tQueries: New(db),\n\t\tdb: db,\n\t}\n}", "func NewRepository(db *db.Database) *Repository {\n\treturn &Repository{db}\n}", "func NewRepo(a *config.AppConfig) *Repository {\n\treturn &Repository{ //returns the referenc to a Repository\n\t\tApp: a, // populate in \"App\" from type \"Repository\n\t}\n}", "func Repository_FromRepositoryAttributes(scope constructs.Construct, id *string, attrs *RepositoryAttributes) IRepository {\n\t_init_.Initialize()\n\n\tvar returns IRepository\n\n\t_jsii_.StaticInvoke(\n\t\t\"monocdk.aws_ecr.Repository\",\n\t\t\"fromRepositoryAttributes\",\n\t\t[]interface{}{scope, id, attrs},\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func NewAuthenticationMethod()(*AuthenticationMethod) {\n m := &AuthenticationMethod{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewRepository(repo *Repository, db *sql.DB) (*Repository, error) {\n\tfmt.Println(\"START NewRepository\")\n\tdefer fmt.Println(\"END START NewRepository\")\n\n\trepo.db = db\n\n\terr := db.Ping()\n\tif err != nil {\n\t\tfmt.Println(\"db err: \", err)\n\t\treturn nil, err\n\t}\n\n\tdb.SetMaxIdleConns(500)\n\tdb.SetMaxOpenConns(500)\n\n\treturn repo, nil\n}", "func NewRepository(s Storer) (*Repository, error) {\n\treturn &Repository{\n\t\ts: s,\n\t\tr: make(map[string]*Remote, 0),\n\t}, nil\n}", "func NewAccountRepository(db *sql.DB) *Accounts {\n\treturn &Accounts{db}\n}", "func NewRepository(awsSession *session.Session, stage string, companyRepo company.IRepository, usersRepo users.UserRepository) SignatureRepository {\n\treturn repository{\n\t\tstage: stage,\n\t\tdynamoDBClient: dynamodb.New(awsSession),\n\t\tcompanyRepo: companyRepo,\n\t\tusersRepo: usersRepo,\n\t\tsignatureTableName: fmt.Sprintf(\"cla-%s-signatures\", stage),\n\t}\n}", "func NewChannelRepository(t testing.TB) *ChannelRepository {\n\tmock := &ChannelRepository{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewCredentials(username string, password string, domain string) *Credentials {\n\tcredentials := Credentials{\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tDomain: domain,\n\t}\n\treturn &credentials\n}", "func New() *Repo {\n\treturn &Repo{}\n}", "func (l *Linux) Create(cfg api.Config, hostname string, token interface{}, user *user.User, vault vault.TerraVault) error {\n\tvar method string\n\tmethod = \"Updated\"\n\n\tif vault != nil {\n\t\t_, err := vault.Get()\n\t\tif err != nil {\n\t\t\tmethod = \"Created\"\n\t\t}\n\n\t\tsecretValue := fmt.Sprintf(\"%v\", token)\n\t\terr = vault.Create(secretValue, method)\n\t\tif err != nil {\n\t\t\thelpers.Logging(cfg, fmt.Sprintf(\"- %s\", err), \"ERROR\")\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Fprintf(color.Output, \"%s: %s the credential object '%s'\\n\", color.GreenString(\"SUCCESS\"), method, hostname)\n\t\treturn err\n\t}\n\n\t_, err := keyring.Get(hostname, string(user.Username))\n\tif err != nil {\n\t\tmethod = \"Created\"\n\t}\n\n\tif token == nil {\n\t\terr = json.NewDecoder(os.Stdin).Decode(&api.CredentialResponse{})\n\t\tif err != nil {\n\t\t\thelpers.CheckError(err)\n\t\t}\n\t\terr = keyring.Set(hostname, string(user.Username), api.CredentialResponse{}.Token)\n\t\treturn err\n\t}\n\n\tstr := fmt.Sprintf(\"%v\", token)\n\terr = keyring.Set(hostname, string(user.Username), str)\n\n\tif err != nil && token != nil {\n\t\tfmt.Fprintf(color.Output, \"%s: You do not have permission to modify this credential\\n\", color.RedString(\"ERROR\"))\n\t\treturn err\n\t}\n\n\tif err != nil {\n\t\thelpers.Logging(cfg, fmt.Sprintf(\"- %s\", err), \"ERROR\")\n\t\treturn nil\n\t}\n\n\tmsg := fmt.Sprintf(\"- %s the credential object %s\", strings.ToLower(method), hostname)\n\thelpers.Logging(cfg, msg, \"SUCCESS\")\n\n\tif token != nil {\n\t\tfmt.Fprintf(color.Output, \"%s: %s the credential object '%s'\\n\", color.GreenString(\"SUCCESS\"), method, hostname)\n\t\treturn err\n\t}\n\n\treturn err\n}", "func newClientMongoRepository() repository.ClientRepository {\n\tmongoAddr := os.Getenv(\"DATABASE_CONN\")\n\tfmt.Println(\"mongoAddr => \", mongoAddr)\n\tclient := repositoryimpl.Connect(mongoAddr)\n\treturn repositoryimpl.NewRepository(client)\n}", "func MakeRepository(db *sql.DB) journal.Repository {\n\tr := &repository{db}\n\n\treturn r\n}", "func NewRepo(a *config.Appconfig) *Repository {\n\treturn &Repository{\n\t\tApp: a,\n\t}\n}", "func NewMockRepository() Repository {\n\treturn mockRepository{\n\t\tUser{\n\t\t\tEmail: \"user1@gmail.com\",\n\t\t\tName: \"User Friendly\",\n\t\t\tRole: \"user\",\n\t\t\tID: 42,\n\t\t\tPassword: \"user1\",\n\t\t},\n\t\tUser{\n\t\t\tEmail: \"user2@gmail.com\",\n\t\t\tName: \"John Walker\",\n\t\t\tRole: \"user\",\n\t\t\tID: 45,\n\t\t\tPassword: \"12345qwerty\",\n\t\t},\n\t}\n}", "func NewRepository(table dynamo.Table) Repository {\n\treturn Repository(user.NewRepository(table))\n}", "func NewRepository(conf *Configuration) (storage.Repository, error) {\n\t// Set client options\n\tclientOptions := options.Client().\n\t\tApplyURI(conf.ConnectionString)\n\n\tif conf.Username != \"\" {\n\t\tclientOptions = clientOptions.\n\t\t\tSetAuth(options.Credential{\n\t\t\t\tUsername: conf.Username,\n\t\t\t\tPassword: conf.Password,\n\t\t\t})\n\t}\n\n\t// Connect to MongoDB\n\tclient, err := mongo.Connect(context.TODO(), clientOptions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check the connection\n\tif err = client.Ping(context.TODO(), nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcollection := client.\n\t\tDatabase(conf.Database).\n\t\tCollection(conf.Collection)\n\n\t// build database\n\tstconf := *conf\n\tstconf.Password = \"\"\n\n\tdb := mongoStore{\n\t\tClient: client,\n\t\tCollection: collection,\n\t\tConfiguration: stconf,\n\t}\n\treturn &db, nil\n}", "func NewRepository(db *database.Database) *Repository {\n\treturn &Repository{db}\n}", "func NewRepository() Repository {\n\treturn &GormRepository{}\n}", "func New(storage storage.Accessor, passwordManager password.Manager) ServiceProvider {\n\treturn &Service{\n\t\tstorage: storage,\n\t\tpasswordManager: passwordManager,\n\t}\n}", "func New(db *gorm.DB) (Repository, error) {\n\treturn &repo{\n\t\tDB: db,\n\t}, nil\n}", "func newRepo(r *github.Repository) Repo {\n\tvar lang string\n\tif r.Language != nil {\n\t\tlang = *r.Language\n\t} else {\n\t\tlang = \"-\"\n\t}\n\treturn Repo{*r.HTMLURL, lang, *r.StargazersCount, *r.ForksCount}\n}", "func NewRepository(data []byte) Repository {\n\treturn Repository{\n\t\tdata: data,\n\t}\n}", "func NewRepository(db *dbcontext.DB, logger log.Logger) Repository {\n\treturn repository{db, logger}\n}", "func NewCreds(id []byte) access.Credential {\n\treturn access.NewContractCreds(id, ContractName, credentialAllCommand)\n}", "func NewRepo(ac *config.App) *Repository {\n\treturn &Repository{\n\t\tApp: ac,\n\t}\n}", "func NewRepository(conn *pgx.Conn) *RepositoryImpl {\n\treturn &RepositoryImpl{conn: conn}\n}", "func (g git) NewRepository(dst string) (WriteableRepository, error) {\n\t_, err := g.OpenRepository(dst)\n\tif err == nil {\n\t\treturn nil, ErrRepoExists\n\t}\n\tcmd := exec.Exec(dst, \"git\", \"init\")\n\tif cmd.Err != nil {\n\t\treturn nil, cmd.Err\n\t}\n\treturn &writeableRepo{\n\t\trepository{rootDir: dst, gitInterface: &g},\n\t}, nil\n}", "func NewRepository(db database.Database) Repository {\n\treturn Repository{db}\n}", "func NewRepository(name, endpoint string, client *http.Client) (*Repository, error) {\n\tname = strings.TrimSpace(name)\n\n\tu, err := utils.ParseEndpoint(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trepository := &Repository{\n\t\tName: name,\n\t\tEndpoint: u,\n\t\tclient: client,\n\t}\n\n\treturn repository, nil\n}", "func NewRepository(db *gorm.DB) *Repository {\n\treturn &Repository{\n\t\tdb: db,\n\t}\n}", "func NewRepository(db *gorm.DB) *Repository {\n\treturn &Repository{\n\t\tdb: db,\n\t}\n}", "func New(registry Registry, name string) *Repository {\n\treturn &Repository{\n\t\tname: name,\n\t\tregistry: registry,\n\t}\n}", "func NewRepository(ctx *pulumi.Context,\n\tname string, args *RepositoryArgs, opts ...pulumi.ResourceOption) (*Repository, error) {\n\tif args == nil {\n\t\targs = &RepositoryArgs{}\n\t}\n\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Repository\n\terr := ctx.RegisterResource(\"aws-native:ecr:Repository\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewAccountsRepository(db *sql.DB) *Accounts {\n\treturn &Accounts{db}\n}", "func NewRepository() (Repository, error) {\n\n\t// Mysql connection configuration\n\tconfig := &mysql.Config{\n\t\tUser: _MysqlUser,\n\t\tPasswd: _MysqlPassword,\n\t\tAddr: fmt.Sprintf(\"%s:%s\", _MysqlHost, _MysqlPort),\n\t\tDBName: _MysqlDB,\n\t\tLoc: time.UTC,\n\t\tParseTime: true,\n\t\tAllowNativePasswords: true,\n\t\tNet: \"tcp\",\n\t}\n\n\t// Do connecting mysql server\n\tconn, err := sql.Open(\"mysql\", config.FormatDSN())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check if mysql is available\n\tif err := conn.Ping(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// return mysql object with connection & error value\n\treturn &repository{conn}, nil\n}", "func New(connection *gorm.DB) Interface {\n\treturn &Repository{connection: connection}\n}", "func NewRegistry(\n\trepoRegistry domain.RepositoryRegistry,\n) domain.Registry {\n\n\tr := registry{\n\t\trepoRegistry: repoRegistry,\n\t\taccountService: NewAccountService(\n\t\t\trepoRegistry,\n\t\t\tvalidator.NewAccountCreation(),\n\t\t\tvalidator.NewAccountBalanceUpdate(),\n\t\t),\n\t\ttransferService: NewTransferService(\n\t\t\trepoRegistry,\n\t\t\tvalidator.NewTransferCreation(),\n\t\t),\n\t\taccessService: NewAccessService(\n\t\t\trepoRegistry,\n\t\t),\n\t}\n\tr.checkDependencies()\n\n\treturn &r\n}", "func NewRepository(db *gorm.DB) ProductDomain.Repository {\n\treturn &handler{\n\t\tdb: db,\n\t}\n}", "func R() Repository {\n\t// make sure to instantiate the Repository only once\n\tonceRepo.Do(func() {\n\t\trepo = newRepository()\n\t})\n\treturn repo\n}", "func NewRepository(db mysql.BaseRepository, logger log.Logger) Repository {\n\treturn repository{db, logger}\n}", "func NewJobRepository(ctxIn context.Context, credentialsProvider secret.SecretProvider) (JobRepository, error) {\n ctx, span := trace.StartSpan(ctxIn, \"NewJobRepository\")\n defer span.End()\n\n storageService, err := service.NewStorageService(ctx, credentialsProvider)\n if err != nil {\n return nil, err\n }\n return &defaultJobRepository{storageService: storageService}, nil\n}", "func OpenRepository(opts GlobalOptions) (*repository.Repository, error) {\n\tif opts.Repo == \"\" {\n\t\treturn nil, errors.Fatal(\"Please specify repository location (-r)\")\n\t}\n\n\tbe, err := open(opts.Repo, opts, opts.extended)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbe = backend.NewRetryBackend(be, 10, func(msg string, err error, d time.Duration) {\n\t\tWarnf(\"%v returned error, retrying after %v: %v\\n\", msg, d, err)\n\t})\n\n\ts := repository.New(be)\n\n\tpasswordTriesLeft := 1\n\tif stdinIsTerminal() && opts.password == \"\" {\n\t\tpasswordTriesLeft = 3\n\t}\n\n\tfor ; passwordTriesLeft > 0; passwordTriesLeft-- {\n\t\topts.password, err = ReadPassword(opts, \"enter password for repository: \")\n\t\tif err != nil && passwordTriesLeft > 1 {\n\t\t\topts.password = \"\"\n\t\t\tfmt.Printf(\"%s. Try again\\n\", err)\n\t\t}\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\terr = s.SearchKey(opts.ctx, opts.password, maxKeys, opts.KeyHint)\n\t\tif err != nil && passwordTriesLeft > 1 {\n\t\t\topts.password = \"\"\n\t\t\tfmt.Printf(\"%s. Try again\\n\", err)\n\t\t}\n\t}\n\tif err != nil {\n\t\tif errors.IsFatal(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, errors.Fatalf(\"%s\", err)\n\t}\n\n\tif stdoutIsTerminal() && !opts.JSON {\n\t\tid := s.Config().ID\n\t\tif len(id) > 8 {\n\t\t\tid = id[:8]\n\t\t}\n\t\tif !opts.JSON {\n\t\t\tVerbosef(\"repository %v opened successfully, password is correct\\n\", id)\n\t\t}\n\t}\n\n\tif opts.NoCache {\n\t\treturn s, nil\n\t}\n\n\tc, err := cache.New(s.Config().ID, opts.CacheDir)\n\tif err != nil {\n\t\tWarnf(\"unable to open cache: %v\\n\", err)\n\t\treturn s, nil\n\t}\n\n\tif c.Created && !opts.JSON {\n\t\tVerbosef(\"created new cache in %v\\n\", c.Base)\n\t}\n\n\t// start using the cache\n\ts.UseCache(c)\n\n\toldCacheDirs, err := cache.Old(c.Base)\n\tif err != nil {\n\t\tWarnf(\"unable to find old cache directories: %v\", err)\n\t}\n\n\t// nothing more to do if no old cache dirs could be found\n\tif len(oldCacheDirs) == 0 {\n\t\treturn s, nil\n\t}\n\n\t// cleanup old cache dirs if instructed to do so\n\tif opts.CleanupCache {\n\t\tPrintf(\"removing %d old cache dirs from %v\\n\", len(oldCacheDirs), c.Base)\n\n\t\tfor _, item := range oldCacheDirs {\n\t\t\tdir := filepath.Join(c.Base, item.Name())\n\t\t\terr = fs.RemoveAll(dir)\n\t\t\tif err != nil {\n\t\t\t\tWarnf(\"unable to remove %v: %v\\n\", dir, err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif stdoutIsTerminal() {\n\t\t\tVerbosef(\"found %d old cache directories in %v, run `restic cache --cleanup` to remove them\\n\",\n\t\t\t\tlen(oldCacheDirs), c.Base)\n\t\t}\n\t}\n\n\treturn s, nil\n}", "func newPassCred(username, password string, secure bool) credentials.PerRPCCredentials {\n\treturn &passCred{\n\t\tusername: username,\n\t\tpassword: password,\n\t\tsecure: secure,\n\t}\n}", "func NewRepository(db *sqlx.DB) *Repository {\n\treturn &Repository{\n\t\tDbConn: db,\n\t}\n}", "func NewRepository(db *sqlx.DB) *Repository {\n\treturn &Repository{\n\t\tDbConn: db,\n\t}\n}", "func NewRepository() Repository {\n\tclient := redis.NewClient(&redis.Options{\n\t\tAddr: \"127.0.0.1:6379\",\n\t\tPassword: \"\",\n\t\tDB: 0,\n\t})\n\n\treturn Repository{Client: client}\n}", "func NewRepository() *Repository {\n\treturn &Repository{\n\t\trepo: make(map[Name]worker.ArtifactSource),\n\t}\n}", "func newService(repo Repository) Service {\n\n\tif repo == nil {\n\t\treturn nil\n\t}\n\treturn &service{repo}\n}", "func newPRMExactRepository(dockerRepository string) (*prmExactRepository, error) {\n\tif _, err := reference.ParseNormalizedNamed(dockerRepository); err != nil {\n\t\treturn nil, InvalidPolicyFormatError(fmt.Sprintf(\"Invalid format of dockerRepository %s: %s\", dockerRepository, err.Error()))\n\t}\n\treturn &prmExactRepository{\n\t\tprmCommon: prmCommon{Type: prmTypeExactRepository},\n\t\tDockerRepository: dockerRepository,\n\t}, nil\n}", "func NewRepo() (r *Repo, err error) {\n\n\tr = &Repo{\n\t\twrappers: make(map[string]*Wrap),\n\t\twaiting: make(map[string]chan struct{}),\n\t}\n\n\treturn r, nil\n}", "func CreateCredential(credential *Credential) (int, error) {\n\tstatus := DEFAULT_STATUS | credential.Status\n\n\tresult, err := DB_mysql.Exec(`insert into credentials(iss,\n\tsub,aud,exp,nbf,iat,jti,net,ipfs,context,credential,status) \n\tvalues (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\tcredential.Iss,\n\t\tcredential.Sub,\n\t\tcredential.Aud,\n\t\tcredential.Exp,\n\t\tcredential.Nbf,\n\t\tcredential.Iat,\n\t\tcredential.Jti,\n\t\tcredential.Net,\n\t\tcredential.IPFS,\n\t\tcredential.Context,\n\t\tcredential.Credential,\n\t\tstatus)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn int(id), nil\n}" ]
[ "0.59865445", "0.5940002", "0.59099764", "0.5908211", "0.58889973", "0.5883554", "0.58732665", "0.5836357", "0.58078223", "0.57829154", "0.5782139", "0.57490116", "0.5743227", "0.5730849", "0.5683967", "0.56299347", "0.5625149", "0.5606245", "0.55853844", "0.5578856", "0.55719334", "0.554693", "0.55390453", "0.5529906", "0.5522423", "0.5520613", "0.551399", "0.5495505", "0.54945725", "0.547049", "0.5457229", "0.5457229", "0.5457229", "0.54515886", "0.54461604", "0.54255044", "0.5423901", "0.5423411", "0.5416873", "0.5414348", "0.5405604", "0.53961146", "0.53961146", "0.5386624", "0.5383671", "0.5376753", "0.537575", "0.53749186", "0.5373238", "0.53606665", "0.5356548", "0.5349771", "0.53456813", "0.53439337", "0.5341661", "0.53404415", "0.5333798", "0.53337884", "0.5333088", "0.5321591", "0.53180504", "0.531672", "0.5315492", "0.5312519", "0.5305462", "0.53048635", "0.53007454", "0.5299486", "0.5298614", "0.5293054", "0.5288739", "0.5288559", "0.5288244", "0.52849644", "0.52826947", "0.52798885", "0.5279404", "0.5277331", "0.5276952", "0.5276952", "0.5275752", "0.52701944", "0.5263425", "0.52631783", "0.5261444", "0.5258673", "0.52534264", "0.5246078", "0.52457875", "0.5232869", "0.5224262", "0.5218094", "0.5212614", "0.5212614", "0.52117205", "0.5204588", "0.52025265", "0.5202307", "0.5202169", "0.51995075" ]
0.7442926
0
GetCPUInfo reads the cpu info from the system
func (info *RpiInfo) GetCPUInfo() error { file, err := os.Open("/proc/cpuinfo") if err != nil { return err } defer file.Close() info.readCPUInfo(file) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Simple) CPUInfo(req *acomm.Request) (interface{}, *url.URL, error) {\n\tvar args CPUInfoArgs\n\tif err := req.UnmarshalArgs(&args); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif args.GuestID == \"\" {\n\t\treturn nil, nil, errors.New(\"missing guest_id\")\n\t}\n\n\tresult := &CPUInfoResult{\n\t\t&CPUInfo{\n\t\t\tProcessor: 0,\n\t\t\tMHz: 2600,\n\t\t},\n\t\t&CPUInfo{\n\t\t\tProcessor: 1,\n\t\t\tMHz: 2600,\n\t\t},\n\t}\n\treturn result, nil, nil\n}", "func (s *Stats) GetCPUInfo() {\n\n if s.CPUInfo == nil {\n s.CPUInfo = new(CPUInfo)\n }\n\n s.CPUInfo.CPU, _ = cpu.Info()\n}", "func CPUInfo(args ...int) (string, error) {\n\tinfo, err := cpu.Info()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(info) == 0 {\n\t\treturn \"\", errors.New(\"no CPU detected\")\n\t}\n\n\tif len(args) > 0 {\n\t\treturn info[args[0]].ModelName, nil\n\t}\n\n\treturn info[0].ModelName, nil\n}", "func ComputeCPUInfo(ctx context.Context, cluster *object.ClusterComputeResource) (uint64, error) {\n\tvar cr mo.ComputeResource\n\tvar hosts []mo.HostSystem\n\tvar minFreq uint64\n\n\tif cluster == nil {\n\t\treturn 0, errors.New(\"Must have a valid cluster reference to compute the cpu info\")\n\t}\n\n\terr := cluster.Properties(ctx, cluster.Reference(), nil, &cr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif len(cr.Host) == 0 {\n\t\treturn 0, errors.New(\"No hosts found in the cluster\")\n\t}\n\n\tpc := property.DefaultCollector(cluster.Client())\n\terr = pc.Retrieve(ctx, cr.Host, []string{\"summary\"}, &hosts)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tfor _, h := range hosts {\n\t\tif h.Summary.Hardware == nil {\n\t\t\tcontinue\n\t\t}\n\t\thostCpuMHz := uint64(h.Summary.Hardware.CpuMhz)\n\t\tif hostCpuMHz < minFreq || minFreq == 0 {\n\t\t\tminFreq = hostCpuMHz\n\t\t}\n\t}\n\n\treturn minFreq, nil\n}", "func Get() (CPUInfo, error) {\n\tbytes, err := ioutil.ReadFile(\"/proc/cpuinfo\")\n\tif err != nil {\n\t\treturn CPUInfo{}, err\n\t}\n\n\tcpuInfo, err := parse(bytes)\n\n\treturn cpuInfo, err\n}", "func GetCPUInfos() (map[string][]string, error) {\n\treturninfos := make(map[string][]string)\n\n\tcpuinfo, err := os.OpenFile(\"/proc/cpuinfo\", os.O_RDONLY|os.O_SYNC, 0666)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not open /proc/cpuinfo\")\n\t}\n\tdefer cpuinfo.Close()\n\tcpuinfo.Seek(0, 0)\n\tinforeader := bufio.NewReader(cpuinfo)\n\tvar line string\n\tfor line, err = inforeader.ReadString('\\n'); err == nil; line, err = inforeader.ReadString('\\n') {\n\t\tfields := strings.SplitN(line, \":\", 2)\n\t\tif len(fields) == 2 {\n\t\t\tkey := strings.TrimSpace(fields[0])\n\t\t\tvalue := strings.TrimSpace(fields[1])\n\t\t\tif pv, inmap := returninfos[key]; inmap {\n\t\t\t\treturninfos[key] = append(pv, value)\n\t\t\t} else {\n\t\t\t\treturninfos[key] = []string{value}\n\t\t\t}\n\t\t}\n\t}\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\treturn returninfos, err\n}", "func (s *Stats) GetAllCPUInfo() {\n s.GetCPUInfo()\n s.GetCPUTimes()\n}", "func initCPUInfo() {\n\tif runtime.GOOS != \"linux\" {\n\t\t// Don't try to read Linux-specific /proc files or\n\t\t// warn about them not existing.\n\t\treturn\n\t}\n\tcpuinfob, err := ioutil.ReadFile(\"/proc/cpuinfo\")\n\tif err != nil {\n\t\t// Leave everything at 0, nothing can be done.\n\t\tlog.Warningf(\"Could not read /proc/cpuinfo: %v\", err)\n\t\treturn\n\t}\n\tcpuinfo := string(cpuinfob)\n\n\t// We get the value straight from host /proc/cpuinfo.\n\tfor _, line := range strings.Split(cpuinfo, \"\\n\") {\n\t\tswitch {\n\t\tcase strings.Contains(line, \"BogoMIPS\"):\n\t\t\tsplitMHz := strings.Split(line, \":\")\n\t\t\tif len(splitMHz) < 2 {\n\t\t\t\tlog.Warningf(\"Could not read /proc/cpuinfo: malformed BogoMIPS\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// If there was a problem, leave cpuFreqMHz as 0.\n\t\t\tvar err error\n\t\t\thostFeatureSet.cpuFreqMHz, err = strconv.ParseFloat(strings.TrimSpace(splitMHz[1]), 64)\n\t\t\tif err != nil {\n\t\t\t\thostFeatureSet.cpuFreqMHz = 0.0\n\t\t\t\tlog.Warningf(\"Could not parse BogoMIPS value %v: %v\", splitMHz[1], err)\n\t\t\t}\n\t\tcase strings.Contains(line, \"CPU implementer\"):\n\t\t\tsplitImpl := strings.Split(line, \":\")\n\t\t\tif len(splitImpl) < 2 {\n\t\t\t\tlog.Warningf(\"Could not read /proc/cpuinfo: malformed CPU implementer\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// If there was a problem, leave cpuImplHex as 0.\n\t\t\tvar err error\n\t\t\thostFeatureSet.cpuImplHex, err = strconv.ParseUint(strings.TrimSpace(splitImpl[1]), 0, 64)\n\t\t\tif err != nil {\n\t\t\t\thostFeatureSet.cpuImplHex = 0\n\t\t\t\tlog.Warningf(\"Could not parse CPU implementer value %v: %v\", splitImpl[1], err)\n\t\t\t}\n\t\tcase strings.Contains(line, \"CPU architecture\"):\n\t\t\tsplitArch := strings.Split(line, \":\")\n\t\t\tif len(splitArch) < 2 {\n\t\t\t\tlog.Warningf(\"Could not read /proc/cpuinfo: malformed CPU architecture\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// If there was a problem, leave cpuArchDec as 0.\n\t\t\tvar err error\n\t\t\thostFeatureSet.cpuArchDec, err = strconv.ParseUint(strings.TrimSpace(splitArch[1]), 0, 64)\n\t\t\tif err != nil {\n\t\t\t\thostFeatureSet.cpuArchDec = 0\n\t\t\t\tlog.Warningf(\"Could not parse CPU architecture value %v: %v\", splitArch[1], err)\n\t\t\t}\n\t\tcase strings.Contains(line, \"CPU variant\"):\n\t\t\tsplitVar := strings.Split(line, \":\")\n\t\t\tif len(splitVar) < 2 {\n\t\t\t\tlog.Warningf(\"Could not read /proc/cpuinfo: malformed CPU variant\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// If there was a problem, leave cpuVarHex as 0.\n\t\t\tvar err error\n\t\t\thostFeatureSet.cpuVarHex, err = strconv.ParseUint(strings.TrimSpace(splitVar[1]), 0, 64)\n\t\t\tif err != nil {\n\t\t\t\thostFeatureSet.cpuVarHex = 0\n\t\t\t\tlog.Warningf(\"Could not parse CPU variant value %v: %v\", splitVar[1], err)\n\t\t\t}\n\t\tcase strings.Contains(line, \"CPU part\"):\n\t\t\tsplitPart := strings.Split(line, \":\")\n\t\t\tif len(splitPart) < 2 {\n\t\t\t\tlog.Warningf(\"Could not read /proc/cpuinfo: malformed CPU part\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// If there was a problem, leave cpuPartHex as 0.\n\t\t\tvar err error\n\t\t\thostFeatureSet.cpuPartHex, err = strconv.ParseUint(strings.TrimSpace(splitPart[1]), 0, 64)\n\t\t\tif err != nil {\n\t\t\t\thostFeatureSet.cpuPartHex = 0\n\t\t\t\tlog.Warningf(\"Could not parse CPU part value %v: %v\", splitPart[1], err)\n\t\t\t}\n\t\tcase strings.Contains(line, \"CPU revision\"):\n\t\t\tsplitRev := strings.Split(line, \":\")\n\t\t\tif len(splitRev) < 2 {\n\t\t\t\tlog.Warningf(\"Could not read /proc/cpuinfo: malformed CPU revision\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// If there was a problem, leave cpuRevDec as 0.\n\t\t\tvar err error\n\t\t\thostFeatureSet.cpuRevDec, err = strconv.ParseUint(strings.TrimSpace(splitRev[1]), 0, 64)\n\t\t\tif err != nil {\n\t\t\t\thostFeatureSet.cpuRevDec = 0\n\t\t\t\tlog.Warningf(\"Could not parse CPU revision value %v: %v\", splitRev[1], err)\n\t\t\t}\n\t\t}\n\t}\n}", "func readCPUInfo() ([]cpuInfo, error) {\n\tcpuinfo, err := ioutil.ReadFile(\"/proc/cpuinfo\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcpus := strings.Split(string(cpuinfo), \"\\n\\n\")\n\tr := make([]cpuInfo, len(cpus))\n\tfor i, cpu := range cpus {\n\t\tif strings.TrimSpace(cpu) == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tm := map[string]string{}\n\t\tfor _, line := range strings.Split(cpu, \"\\n\") {\n\t\t\tc := strings.Split(line, \":\")\n\t\t\tif len(c) == 2 {\n\t\t\t\tkey := strings.TrimSpace(c[0])\n\t\t\t\tvalue := strings.TrimSpace(c[1])\n\t\t\t\tm[key] = value\n\t\t\t}\n\t\t}\n\n\t\tst := reflect.TypeOf(r[i])\n\t\tobj := reflect.ValueOf(&r[i]).Elem()\n\t\tfor i := 0; i < st.NumField(); i++ {\n\t\t\ttag := st.Field(i).Tag.Get(\"cpuinfo\")\n\t\t\tvalue, ok := m[tag]\n\t\t\tif !ok {\n\t\t\t\treturn nil, errors.Errorf(\"Missing value for cpuinfo key %s\", tag)\n\t\t\t}\n\n\t\t\tfield := obj.Field(i)\n\t\t\tkind := field.Kind()\n\t\t\tswitch kind {\n\t\t\tcase reflect.String:\n\t\t\t\tfield.SetString(value)\n\t\t\tcase reflect.Uint:\n\t\t\t\tn, err := strconv.ParseUint(value, 0, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tfield.SetUint(n)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn r, nil\n}", "func getCPUDetails(log logging.Logger, numaSSDs numaSSDsMap, coresPerNuma int) (numaCoreCountsMap, error) {\n\tif coresPerNuma < 1 {\n\t\treturn nil, errors.Errorf(errInvalNrCores, coresPerNuma)\n\t}\n\n\tnumaCoreCounts := make(numaCoreCountsMap)\n\tfor numaID, ssds := range numaSSDs {\n\t\tcoreCounts, err := checkCPUs(log, len(ssds), coresPerNuma)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnumaCoreCounts[numaID] = coreCounts\n\t}\n\n\treturn numaCoreCounts, nil\n}", "func TestGetCPUStat(t *testing.T) {\n\t// setup the faking of `cpu.Info()`\n\toldcpuInfo := cpuInfo\n\tcpuInfo = func() ([]cpu.InfoStat, error) {\n\t\tret := []cpu.InfoStat{\n\t\t\t{\n\t\t\t\tVendorID: string(\"vendor\"),\n\t\t\t\tModelName: string(\"model\"),\n\t\t\t\tMhz: float64(100),\n\t\t\t},\n\t\t\t{\n\t\t\t\tVendorID: string(\"vendor\"), // two CPUs --> cpuinfo.count = \"2\"\n\t\t\t\tModelName: string(\"model\"),\n\t\t\t\tMhz: float64(100),\n\t\t\t},\n\t\t}\n\t\treturn ret, nil\n\t}\n\n\t// test\n\texpected := cpuStat{\n\t\tcount: strconv.FormatInt(2, 10),\n\t\tvendorID: \"vendor\",\n\t\tmodelName: \"model\",\n\t\tmhz: strconv.FormatInt(100, 10),\n\t}\n\tactual, err := getCPUStat()\n\n\tassert.NoError(t, err, \"`getCPUStat()` should not have returned an error\")\n\tassert.Equal(t, expected, actual, \"`getCPUStat()` should be equal to main.cpuStat{count:\\\"2\\\", vendorID:\\\"vendor\\\", modelName:\\\"model\\\", mhz:\\\"100\\\"}\")\n\n\t// teardown\n\tcpuInfo = oldcpuInfo\n}", "func Getcpu(t *kernel.Task, sysno uintptr, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n\tcpu := args[0].Pointer()\n\tnode := args[1].Pointer()\n\t// third argument to this system call is nowadays unused.\n\n\tif cpu != 0 {\n\t\tif _, err := primitive.CopyInt32Out(t, cpu, t.CPU()); err != nil {\n\t\t\treturn 0, nil, err\n\t\t}\n\t}\n\t// We always return node 0.\n\tif node != 0 {\n\t\tif _, err := t.MemoryManager().ZeroOut(t, node, 4, usermem.IOOpts{\n\t\t\tAddressSpaceActive: true,\n\t\t}); err != nil {\n\t\t\treturn 0, nil, err\n\t\t}\n\t}\n\treturn 0, nil, nil\n}", "func GetSystemCPUUsage() (uint64, error) {\n\tvar line string\n\tf, err := os.Open(\"/proc/stat\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tbufReader := bufio.NewReaderSize(nil, 128)\n\tdefer func() {\n\t\tbufReader.Reset(nil)\n\t\tf.Close()\n\t}()\n\tbufReader.Reset(f)\n\terr = nil\n\tfor err == nil {\n\t\tline, err = bufReader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tparts := strings.Fields(line)\n\t\tswitch parts[0] {\n\t\tcase \"cpu\":\n\t\t\tif len(parts) < 8 {\n\t\t\t\treturn 0, fmt.Errorf(\"bad format of cpu stats\")\n\t\t\t}\n\t\t\tvar totalClockTicks uint64\n\t\t\tfor _, i := range parts[1:8] {\n\t\t\t\tv, err := strconv.ParseUint(i, 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"error parsing cpu stats\")\n\t\t\t\t}\n\t\t\t\ttotalClockTicks += v\n\t\t\t}\n\t\t\treturn (totalClockTicks * nanoSecondsPerSecond) /\n\t\t\t\tclockTicksPerSecond, nil\n\t\t}\n\t}\n\treturn 0, fmt.Errorf(\"bad stats format\")\n}", "func (cpu *CPU) Get(s *smbios.Structure) error {\n\t// SMBIOS returns an index starting from 1, need to -1 for Go slice indices\n\tcpu.SocketDesignation = strings.TrimSpace(s.Strings[(s.Formatted[0] - 1)])\n\tcpu.ProcessorManufacturer = strings.TrimSpace(s.Strings[(s.Formatted[3] - 1)])\n\tcpu.Version = strings.TrimSpace(s.Strings[(s.Formatted[12] - 1)])\n\tcpu.SerialNumber = strings.TrimSpace(s.Strings[(s.Formatted[28] - 1)])\n\tcpu.AssetTag = strings.TrimSpace(s.Strings[(s.Formatted[29] - 1)])\n\tcpu.PartNumber = strings.TrimSpace(s.Strings[(s.Formatted[30] - 1)])\n\tcpu.ProcessorType = processorTypeList[int(s.Formatted[1])]\n\tcpu.ProcessorFamily = processorFamilyList[int(s.Formatted[2])]\n\tcpu.Stepping = int(s.Formatted[4]) & 15\n\tcpu.Family = int(s.Formatted[5]) & 15\n\tcpu.Model = getCPUModelInt(int(s.Formatted[4]), int(s.Formatted[6]))\n\tcpu.Voltage = getCPUVoltage(int(s.Formatted[13]))\n\tcpu.ExternalClock = int(binary.LittleEndian.Uint16(s.Formatted[14:16]))\n\tcpu.MaxSpeed = int(binary.LittleEndian.Uint16(s.Formatted[16:18]))\n\tcpu.CurrentSpeed = int(binary.LittleEndian.Uint16(s.Formatted[18:20]))\n\tcpu.L1CacheHandle = fmt.Sprintf(\"0x%04d\", binary.LittleEndian.Uint16(s.Formatted[22:24]))\n\tcpu.L2CacheHandle = fmt.Sprintf(\"0x%04d\", binary.LittleEndian.Uint16(s.Formatted[24:26]))\n\tcpu.L3CacheHandle = fmt.Sprintf(\"0x%04d\", binary.LittleEndian.Uint16(s.Formatted[26:28]))\n\tcpu.StatusFlags = getCPUStatusFlags(int(s.Formatted[20]))\n\tcpu.ProcessorUpgrade = processorUpgradeList[int(s.Formatted[21])]\n\tcpu.CoreCount = int(s.Formatted[31])\n\tcpu.CoreEnabled = int(s.Formatted[32])\n\tcpu.ThreadCount = int(s.Formatted[33])\n\t// Fields 34 and 35 make up the bits for the characteristics flags\n\tcpu.ProcessorCharacteristics = getCPUCharacteristicsFlags(int(binary.LittleEndian.Uint16(s.Formatted[34:36])))\n\t// Fields 8 - 11 make up the bits for the EDX CPU Feature flags\n\tcpu.ProcessorFlags = getCPUFeatureFlags(int(binary.LittleEndian.Uint16(s.Formatted[8:12])))\n\n\treturn nil\n}", "func GetCpuCount() float64 {\n return float64(procStatCpuCount)\n}", "func (r *Resources) GetCPU() float64 {\n\treturn r.CPU\n}", "func getCPUStats() (userCPU, systemCPU float64) {\n\treturn 0.0, 0.0\n}", "func procCPU(_ int) (ProcCPUStats, error) {\n\treturn ProcCPUStats{}, nil\n}", "func CPUInfoQuery(query string, w trdsql.Writer) error {\n\treader, err := CPUInfoReader()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefaultQuery := \"SELECT * FROM \" + psCPUInfo + \" ORDER BY cpu\"\n\tif query == \"\" {\n\t\tquery = defaultQuery\n\t}\n\treturn readerExec(reader, query, w)\n}", "func SystemInfo() string {\n\n\tvar si SysInfo\n\tvar m runtime.MemStats\n\truntime.ReadMemStats(&m)\n\tsi.AllocMemory = m.Alloc\n\tsi.AllocMemoryMB = btomb(m.Alloc)\n\tsi.TotalAllocMemory = m.TotalAlloc\n\tsi.TotalAllocMemoryMB = btomb(m.TotalAlloc)\n\tsi.TotalSystemMemory = m.Sys\n\tsi.TotalSystemMemoryMB = btomb(m.Sys)\n\tc, _ := cpu.Info()\n\n\tsi.CPUs = c[0].Cores\n\n\tsi.GolangVersion = runtime.Version()\n\tsi.ContainerHostName, _ = os.Hostname()\n\tsi.CurrentUTC = time.Now().UTC()\n\n\tsi.CurrentLocalTime = time.Now().Local()\n\n\tconst (\n\t\tB = 1\n\t\tKB = 1024 * B\n\t\tMB = 1024 * KB\n\t\tGB = 1024 * MB\n\t)\n\n\tv, _ := mem.VirtualMemory()\n\tfmt.Printf(\"Total: %v, Free:%v, UsedPercent:%f%%\\n\", v.Total, v.Free, v.UsedPercent)\n\n\ttype InfoStat struct {\n\t\tHostname string `json:\"hostname\"`\n\t\tUptime uint64 `json:\"uptime\"`\n\t\tBootTime uint64 `json:\"bootTime\"`\n\t\tProcs uint64 `json:\"procs\"` // number of processes\n\t\tOS string `json:\"os\"` // ex: freebsd, linux\n\t\tPlatform string `json:\"platform\"` // ex: ubuntu, linuxmint\n\t\tPlatformFamily string `json:\"platformFamily\"` // ex: debian, rhel\n\t\tPlatformVersion string `json:\"platformVersion\"` // version of the complete OS\n\t\tKernelVersion string `json:\"kernelVersion\"` // version of the OS kernel (if available)\n\t\tVirtualizationSystem string `json:\"virtualizationSystem\"`\n\t\tVirtualizationRole string `json:\"virtualizationRole\"` // guest or host\n\t\tHostID string `json:\"hostid\"` // ex: uuid\n\t}\n\n\tvar his *host.InfoStat\n\this, _ = host.Info()\n\n\tsi.Uptime = his.Uptime\n\n\tsi.OperatingSystem = his.OS\n\tsi.Platform = his.Platform\n\tsi.PlatformFamily = his.PlatformFamily\n\tsi.PlatformVersion = his.PlatformVersion\n\tsi.VirtualSystem = his.VirtualizationSystem\n\tsi.VirtualRole = his.VirtualizationRole\n\tsi.HostID = his.HostID\n\tsi.HostName = his.Hostname\n\tsi.BootTime = strconv.FormatUint(his.BootTime, 10)\n\tsi.KernelVersion = his.KernelVersion\n\n\tsi.UptimeDays = si.Uptime / (60 * 60 * 24)\n\tsi.UptimeHours = (si.Uptime - (si.UptimeDays * 60 * 60 * 24)) / (60 * 60)\n\tsi.UptimeMinutes = ((si.Uptime - (si.UptimeDays * 60 * 60 * 24)) - (si.UptimeHours * 60 * 60)) / 60\n\tinterfaces, err := net.Interfaces()\n\n\tif err == nil {\n\t\tfor i, interfac := range interfaces {\n\t\t\tif interfac.Name == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taddrs := interfac.Addrs\n\t\t\tsi.NetworkInterfaces[i].Name = interfac.Name\n\t\t\tsi.NetworkInterfaces[i].HardwareAddress = string(interfac.HardwareAddr)\n\t\t\tfor x, addr := range addrs {\n\t\t\t\tif addr.String() != \"\" {\n\t\t\t\t\tsi.NetworkInterfaces[i].IPAddresses[x].IPAddress = addr.String()\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar paths [10]string\n\tpaths[0] = \"/\"\n\n\tfor i, path := range paths {\n\t\tdisk := DiskUsage(path)\n\t\tsi.Disk[i].Path = path\n\t\tsi.Disk[i].All = float64(disk.All) / float64(GB)\n\t\tsi.Disk[i].Used = float64(disk.Used) / float64(GB)\n\t\tsi.Disk[i].Free = float64(disk.Free) / float64(GB)\n\t}\n\n\tstrJSON, err := json.Marshal(si)\n\tcheckErr(err)\n\n\treturn string(strJSON)\n}", "func GetSystemCpuUsage() (uint64, error) {\n\tvar (\n\t\tline string\n\t\tf *os.File\n\t\tusage uint64 = 0\n\t\terr error\n\t)\n\tif f, err = os.Open(\"/proc/stat\"); err != nil {\n\t\treturn 0, err\n\t}\n\tbufReader := bufio.NewReaderSize(nil, 128)\n\tdefer func() {\n\t\tbufReader.Reset(nil)\n\t\tf.Close()\n\t}()\n\tbufReader.Reset(f)\n\tfor err == nil {\n\t\tif line, err = bufReader.ReadString('\\n'); err != nil {\n\t\t\terr = errors.WithStack(err)\n\t\t\treturn 0, err\n\t\t}\n\t\tarray := strings.Fields(line)\n\t\tswitch array[0] {\n\t\tcase \"cpu\": //只统计cpu那行的数据\n\t\t\tif len(array) < 8 {\n\t\t\t\terr = errors.WithStack(fmt.Errorf(\"bad format of cpu stats\"))\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tvar totalClockTicks uint64\n\t\t\tfor _, i := range array[1:8] {\n\t\t\t\tvar v uint64\n\t\t\t\tif v, err = strconv.ParseUint(i, 10, 64); err != nil {\n\t\t\t\t\terr = errors.WithStack(fmt.Errorf(\"error parsing cpu stats\"))\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t\ttotalClockTicks += v\n\t\t\t}\n\t\t\tusage = (totalClockTicks * nanoSecondsPerSecond) / clockTicksPerSecond\n\t\t\treturn usage, nil\n\t\t}\n\t}\n\terr = errors.Errorf(\"bad stats format\")\n\treturn 0, err\n}", "func perfInfo() ([]win32_SystemProcessorPerformanceInformation, error) {\n\t// Make maxResults large for safety.\n\t// We can't invoke the api call with a results array that's too small.\n\t// If we have more than 2056 cores on a single host, then it's probably the future.\n\tmaxBuffer := 2056\n\t// buffer for results from the windows proc\n\tresultBuffer := make([]win32_SystemProcessorPerformanceInformation, maxBuffer)\n\t// size of the buffer in memory\n\tbufferSize := uintptr(win32_SystemProcessorPerformanceInfoSize) * uintptr(maxBuffer)\n\t// size of the returned response\n\tvar retSize uint32\n\n\t// Invoke windows api proc.\n\t// The returned err from the windows dll proc will always be non-nil even when successful.\n\t// See https://godoc.org/golang.org/x/sys/windows#LazyProc.Call for more information\n\tretCode, _, err := common.ProcNtQuerySystemInformation.Call(\n\t\twin32_SystemProcessorPerformanceInformationClass, // System Information Class -> SystemProcessorPerformanceInformation\n\t\tuintptr(unsafe.Pointer(&resultBuffer[0])), // pointer to first element in result buffer\n\t\tbufferSize, // size of the buffer in memory\n\t\tuintptr(unsafe.Pointer(&retSize)), // pointer to the size of the returned results the windows proc will set this\n\t)\n\n\t// check return code for errors\n\tif retCode != 0 {\n\t\treturn nil, fmt.Errorf(\"call to NtQuerySystemInformation returned %d. err: %s\", retCode, err.Error())\n\t}\n\n\t// calculate the number of returned elements based on the returned size\n\tnumReturnedElements := retSize / win32_SystemProcessorPerformanceInfoSize\n\n\t// trim results to the number of returned elements\n\tresultBuffer = resultBuffer[:numReturnedElements]\n\n\treturn resultBuffer, nil\n}", "func (t *Template) GetCPU() (float64, error) {\n\n\tCPU, err := t.GetFloat(string(keys.CPU))\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn CPU, nil\n}", "func GetCPU() string {\n\tm := map[string]string{\n\t\t\"amd64\": \"x86_64\",\n\t\t\"386\": \"x86\",\n\t\t\"arm64\": \"aarch64\",\n\t\t\"arm\": \"arm\",\n\t\t\"ppc64le\": \"powerpc64le\",\n\t\t\"ppc64\": \"powerpc64\",\n\t\t// powerpc32le is not supported by Go\n\t\t\"ppc\": \"powerpc32\",\n\t\t\"mipsle\": \"mips32el\",\n\t\t\"mips\": \"mips32\",\n\t\t\"mips64le\": \"mips64el\",\n\t\t\"mips64\": \"mips64\",\n\t}\n\treturn m[runtime.GOARCH]\n}", "func (o *VirtualizationVmwareVirtualMachineAllOf) GetCpuSocketInfo() VirtualizationVmwareVmCpuSocketInfo {\n\tif o == nil || o.CpuSocketInfo.Get() == nil {\n\t\tvar ret VirtualizationVmwareVmCpuSocketInfo\n\t\treturn ret\n\t}\n\treturn *o.CpuSocketInfo.Get()\n}", "func (p *Proc) CPU() (float64, error) {\n\tvar totalCPU float64\n\terr := p.walkProcessTree(p.proc, func(p *process.Process) error {\n\t\tcpu, err := p.Percent(0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttotalCPU += cpu\n\t\treturn nil\n\t})\n\n\treturn totalCPU, err\n}", "func (o *HostMetrics) GetCpu() float64 {\n\tif o == nil || o.Cpu == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\treturn *o.Cpu\n}", "func getCPUUtilization() (*define.CPUUsage, error) {\n\tbuf, err := unix.SysctlRaw(\"kern.cp_time\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading sysctl kern.cp_time: %w\", err)\n\t}\n\n\tvar total uint64 = 0\n\tvar times [unix.CPUSTATES]uint64\n\n\tfor i := 0; i < unix.CPUSTATES; i++ {\n\t\tval := *(*uint64)(unsafe.Pointer(&buf[8*i]))\n\t\ttimes[i] = val\n\t\ttotal += val\n\t}\n\treturn &define.CPUUsage{\n\t\tUserPercent: timeToPercent(times[unix.CP_USER], total),\n\t\tSystemPercent: timeToPercent(times[unix.CP_SYS], total),\n\t\tIdlePercent: timeToPercent(times[unix.CP_IDLE], total),\n\t}, nil\n}", "func CPUUsage() {\r\n usage, err := cpu.Percent(0, perCPU)\r\n for i, value := range usage {\r\n fmt.Printf(\"CPU%d: %f \", i, value)\r\n }\r\n check(err)\r\n}", "func ReadCPUStats() (*CPUStats, error) {\r\n\treturn nil, errors.New(\"not implement\")\r\n}", "func Discover(machineInfo *cadvisorapi.MachineInfo) (*CPUTopology, error) {\n\n\tif machineInfo.NumCores == 0 {\n\t\treturn nil, fmt.Errorf(\"could not detect number of cpus\")\n\t}\n\n\tCPUDetails := CPUDetails{}\n\tnumCPUs := machineInfo.NumCores\n\tnumPhysicalCores := 0\n\tvar coreID int\n\tvar err error\n\n\tfor _, socket := range machineInfo.Topology {\n\t\tnumPhysicalCores += len(socket.Cores)\n\t\tfor _, core := range socket.Cores {\n\t\t\tif coreID, err = getUniqueCoreID(core.Threads); err != nil {\n\t\t\t\tglog.Errorf(\"could not get unique coreID for socket: %d core %d threads: %v\",\n\t\t\t\t\tsocket.Id, core.Id, core.Threads)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor _, cpu := range core.Threads {\n\t\t\t\tCPUDetails[cpu] = CPUInfo{\n\t\t\t\t\tCoreID: coreID,\n\t\t\t\t\tSocketID: socket.Id,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &CPUTopology{\n\t\tNumCPUs: numCPUs,\n\t\tNumSockets: len(machineInfo.Topology),\n\t\tNumCores: numPhysicalCores,\n\t\tCPUDetails: CPUDetails,\n\t}, nil\n}", "func GetOnlineCPUs() int {\n\tfile, err := os.Open(\"/proc/stat\")\n\tif err != nil {\n\t\treturn -1\n\t}\n\tcpusOnline := getOnlineCPUs(file)\n\t_ = file.Close()\n\treturn cpusOnline\n}", "func getCPUUsage() (data.MemoryFrame, error) {\n\tcpuList := gosigar.CpuList{}\n\terr := cpuList.Get()\n\tif err != nil {\n\t\treturn data.MemoryFrame{}, errors.Wrapf(err, \"unable to list cpus for usage\")\n\t}\n\tcolumns := []string{\"sys\", \"nice\", \"stolen\", \"irq\", \"idle\", \"softIrq\", \"user\", \"wait\", \"total\"}\n\trows := make([][]interface{}, len(cpuList.List), len(cpuList.List))\n\tfor i, cpu := range cpuList.List {\n\t\trows[i] = []interface{}{cpu.Sys, cpu.Nice, cpu.Stolen, cpu.Irq, cpu.Idle, cpu.SoftIrq, cpu.User, cpu.Wait, cpu.Total()}\n\t}\n\treturn data.NewMemoryFrame(\"cpu_usage\", columns, rows), nil\n}", "func (a *AzureInfoer) GetCpuAttrName() string {\n\treturn productinfo.Cpu\n}", "func (s *PerProcessStat) CPUUsage() float64 {\n\to := s.Metrics\n\trateNs := o.UserTime.ComputeRate() + o.SystemTime.ComputeRate()\n\treturn (rateNs / float64(nanoSecond))\n}", "func TestCpuInfo(t *testing.T) {\n\texpected := []cpu.InfoStat{}\n\tactual, _ := cpu.Info()\n\n\tassert.IsType(t, expected, actual, \"`cpuInfo()` should return a []cpu.InfoStat slice\")\n}", "func (m *CoreDNSConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (o FunctionServiceConfigOutput) AvailableCpu() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FunctionServiceConfig) *string { return v.AvailableCpu }).(pulumi.StringPtrOutput)\n}", "func GetCPUUsage()int{\n\t// Loop not run, launch it\n\tif cpuStatsRun == false {\n\t\tcpuStatsRun = true\n\t\tgo runCPUUsageStats()\n\t}\n\treturn currentUsage\n}", "func (sys *System) GetProfileCPU(ctx *Context, stop bool) (prof []byte, err error) {\n\tLog(INFO, ctx, \"System.GetProfileCPU\")\n\tsys.Lock()\n\tif nil == sys.ProfCPUFile {\n\t\terr = fmt.Errorf(\"no cpu profile available\")\n\t\tLog(ERROR, ctx, \"System.GetProfileCPU\", \"error\", err)\n\t} else {\n\t\tsys.stopProfiling(ctx)\n\t\tprof, err = ioutil.ReadFile(ProfCPUFileName)\n\t\tif !stop {\n\t\t\tsys.startProfiling(ctx)\n\t\t}\n\t\tif err != nil {\n\t\t\tLog(ERROR, ctx, \"System.GetProfileCPU\", \"error\", err, \"when\", \"readfile\")\n\t\t}\n\t}\n\tsys.Unlock()\n\n\treturn prof, err\n}", "func (s *Stats) GetCPUTimes() {\n\n if s.CPUInfo == nil {\n s.CPUInfo = new(CPUInfo)\n }\n\n s.CPUInfo.PrevCPUTimes = s.CPUInfo.PerCPUTimes\n s.CPUInfo.PerCPUTimes, _ = cpu.Times(true)\n\n if len(s.CPUInfo.PrevCPUTimes) == 0 {\n s.CPUInfo.PrevCPUTimes = s.CPUInfo.PerCPUTimes\n }\n}", "func GetSysCPUCount() int {\n\treturn runtime.NumCPU()\n}", "func (o *HostMetrics) GetCpuOk() (*float64, bool) {\n\tif o == nil || o.Cpu == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Cpu, true\n}", "func CPUCount() int {\n\treturn int(C.al_get_cpu_count())\n}", "func (sysload *SystemLoad) GetCPULoad(cpu int) (int, int, int) {\n\tif cpu > len(sysload.cpusLoad) {\n\t\treturn 0, 0, 0\n\t}\n\n\tload := sysload.cpusLoad[cpu].stat.load()\n\tidle := sysload.cpusLoad[cpu].stat.idle()\n\tirq := sysload.cpusLoad[cpu].stat.irq()\n\treturn load, idle, irq\n}", "func (o FunctionServiceConfigPtrOutput) AvailableCpu() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FunctionServiceConfig) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.AvailableCpu\n\t}).(pulumi.StringPtrOutput)\n}", "func cpuUsage() (int64, error) {\n\tcmd := exec.Command(\"ps\", \"aux\")\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tcurrentPID := os.Getpid()\n\tfor {\n\t\tline, err := out.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttokens := strings.Split(line, \" \")\n\t\tvar ft []string\n\t\tfor _, t := range tokens {\n\t\t\tif t != \"\" && t != \"\\t\" {\n\t\t\t\tft = append(ft, t)\n\t\t\t}\n\t\t}\n\t\tpid, err := strconv.Atoi(ft[1])\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif pid != currentPID {\n\t\t\tcontinue\n\t\t}\n\t\tcpu, err := strconv.ParseFloat(ft[2], 64)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn int64(cpu), nil\n\t}\n\treturn 0, errors.New(\"no cpu info found\")\n}", "func ProcInfo() ([]Win32_PerfFormattedData_PerfOS_System, error) {\n\treturn ProcInfoWithContext(context.Background())\n}", "func (o *ApplianceSetupInfoAllOf) GetMinCpu() int64 {\n\tif o == nil || o.MinCpu == nil {\n\t\tvar ret int64\n\t\treturn ret\n\t}\n\treturn *o.MinCpu\n}", "func (r *NetlinkReader) GetCpuLoad(name string, path string) (info.LoadStats, error) {\n\tif len(path) == 0 {\n\t\treturn info.LoadStats{}, fmt.Errorf(\"cgroup path can not be empty\")\n\t}\n\n\tcfd, err := os.Open(path)\n\tif err != nil {\n\t\treturn info.LoadStats{}, fmt.Errorf(\"failed to open cgroup path %s: %q\", path, err)\n\t}\n\tdefer cfd.Close()\n\n\tstats, err := getLoadStats(r.familyID, cfd, r.conn)\n\tif err != nil {\n\t\treturn info.LoadStats{}, err\n\t}\n\tklog.V(4).Infof(\"Task stats for %q: %+v\", path, stats)\n\treturn stats, nil\n}", "func (m *MixerTelemetryConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *MixerTelemetryConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *MixerTelemetryConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *MixerTelemetryConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *MixerTelemetryConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *MixerTelemetryConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *MixerTelemetryConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (o RegistryTaskAgentSettingOutput) Cpu() pulumi.IntOutput {\n\treturn o.ApplyT(func(v RegistryTaskAgentSetting) int { return v.Cpu }).(pulumi.IntOutput)\n}", "func parseCPUStat(line string) (CPUStat, int64, error) {\n\tcpuStat := CPUStat{}\n\tvar cpu string\n\n\tcount, err := fmt.Sscanf(line, \"%s %f %f %f %f %f %f %f %f %f %f\",\n\t\t&cpu,\n\t\t&cpuStat.User, &cpuStat.Nice, &cpuStat.System, &cpuStat.Idle,\n\t\t&cpuStat.Iowait, &cpuStat.IRQ, &cpuStat.SoftIRQ, &cpuStat.Steal,\n\t\t&cpuStat.Guest, &cpuStat.GuestNice)\n\n\tif err != nil && err != io.EOF {\n\t\treturn CPUStat{}, -1, fmt.Errorf(\"couldn't parse %q (cpu): %w\", line, err)\n\t}\n\tif count == 0 {\n\t\treturn CPUStat{}, -1, fmt.Errorf(\"couldn't parse %q (cpu): 0 elements parsed\", line)\n\t}\n\n\tcpuStat.User /= userHZ\n\tcpuStat.Nice /= userHZ\n\tcpuStat.System /= userHZ\n\tcpuStat.Idle /= userHZ\n\tcpuStat.Iowait /= userHZ\n\tcpuStat.IRQ /= userHZ\n\tcpuStat.SoftIRQ /= userHZ\n\tcpuStat.Steal /= userHZ\n\tcpuStat.Guest /= userHZ\n\tcpuStat.GuestNice /= userHZ\n\n\tif cpu == \"cpu\" {\n\t\treturn cpuStat, -1, nil\n\t}\n\n\tcpuID, err := strconv.ParseInt(cpu[3:], 10, 64)\n\tif err != nil {\n\t\treturn CPUStat{}, -1, fmt.Errorf(\"couldn't parse %q (cpu/cpuid): %w\", line, err)\n\t}\n\n\treturn cpuStat, cpuID, nil\n}", "func Collectcpu(serverName string) (Metric, error) {\n\tvalues := Metric{}\n\tvar err error\n\tvalues.Timestamp = time.Now()\n\tvalues.MetricType = \"cpu\"\n\n\tvar response cpmserverapi.MetricCPUResponse\n\trequest := &cpmserverapi.MetricCPURequest{}\n\tresponse, err = cpmserverapi.MetricCPUClient(serverName, request)\n\tif err != nil {\n\t\tlogit.Error.Println(\"cpu metric error:\" + err.Error())\n\t\treturn values, err\n\t}\n\n\tvar output = strings.TrimSpace(response.Output)\n\n\tvalues.Value, err = strconv.ParseFloat(output, 64)\n\tif err != nil {\n\t\tlogit.Error.Println(\"parseFloat error in cpu metric \" + err.Error())\n\t}\n\n\treturn values, err\n}", "func (m *IngressGatewayConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *IngressGatewayConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *IngressGatewayConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *IngressGatewayConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *IngressGatewayConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *IngressGatewayConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *IngressGatewayConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *IngressGatewayConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *IngressGatewayConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (l *Load) CPU() float32 {\n\tx := atomic.LoadUint32(&l.currentCPULoad)\n\n\tx1 := math.Float32frombits(x)\n\treturn x1\n}", "func getCpuMem() (float64, float64) {\n\tvar sumCPU, sumMEM float64\n\tcmd := exec.Command(\"ps\", \"aux\") // ps aux is the command used to get cpu and ram usage\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out //catching the command output\n\terr := cmd.Run() //running the command\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor {\n\t\tline, err := out.ReadString('\\n') //breaking the output in lines\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\ttokens := strings.Split(line, \" \") //spliting each output line\n\t\tft := make([]string, 0)\n\t\tfor _, t := range tokens {\n\t\t\tif t != \"\" && t != \"\\t\" {\n\t\t\t\tft = append(ft, t) //for each line there is a buffer (ft) that keeps all the parameters\n\t\t\t}\n\t\t}\n\t\tif cpu, err := strconv.ParseFloat(ft[2], 32); err == nil { // parsing the cpu variable, as string, to float\n\t\t\tsumCPU += cpu //all the cpu's used capacity at the instant\n\t\t}\n\t\tif mem, err := strconv.ParseFloat(ft[3], 32); err == nil { // parsing the ram variable, as string, to float\n\t\t\tsumMEM += mem //all the ram's used capacity at the instant\n\t\t}\n\t}\n\tlog.Println(\"Used CPU\", sumCPU/8, \"%\", \" Used Memory RAM\", sumMEM, \"%\")\n\treturn sumCPU / 8, sumMEM //the cpu's total used capacity is splitted by 8 because its the total number of my PC's cores\n\t//otherwise, we would see outputs bigger than 100%\n}", "func TestJoeFridayGetCPUInfo(t *testing.T) {\n\tprof, err := cpuinfo.NewProfiler()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tinf, err := prof.Get()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tp, err := json.MarshalIndent(inf, \"\", \"\\t\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Logf(\"%s\\n\", string(p))\n}", "func GetCPUTimeStat(rw http.ResponseWriter) error {\n\tcpus, err := cpu.Times(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn share.JSONResponse(cpus, rw)\n}", "func GetCPUAndNode() (cpu int, node int) {\n\tcpu = runtime_procPin()\n\truntime_procUnpin()\n\treturn cpu % ncpumax, nnodemax - 1\n}", "func (o *ClusterRequest) GetCpu() float32 {\n\tif o == nil || o.Cpu == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\treturn *o.Cpu\n}", "func TestParseCpuinfoForIntBasic(t *testing.T) {\n\n\tcontent, err := ioutil.ReadFile(\"../test_resources/cpuinfo\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ts := string(content)\n\n\tcores, _ := parseCpuinfoForInt(&s, \"cpu cores\")\n\n\tif cores != 10 {\n\t\tt.Errorf(\"num cores returned unexpected: got %d want %d\",\n\t\t\tcores, 10)\n\t}\n}", "func (o AtlasMapSpecOutput) RequestCPU() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AtlasMapSpec) *string { return v.RequestCPU }).(pulumi.StringPtrOutput)\n}", "func (o *Vm) GetCpu() float32 {\n\tif o == nil || o.Cpu == nil {\n\t\tvar ret float32\n\t\treturn ret\n\t}\n\treturn *o.Cpu\n}", "func CPUInfoReader() (*trdsql.SliceReader, error) {\n\tv, err := cpu.Info()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn trdsql.NewSliceReader(psCPUInfo, v), nil\n}", "func GetCpuUsage() ([]float64, error) {\n\n currProcStat := getProcStats()\n usage := make([]float64, len(currProcStat))\n for i := 0; i < len(currProcStat); i++ {\n\n // Get Difference\n dIdle := float64(currProcStat[i].GetIdle() - prevProcStat[i].GetIdle())\n dTotal := float64(currProcStat[i].GetTotal() - prevProcStat[i].GetTotal())\n\n // Get Usage\n usage[i] = (dTotal - dIdle) / dTotal * 100.0\n\n }\n\n // Assign Previous Value\n prevProcStat = currProcStat\n return usage, nil\n}", "func (c *ironwareCommunicator) GetCPUComponentCPULoad(ctx context.Context) ([]float64, error) {\n\tcon, ok := network.DeviceConnectionFromContext(ctx)\n\tif !ok || con.SNMP == nil {\n\t\treturn nil, errors.New(\"no device connection available\")\n\t}\n\tresponses, err := con.SNMP.SnmpClient.SNMPWalk(ctx, \".1.3.6.1.4.1.1991.1.1.2.11.1.1.5\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"snmpwalk failed\")\n\t}\n\tvar cpus []float64\n\tfor _, response := range responses {\n\t\tif !strings.HasSuffix(response.GetOID(), \"300\") {\n\t\t\tcontinue\n\t\t}\n\t\tvalueString, err := response.GetValueString()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"couldn't get string value\")\n\t\t}\n\t\tvalue, err := strconv.ParseFloat(valueString, 64)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to parse snmp response\")\n\t\t}\n\t\tcpus = append(cpus, value)\n\t}\n\treturn cpus, nil\n}", "func (o RegistryTaskAgentSettingPtrOutput) Cpu() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *RegistryTaskAgentSetting) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Cpu\n\t}).(pulumi.IntPtrOutput)\n}", "func (o *Vm) GetCpuOk() (*float32, bool) {\n\tif o == nil || o.Cpu == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Cpu, true\n}", "func (m *PilotConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *PilotConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *PilotConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *PilotConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *PilotConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *PilotConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *PilotConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *PilotConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func (m *PilotConfig) GetCpu() *CPUTargetUtilizationConfig {\n\tif m != nil {\n\t\treturn m.Cpu\n\t}\n\treturn nil\n}", "func GetCpuFreq() uint64 {\n\tlines, err := pyfile.ReadAllLines(\"/proc/cpuinfo\")\n\tif err != nil {\n\t\treturn 0\n\t}\n\tfor _, line := range lines {\n\t\tarray := strings.Split(line, \":\")\n\t\tif len(array) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tkey := strings.TrimSpace(array[0])\n\t\tvalue := strings.TrimSpace(array[1])\n\t\tif key == \"cpu MHz\" {\n\t\t\tif t, err := strconv.ParseFloat(strings.Replace(value, \"MHz\", \"\", 1), 64); err == nil {\n\t\t\t\treturn uint64(t * 1000.0 * 1000.0)\n\t\t\t}\n\t\t}\n\t}\n\treturn 0\n}", "func (o *ClusterRequest) GetCpuOk() (*float32, bool) {\n\tif o == nil || o.Cpu == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Cpu, true\n}", "func CPUUsage() (idle float64, e error) {\n\tvar ps []float64\n\tps, e = cpu.Percent(0, false)\n\tif e != nil {\n\t\treturn\n\t}\n\treturn ps[0], e\n}", "func (o AtlasMapSpecPtrOutput) RequestCPU() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AtlasMapSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.RequestCPU\n\t}).(pulumi.StringPtrOutput)\n}", "func currCPUUse() int {\n\trawData, err := ioutil.ReadFile(\"/proc/stat\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdata := string(rawData)\n\tcpuData := strings.Fields(strings.Split(data, \"\\n\")[0]) // CPU is the 1st line\n\tif cpuData[0] != \"cpu\" {\n\t\tlog.Fatal(\"Incorrectly parsed `/proc/stat`\")\n\t}\n\tvar total, idle float64\n\tfor i, v := range cpuData[1:] {\n\t\tval, err := strconv.ParseFloat(v, 64)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\ttotal += val\n\t\tif i == 3 { // 4th field is idle\n\t\t\tidle = val\n\t\t}\n\t}\n\treturn int(100 * ((total - idle) / total))\n}", "func ProcStat(c *gin.Context) {\n\tres := CmdExec(\"cat /proc/stat | head -n 1 | awk '{$1=\\\"\\\";print}'\")\n\tresArray := strings.Split(res[0], \" \")\n\tvar cpu []int64\n\tvar totalcpu, idlecpu int64\n\tfor _, v := range resArray {\n\t\ttemp, err := strconv.ParseInt(v, 10, 64)\n\t\tif err == nil {\n\t\t\tcpu = append(cpu, temp)\n\t\t\ttotalcpu = totalcpu + temp\n\t\t}\n\t}\n\tidlecpu = cpu[3]\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"totalcpu\": totalcpu,\n\t\t\"idlecpu\": idlecpu,\n\t})\n}", "func (cg *CGroup) GetCPUAcctUsageAll() (map[int64]CPUStats, error) {\n\tout := map[int64]CPUStats{}\n\n\tversion := cgControllers[\"cpuacct\"]\n\tswitch version {\n\tcase V1:\n\t\tval, err := cg.rw.Get(version, \"cpuacct\", \"cpuacct.usage_all\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tscanner := bufio.NewScanner(strings.NewReader(val))\n\n\t\tfor scanner.Scan() {\n\t\t\tfields := strings.Fields(scanner.Text())\n\n\t\t\t// Skip header\n\t\t\tif fields[0] == \"cpu\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tstats := CPUStats{}\n\n\t\t\tcpuID, err := strconv.ParseInt(fields[0], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Failed parsing %q: %w\", fields[0], err)\n\t\t\t}\n\n\t\t\tstats.User, err = strconv.ParseInt(fields[1], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Failed parsing %q: %w\", fields[0], err)\n\t\t\t}\n\n\t\t\tstats.System, err = strconv.ParseInt(fields[2], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Failed parsing %q: %w\", fields[0], err)\n\t\t\t}\n\n\t\t\tout[cpuID] = stats\n\t\t}\n\n\t\treturn out, nil\n\t}\n\n\t// Handle cgroups v2\n\tversion = cgControllers[\"cpu\"]\n\tswitch version {\n\tcase Unavailable:\n\t\treturn nil, ErrControllerMissing\n\tcase V2:\n\t\tval, err := cg.rw.Get(version, \"cpu\", \"cpu.stat\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstats := CPUStats{}\n\n\t\tscanner := bufio.NewScanner(strings.NewReader(val))\n\n\t\tfor scanner.Scan() {\n\t\t\tfields := strings.Fields(scanner.Text())\n\n\t\t\tswitch fields[0] {\n\t\t\tcase \"user_usec\":\n\t\t\t\tval, err := strconv.ParseInt(fields[1], 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Failed parsing %q: %w\", val, err)\n\t\t\t\t}\n\n\t\t\t\t// Convert usec to nsec\n\t\t\t\tstats.User = val * 1000\n\t\t\tcase \"system_usec\":\n\t\t\t\tval, err := strconv.ParseInt(fields[1], 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Failed parsing %q: %w\", val, err)\n\t\t\t\t}\n\n\t\t\t\t// Convert usec to nsec\n\t\t\t\tstats.System = val * 1000\n\t\t\t}\n\t\t}\n\n\t\t// Use CPU ID 0 here as cgroup v2 doesn't show the usage of separate CPUs.\n\t\tout[0] = stats\n\n\t\treturn out, nil\n\t}\n\n\treturn nil, ErrUnknownVersion\n}", "func (s *Stats) GetTotalCPUTimes() {\n\n if s.CPUInfo == nil {\n s.CPUInfo = new(CPUInfo)\n }\n\n s.CPUInfo.PrevTotalTimes = s.CPUInfo.TotalTimes\n s.CPUInfo.TotalTimes, _ = cpu.Times(false)\n\n if len(s.CPUInfo.PrevTotalTimes) == 0 {\n s.CPUInfo.PrevTotalTimes = s.CPUInfo.TotalTimes\n }\n}" ]
[ "0.78435516", "0.77686065", "0.75853837", "0.7222646", "0.718413", "0.7149646", "0.7146789", "0.7026387", "0.6978236", "0.67174673", "0.6629169", "0.65276617", "0.6524987", "0.6483721", "0.644528", "0.64240366", "0.6423062", "0.6414883", "0.6402341", "0.63637906", "0.6331547", "0.6291099", "0.62500876", "0.62040305", "0.6197353", "0.6177968", "0.6170155", "0.6166282", "0.61419797", "0.6138331", "0.61198616", "0.6108911", "0.61075145", "0.6098314", "0.6094289", "0.6090894", "0.60834247", "0.6074496", "0.6070566", "0.60697246", "0.6036301", "0.6005299", "0.59929067", "0.59912467", "0.5983292", "0.5968687", "0.59476393", "0.5915035", "0.59098166", "0.59020346", "0.58974874", "0.58974874", "0.58974874", "0.58974874", "0.58974874", "0.58974874", "0.58974874", "0.5892113", "0.5879309", "0.58730865", "0.5862899", "0.5862899", "0.5862899", "0.5862899", "0.5862899", "0.5862899", "0.5862899", "0.5862899", "0.5862899", "0.5859478", "0.58551425", "0.58548164", "0.5854381", "0.5831399", "0.5822991", "0.5795116", "0.57945466", "0.5790898", "0.5787831", "0.57796663", "0.57728875", "0.5772294", "0.57558316", "0.57502687", "0.57502687", "0.57502687", "0.57502687", "0.57502687", "0.57502687", "0.57502687", "0.57502687", "0.57502687", "0.5748106", "0.5725048", "0.57108665", "0.5698455", "0.5697073", "0.5690479", "0.5688195", "0.56813306" ]
0.817543
0
Deprecated: Use PbStatsSampleFeed.ProtoReflect.Descriptor instead.
func (*PbStatsSampleFeed) Descriptor() ([]byte, []int) { return file_stats_proto_rawDescGZIP(), []int{0} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*Sample) Descriptor() ([]byte, []int) {\n\treturn file_alameda_api_v1alpha1_datahub_common_metrics_proto_rawDescGZIP(), []int{0}\n}", "func (*RateLimitingSampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{4}\n}", "func (*PbStatsSampleEntry) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{1}\n}", "func (*PbStatsSampleValue) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{2}\n}", "func (*RateLimitingSampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{3}\n}", "func (*StatsPayload) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{0}\n}", "func (*FeedbackMetrics) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{12}\n}", "func (*ProbabilitySampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{2}\n}", "func (*ConstantSampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{3}\n}", "func (*PbStatsIndexFeed) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{4}\n}", "func (*ProbabilitySampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{1}\n}", "func (*RateLimitingSampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{3}\n}", "func (*SampledData) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{37}\n}", "func (*ConstantSampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{2}\n}", "func (*ClientStatsPayload) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{1}\n}", "func (*KafkaMeter) Descriptor() ([]byte, []int) {\n\treturn file_pkg_sinks_plugin_proto_metrics_proto_rawDescGZIP(), []int{0}\n}", "func (*TelemetryParams) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{62}\n}", "func (*Stats) Descriptor() ([]byte, []int) {\n\treturn file_ligato_configurator_statspoller_proto_rawDescGZIP(), []int{0}\n}", "func (*Instant) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{7}\n}", "func (*BaseMetrics) Descriptor() ([]byte, []int) {\n\treturn file_mitre_cvss_v3_cvss_proto_rawDescGZIP(), []int{0}\n}", "func (*LoadBalancerStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_test_proto_rawDescGZIP(), []int{9}\n}", "func (*Metrics) Descriptor() ([]byte, []int) {\n\treturn file_grpc_proto_rawDescGZIP(), []int{0}\n}", "func (*GetStatsResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{45}\n}", "func (*ProbabilitySampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{2}\n}", "func (*PollStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_ligato_configurator_statspoller_proto_rawDescGZIP(), []int{1}\n}", "func (*MemberStatisticsInfoData) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{102}\n}", "func (*TrialProfilerMetricsBatch) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{4}\n}", "func (*NetRateTalker) Descriptor() ([]byte, []int) {\n\treturn file_pkg_smgrpc_smgrpc_proto_rawDescGZIP(), []int{2}\n}", "func ProtoFromDescriptor(d protoreflect.Descriptor) proto.Message {\n\tswitch d := d.(type) {\n\tcase protoreflect.FileDescriptor:\n\t\treturn ProtoFromFileDescriptor(d)\n\tcase protoreflect.MessageDescriptor:\n\t\treturn ProtoFromMessageDescriptor(d)\n\tcase protoreflect.FieldDescriptor:\n\t\treturn ProtoFromFieldDescriptor(d)\n\tcase protoreflect.OneofDescriptor:\n\t\treturn ProtoFromOneofDescriptor(d)\n\tcase protoreflect.EnumDescriptor:\n\t\treturn ProtoFromEnumDescriptor(d)\n\tcase protoreflect.EnumValueDescriptor:\n\t\treturn ProtoFromEnumValueDescriptor(d)\n\tcase protoreflect.ServiceDescriptor:\n\t\treturn ProtoFromServiceDescriptor(d)\n\tcase protoreflect.MethodDescriptor:\n\t\treturn ProtoFromMethodDescriptor(d)\n\tdefault:\n\t\t// WTF??\n\t\tif res, ok := d.(DescriptorProtoWrapper); ok {\n\t\t\treturn res.AsProto()\n\t\t}\n\t\treturn nil\n\t}\n}", "func (*Telemetry) Descriptor() ([]byte, []int) {\n\treturn file_huawei_telemetry_proto_rawDescGZIP(), []int{0}\n}", "func (*TestStreamPayload) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{22}\n}", "func (*GetStatisticsBroadcastRequest) Descriptor() ([]byte, []int) {\n\treturn file_services_core_protobuf_servers_proto_rawDescGZIP(), []int{2}\n}", "func (*TraceProto) Descriptor() ([]byte, []int) {\n\treturn file_internal_tracing_extended_extended_trace_proto_rawDescGZIP(), []int{0}\n}", "func (StandardPTransforms_DeprecatedPrimitives) EnumDescriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{4, 1}\n}", "func (*NetProtoTalker) Descriptor() ([]byte, []int) {\n\treturn file_pkg_smgrpc_smgrpc_proto_rawDescGZIP(), []int{1}\n}", "func (*LoadStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_envoy_service_load_stats_v3_lrs_proto_rawDescGZIP(), []int{0}\n}", "func (*Example) Descriptor() ([]byte, []int) {\n\treturn file_google_ai_generativelanguage_v1beta2_discuss_service_proto_rawDescGZIP(), []int{4}\n}", "func (*BasicStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{23}\n}", "func (*ConstSampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{1}\n}", "func (*TrafficSplitStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{25}\n}", "func (*Ping) Descriptor() ([]byte, []int) {\n\treturn file_api_protobuf_spec_example_example_proto_rawDescGZIP(), []int{5}\n}", "func (*Module) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{3}\n}", "func (*Telemetry) Descriptor() ([]byte, []int) {\n\treturn file_protocol_proto_rawDescGZIP(), []int{0}\n}", "func (*Message6024) Descriptor() ([]byte, []int) {\n\treturn file_datasets_google_message4_benchmark_message4_2_proto_rawDescGZIP(), []int{26}\n}", "func (*Listen) Descriptor() ([]byte, []int) {\n\treturn file_pkg_smgrpc_smgrpc_proto_rawDescGZIP(), []int{4}\n}", "func (*DatasetStatistics) Descriptor() ([]byte, []int) {\n\treturn file_asgt_type_dataset_statistics_proto_rawDescGZIP(), []int{0}\n}", "func (*PatchCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{161}\n}", "func (*MemberStatisticsInfoUpdateResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{105}\n}", "func (*TargetMetrics) Descriptor() ([]byte, []int) {\n\treturn file_asgt_type_target_metrics_proto_rawDescGZIP(), []int{0}\n}", "func (*GetStatisticsBroadcastResponse) Descriptor() ([]byte, []int) {\n\treturn file_services_core_protobuf_servers_proto_rawDescGZIP(), []int{3}\n}", "func (*Timing) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{40}\n}", "func (*TestStreamPayload_TimestampedElement) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{22, 1}\n}", "func (*Message12796) Descriptor() ([]byte, []int) {\n\treturn file_datasets_google_message4_benchmark_message4_2_proto_rawDescGZIP(), []int{1}\n}", "func (*MemberStatisticsInfoUpdateReq) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{104}\n}", "func (*OnTargetAudienceMetrics) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{19}\n}", "func (*MetricsReport) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{9}\n}", "func (*Message6127) Descriptor() ([]byte, []int) {\n\treturn file_datasets_google_message4_benchmark_message4_2_proto_rawDescGZIP(), []int{24}\n}", "func (*DynamicSampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{5}\n}", "func (*Performance) Descriptor() ([]byte, []int) {\n\treturn file_commissionService_proto_rawDescGZIP(), []int{2}\n}", "func (*CMatchTeamTimedStats) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{10}\n}", "func (*TrialSourceInfoMetric) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{11}\n}", "func (*AdaptiveSampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{4}\n}", "func (*Deprecation) Descriptor() ([]byte, []int) {\n\treturn file_external_cfgmgmt_response_nodes_proto_rawDescGZIP(), []int{8}\n}", "func (*MetricsRequest) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{11}\n}", "func (*OneofSample) Descriptor() ([]byte, []int) {\n\treturn file_examples_documents_example_proto_rawDescGZIP(), []int{20}\n}", "func (*Span_Link) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 3}\n}", "func (*FormatMessage) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_clouddebugger_v2_data_proto_rawDescGZIP(), []int{0}\n}", "func (*MemberStatisticsInfoAddResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{100}\n}", "func (*MetricsServiceRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{18}\n}", "func (*StandardProtocols) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{54}\n}", "func (*LabelledPayload) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{59}\n}", "func (*ExternalPayload) Descriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{53}\n}", "func (*TargetMetrics_Metric) Descriptor() ([]byte, []int) {\n\treturn file_asgt_type_target_metrics_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*CLRMetric) Descriptor() ([]byte, []int) {\n\treturn file_language_agent_CLRMetric_proto_rawDescGZIP(), []int{1}\n}", "func (*SubscriberQuotaUpdate) Descriptor() ([]byte, []int) {\n\treturn file_pipelined_proto_rawDescGZIP(), []int{14}\n}", "func (*Counts) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_analysis_internal_changepoints_proto_output_buffer_proto_rawDescGZIP(), []int{2}\n}", "func (*BaseScore) Descriptor() ([]byte, []int) {\n\treturn file_mitre_cvss_v3_cvss_proto_rawDescGZIP(), []int{3}\n}", "func (*LoadBalancerStatsResponse) Descriptor() ([]byte, []int) {\n\treturn file_grpc_test_proto_rawDescGZIP(), []int{10}\n}", "func (*Simple) Descriptor() ([]byte, []int) {\n\treturn file_config_module_featureflag_v1_featureflag_proto_rawDescGZIP(), []int{0}\n}", "func (*Profile) Descriptor() ([]byte, []int) {\n\treturn file_examplepb_example_proto_rawDescGZIP(), []int{7}\n}", "func (*TelemetryPacket) Descriptor() ([]byte, []int) {\n\treturn file_protocol_proto_rawDescGZIP(), []int{1}\n}", "func (*LoadAverage) Descriptor() ([]byte, []int) {\n\treturn file_pkg_smgrpc_smgrpc_proto_rawDescGZIP(), []int{5}\n}", "func (*TrialProfilerMetricLabels) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{3}\n}", "func (*ClientStatsBucket) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{2}\n}", "func (*PredictionValues) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{2}\n}", "func (*ApiWarning) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1_cloud_sql_resources_proto_rawDescGZIP(), []int{1}\n}", "func (*GoogleProfilerCF) Descriptor() ([]byte, []int) {\n\treturn file_pkg_kascfg_kascfg_proto_rawDescGZIP(), []int{12}\n}", "func (*PlanChange_Added) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_plan_change_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*Instance) Descriptor() ([]byte, []int) {\n\treturn file_cloudprovider_externalgrpc_protos_externalgrpc_proto_rawDescGZIP(), []int{28}\n}", "func (*Spend) Descriptor() ([]byte, []int) {\n\treturn file_recordwants_proto_rawDescGZIP(), []int{3}\n}", "func (*Score) Descriptor() ([]byte, []int) {\n\treturn file_mitre_cvss_v3_cvss_proto_rawDescGZIP(), []int{2}\n}", "func (*TimestampSeconds) Descriptor() ([]byte, []int) {\n\treturn file_proto_Timestamp_proto_rawDescGZIP(), []int{1}\n}", "func (*LoadStatsResponse) Descriptor() ([]byte, []int) {\n\treturn file_envoy_service_load_stats_v3_lrs_proto_rawDescGZIP(), []int{1}\n}", "func (*ServicesStatsRes) Descriptor() ([]byte, []int) {\n\treturn file_external_applications_applications_proto_rawDescGZIP(), []int{9}\n}", "func (*Metric) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_analysis_proto_v1_metrics_proto_rawDescGZIP(), []int{2}\n}", "func (*GetBalancerBandwidthResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{19}\n}", "func (TestInfo_Trend) EnumDescriptor() ([]byte, []int) {\n\treturn file_summary_proto_rawDescGZIP(), []int{1, 0}\n}", "func (*StatsEntry) Descriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{2}\n}", "func (*FeedbackRequest) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{10}\n}", "func (*ClrThread) Descriptor() ([]byte, []int) {\n\treturn file_language_agent_CLRMetric_proto_rawDescGZIP(), []int{3}\n}" ]
[ "0.688585", "0.6697076", "0.6658216", "0.6657251", "0.66076976", "0.6588843", "0.6540398", "0.646052", "0.64041436", "0.6333316", "0.6320216", "0.63077956", "0.6295664", "0.6284261", "0.6254959", "0.6246454", "0.6208883", "0.62084496", "0.6187565", "0.61792845", "0.6176941", "0.61614615", "0.6154143", "0.6149122", "0.61348104", "0.61297524", "0.6126196", "0.6116832", "0.6112504", "0.6098441", "0.6094025", "0.6087197", "0.60868776", "0.6072851", "0.6072364", "0.60580903", "0.6053214", "0.60474676", "0.6043258", "0.60400325", "0.60389924", "0.6032807", "0.6032145", "0.6029516", "0.6029494", "0.60267687", "0.6025677", "0.6020714", "0.6016095", "0.6014862", "0.601097", "0.5998996", "0.59862626", "0.59855527", "0.59849083", "0.59832674", "0.59829235", "0.5963005", "0.59629744", "0.59603184", "0.5950075", "0.59465516", "0.5938906", "0.593802", "0.5937412", "0.59357214", "0.5933395", "0.5931331", "0.5925108", "0.59242034", "0.592392", "0.5922321", "0.59163666", "0.5915441", "0.59141296", "0.59131104", "0.59120935", "0.5911528", "0.59087306", "0.5908066", "0.5906303", "0.59031904", "0.5901461", "0.5895514", "0.5888795", "0.5884543", "0.588407", "0.5882782", "0.58784485", "0.5876594", "0.5874337", "0.58734864", "0.5871705", "0.5868013", "0.5867697", "0.58664846", "0.5866196", "0.58620274", "0.5861722", "0.58600265" ]
0.71332276
0
Deprecated: Use PbStatsSampleEntry.ProtoReflect.Descriptor instead.
func (*PbStatsSampleEntry) Descriptor() ([]byte, []int) { return file_stats_proto_rawDescGZIP(), []int{1} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*PbStatsSampleValue) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{2}\n}", "func (*Sample) Descriptor() ([]byte, []int) {\n\treturn file_alameda_api_v1alpha1_datahub_common_metrics_proto_rawDescGZIP(), []int{0}\n}", "func (*PbStatsSampleFeed) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{0}\n}", "func (*RateLimitingSampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{4}\n}", "func (*RateLimitingSampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{3}\n}", "func (*StatsPayload) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{0}\n}", "func (*ProbabilitySampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{2}\n}", "func (*ConstantSampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{3}\n}", "func (*ProbabilitySampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{1}\n}", "func (*ConstantSampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{2}\n}", "func (*SampledData) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{37}\n}", "func (*StatsEntry) Descriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{2}\n}", "func (*ClientStatsPayload) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{1}\n}", "func (*RateLimitingSampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{3}\n}", "func (*LoadBalancerStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_test_proto_rawDescGZIP(), []int{9}\n}", "func (*GetStatsResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{45}\n}", "func (*ProbabilitySampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{2}\n}", "func (*DumpStatsEntry) Descriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{0}\n}", "func (*Span) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0}\n}", "func (*Stats) Descriptor() ([]byte, []int) {\n\treturn file_ligato_configurator_statspoller_proto_rawDescGZIP(), []int{0}\n}", "func (*FeedbackMetrics) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{12}\n}", "func (*ClientStatsBucket) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{2}\n}", "func (*KafkaMeter) Descriptor() ([]byte, []int) {\n\treturn file_pkg_sinks_plugin_proto_metrics_proto_rawDescGZIP(), []int{0}\n}", "func (*ConstSampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{1}\n}", "func (*TraceProto) Descriptor() ([]byte, []int) {\n\treturn file_internal_tracing_extended_extended_trace_proto_rawDescGZIP(), []int{0}\n}", "func (*LoadStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_envoy_service_load_stats_v3_lrs_proto_rawDescGZIP(), []int{0}\n}", "func (*MemberStatisticsInfoData) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{102}\n}", "func (*MemberStatisticsInfoUpdateReq) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{104}\n}", "func (*Metrics) Descriptor() ([]byte, []int) {\n\treturn file_grpc_proto_rawDescGZIP(), []int{0}\n}", "func (*Span_Link) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 3}\n}", "func (*BaseMetrics) Descriptor() ([]byte, []int) {\n\treturn file_mitre_cvss_v3_cvss_proto_rawDescGZIP(), []int{0}\n}", "func (*TrialSourceInfoMetric) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{11}\n}", "func (*MemberStatisticsInfoUpdateResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{105}\n}", "func ProtoFromDescriptor(d protoreflect.Descriptor) proto.Message {\n\tswitch d := d.(type) {\n\tcase protoreflect.FileDescriptor:\n\t\treturn ProtoFromFileDescriptor(d)\n\tcase protoreflect.MessageDescriptor:\n\t\treturn ProtoFromMessageDescriptor(d)\n\tcase protoreflect.FieldDescriptor:\n\t\treturn ProtoFromFieldDescriptor(d)\n\tcase protoreflect.OneofDescriptor:\n\t\treturn ProtoFromOneofDescriptor(d)\n\tcase protoreflect.EnumDescriptor:\n\t\treturn ProtoFromEnumDescriptor(d)\n\tcase protoreflect.EnumValueDescriptor:\n\t\treturn ProtoFromEnumValueDescriptor(d)\n\tcase protoreflect.ServiceDescriptor:\n\t\treturn ProtoFromServiceDescriptor(d)\n\tcase protoreflect.MethodDescriptor:\n\t\treturn ProtoFromMethodDescriptor(d)\n\tdefault:\n\t\t// WTF??\n\t\tif res, ok := d.(DescriptorProtoWrapper); ok {\n\t\t\treturn res.AsProto()\n\t\t}\n\t\treturn nil\n\t}\n}", "func (*PollStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_ligato_configurator_statspoller_proto_rawDescGZIP(), []int{1}\n}", "func (*Telemetry) Descriptor() ([]byte, []int) {\n\treturn file_huawei_telemetry_proto_rawDescGZIP(), []int{0}\n}", "func (*Timing) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{40}\n}", "func (*BasicStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{23}\n}", "func (*TimerInfo) Descriptor() ([]byte, []int) {\n\treturn file_grpc_proto_rawDescGZIP(), []int{0}\n}", "func (*Instant) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{7}\n}", "func (*CMatchTeamTimedStats) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{10}\n}", "func (*Module) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{3}\n}", "func (*OneofSample) Descriptor() ([]byte, []int) {\n\treturn file_examples_documents_example_proto_rawDescGZIP(), []int{20}\n}", "func (*TelemetryParams) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{62}\n}", "func (*MetricsReport) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{9}\n}", "func (*TargetMetrics) Descriptor() ([]byte, []int) {\n\treturn file_asgt_type_target_metrics_proto_rawDescGZIP(), []int{0}\n}", "func (*CMatchPlayerTimedStats) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{9}\n}", "func (*TrialProfilerMetricLabels) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{3}\n}", "func (*TrialProfilerMetricsBatch) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{4}\n}", "func (*Span_TimeEvents) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 2}\n}", "func (*LoadBalancerStatsResponse) Descriptor() ([]byte, []int) {\n\treturn file_grpc_test_proto_rawDescGZIP(), []int{10}\n}", "func (*Record) Descriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{1}\n}", "func (*RestoreStatsEntry) Descriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{1}\n}", "func (*Span_Attributes) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*LoadStatsResponse) Descriptor() ([]byte, []int) {\n\treturn file_envoy_service_load_stats_v3_lrs_proto_rawDescGZIP(), []int{1}\n}", "func (*NumericValue) Descriptor() ([]byte, []int) {\n\treturn file_google_analytics_admin_v1alpha_access_report_proto_rawDescGZIP(), []int{10}\n}", "func (*TrafficSplitStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{25}\n}", "func (StandardPTransforms_DeprecatedPrimitives) EnumDescriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{4, 1}\n}", "func (*Performance) Descriptor() ([]byte, []int) {\n\treturn file_commissionService_proto_rawDescGZIP(), []int{2}\n}", "func (Span_SpanKind) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*GetStatisticsBroadcastRequest) Descriptor() ([]byte, []int) {\n\treturn file_services_core_protobuf_servers_proto_rawDescGZIP(), []int{2}\n}", "func (StatusMessage_Reference) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_clouddebugger_v2_data_proto_rawDescGZIP(), []int{1, 0}\n}", "func (*CMsgClientToGCPlayerStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{143}\n}", "func (*DynamicSampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{5}\n}", "func (*AdaptiveSampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{4}\n}", "func (*DatasetStatistics) Descriptor() ([]byte, []int) {\n\treturn file_asgt_type_dataset_statistics_proto_rawDescGZIP(), []int{0}\n}", "func (*ApiWarning) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1_cloud_sql_resources_proto_rawDescGZIP(), []int{1}\n}", "func (*TimestampSeconds) Descriptor() ([]byte, []int) {\n\treturn file_proto_Timestamp_proto_rawDescGZIP(), []int{1}\n}", "func (*TrialMetrics) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{8}\n}", "func (Instant_Precision) EnumDescriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{7, 0}\n}", "func (*CMsgMapStatsSnapshot) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{90}\n}", "func (*ClientGroupedStats) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{3}\n}", "func (Span_Link_Type) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 3, 0}\n}", "func (ConstantSampler_ConstantDecision) EnumDescriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{2, 0}\n}", "func (*MemberStatisticsInfoAddResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{100}\n}", "func (*GetStatisticsBroadcastResponse) Descriptor() ([]byte, []int) {\n\treturn file_services_core_protobuf_servers_proto_rawDescGZIP(), []int{3}\n}", "func (*PbStatsIndexFeed) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{4}\n}", "func (*TcpStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{24}\n}", "func (*TrialSourceInfo) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{10}\n}", "func (*TargetMetrics_Metric) Descriptor() ([]byte, []int) {\n\treturn file_asgt_type_target_metrics_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*ApiWarning) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1beta4_cloud_sql_resources_proto_rawDescGZIP(), []int{1}\n}", "func (*Telemetry) Descriptor() ([]byte, []int) {\n\treturn file_protocol_proto_rawDescGZIP(), []int{0}\n}", "func (*MemberStatisticsInfoAddReq) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{99}\n}", "func (*GoogleProfilerCF) Descriptor() ([]byte, []int) {\n\treturn file_pkg_kascfg_kascfg_proto_rawDescGZIP(), []int{12}\n}", "func (*ScanRunWarningTrace) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_websecurityscanner_v1_scan_run_warning_trace_proto_rawDescGZIP(), []int{0}\n}", "func (Metric_Scale) EnumDescriptor() ([]byte, []int) {\n\treturn file_api_assessment_metric_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*Spend) Descriptor() ([]byte, []int) {\n\treturn file_recordwants_proto_rawDescGZIP(), []int{3}\n}", "func (*MetricsServiceRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{18}\n}", "func (*PActiveTraceHistogram) Descriptor() ([]byte, []int) {\n\treturn file_v1_Stat_proto_rawDescGZIP(), []int{15}\n}", "func (*Metric) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_analysis_proto_v1_metrics_proto_rawDescGZIP(), []int{2}\n}", "func (Type) EnumDescriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{0}\n}", "func (*SubscriberQuotaUpdate) Descriptor() ([]byte, []int) {\n\treturn file_pipelined_proto_rawDescGZIP(), []int{14}\n}", "func (NumberType) EnumDescriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{6}\n}", "func (*GetMetricsInfoResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{44}\n}", "func (*PlanChange_Added) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_plan_change_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*Span_TimeEvent) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 1}\n}", "func (SpanLayer) EnumDescriptor() ([]byte, []int) {\n\treturn file_common_trace_common_proto_rawDescGZIP(), []int{2}\n}", "func (*Message12796) Descriptor() ([]byte, []int) {\n\treturn file_datasets_google_message4_benchmark_message4_2_proto_rawDescGZIP(), []int{1}\n}", "func (*Ping) Descriptor() ([]byte, []int) {\n\treturn file_api_protobuf_spec_example_example_proto_rawDescGZIP(), []int{5}\n}", "func (*FormatMessage) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_clouddebugger_v2_data_proto_rawDescGZIP(), []int{0}\n}" ]
[ "0.68787944", "0.67939395", "0.66097397", "0.6603801", "0.65751487", "0.6460975", "0.64265966", "0.6382489", "0.635776", "0.6314068", "0.6217413", "0.6216349", "0.6167733", "0.6165071", "0.60689914", "0.60576195", "0.6048943", "0.6048222", "0.60278815", "0.6014108", "0.6000626", "0.59979695", "0.59868073", "0.5974604", "0.59733844", "0.5960978", "0.59580284", "0.592041", "0.59186864", "0.59123564", "0.590827", "0.5898552", "0.58869535", "0.5885035", "0.5878702", "0.5876595", "0.5874658", "0.58730805", "0.58611596", "0.58562976", "0.58527166", "0.5844677", "0.58422875", "0.58421224", "0.5833583", "0.58310205", "0.5818754", "0.5812384", "0.57987624", "0.57970923", "0.5794351", "0.57939005", "0.57931316", "0.5790388", "0.57833534", "0.57786185", "0.5777676", "0.5773525", "0.5773272", "0.57676077", "0.5764223", "0.57538563", "0.574995", "0.5747327", "0.5747152", "0.5743601", "0.57430315", "0.57425445", "0.5740064", "0.57393426", "0.5739128", "0.5738878", "0.5726463", "0.57238275", "0.5722045", "0.5718871", "0.5715227", "0.5709278", "0.5703404", "0.5702819", "0.569588", "0.5690308", "0.56890863", "0.5684266", "0.5684199", "0.5682781", "0.567911", "0.5676779", "0.5674471", "0.5673625", "0.56728643", "0.5671987", "0.56715703", "0.5670465", "0.56670344", "0.5665109", "0.5663038", "0.5662505", "0.5662328", "0.566189" ]
0.71390134
0
Deprecated: Use PbStatsSampleValue.ProtoReflect.Descriptor instead.
func (*PbStatsSampleValue) Descriptor() ([]byte, []int) { return file_stats_proto_rawDescGZIP(), []int{2} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*Sample) Descriptor() ([]byte, []int) {\n\treturn file_alameda_api_v1alpha1_datahub_common_metrics_proto_rawDescGZIP(), []int{0}\n}", "func (*PbStatsSampleEntry) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{1}\n}", "func (*RateLimitingSampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{4}\n}", "func (*RateLimitingSampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{3}\n}", "func (*StatsPayload) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{0}\n}", "func (*PbStatsSampleFeed) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{0}\n}", "func (*ConstantSampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{3}\n}", "func (*ProbabilitySampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{2}\n}", "func (*ConstantSampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{2}\n}", "func (*ProbabilitySampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{1}\n}", "func (*SampledData) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{37}\n}", "func (*ClientStatsPayload) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{1}\n}", "func (*NumericValue) Descriptor() ([]byte, []int) {\n\treturn file_google_analytics_admin_v1alpha_access_report_proto_rawDescGZIP(), []int{10}\n}", "func (*RateLimitingSampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{3}\n}", "func (*ProbabilitySampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{2}\n}", "func (*GetStatsResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{45}\n}", "func (*KafkaMeter) Descriptor() ([]byte, []int) {\n\treturn file_pkg_sinks_plugin_proto_metrics_proto_rawDescGZIP(), []int{0}\n}", "func (*ConstSampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{1}\n}", "func (*BaseMetrics) Descriptor() ([]byte, []int) {\n\treturn file_mitre_cvss_v3_cvss_proto_rawDescGZIP(), []int{0}\n}", "func (*TargetValue) Descriptor() ([]byte, []int) {\n\treturn file_packetbroker_api_iam_v1_service_proto_rawDescGZIP(), []int{7}\n}", "func (*Metrics) Descriptor() ([]byte, []int) {\n\treturn file_grpc_proto_rawDescGZIP(), []int{0}\n}", "func (*FeedbackMetrics) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{12}\n}", "func (*LoadBalancerStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_test_proto_rawDescGZIP(), []int{9}\n}", "func (*Stats) Descriptor() ([]byte, []int) {\n\treturn file_ligato_configurator_statspoller_proto_rawDescGZIP(), []int{0}\n}", "func (StandardPTransforms_DeprecatedPrimitives) EnumDescriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{4, 1}\n}", "func (*OneofSample) Descriptor() ([]byte, []int) {\n\treturn file_examples_documents_example_proto_rawDescGZIP(), []int{20}\n}", "func (*TargetMetrics) Descriptor() ([]byte, []int) {\n\treturn file_asgt_type_target_metrics_proto_rawDescGZIP(), []int{0}\n}", "func (*CLRMetric) Descriptor() ([]byte, []int) {\n\treturn file_language_agent_CLRMetric_proto_rawDescGZIP(), []int{1}\n}", "func (*SValues) Descriptor() ([]byte, []int) {\n\treturn file_internals_proto_select_proto_rawDescGZIP(), []int{1}\n}", "func (*PredictionValues) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{2}\n}", "func (*Timing) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{40}\n}", "func (*DoubleValue) Descriptor() ([]byte, []int) {\n\treturn file_proto_wrappers_proto_rawDescGZIP(), []int{0}\n}", "func (*TrialProfilerMetricLabels) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{3}\n}", "func (*ClientStatsBucket) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{2}\n}", "func (*TimestampSeconds) Descriptor() ([]byte, []int) {\n\treturn file_proto_Timestamp_proto_rawDescGZIP(), []int{1}\n}", "func (*TargetMetrics_Metric) Descriptor() ([]byte, []int) {\n\treturn file_asgt_type_target_metrics_proto_rawDescGZIP(), []int{0, 0}\n}", "func ProtoFromDescriptor(d protoreflect.Descriptor) proto.Message {\n\tswitch d := d.(type) {\n\tcase protoreflect.FileDescriptor:\n\t\treturn ProtoFromFileDescriptor(d)\n\tcase protoreflect.MessageDescriptor:\n\t\treturn ProtoFromMessageDescriptor(d)\n\tcase protoreflect.FieldDescriptor:\n\t\treturn ProtoFromFieldDescriptor(d)\n\tcase protoreflect.OneofDescriptor:\n\t\treturn ProtoFromOneofDescriptor(d)\n\tcase protoreflect.EnumDescriptor:\n\t\treturn ProtoFromEnumDescriptor(d)\n\tcase protoreflect.EnumValueDescriptor:\n\t\treturn ProtoFromEnumValueDescriptor(d)\n\tcase protoreflect.ServiceDescriptor:\n\t\treturn ProtoFromServiceDescriptor(d)\n\tcase protoreflect.MethodDescriptor:\n\t\treturn ProtoFromMethodDescriptor(d)\n\tdefault:\n\t\t// WTF??\n\t\tif res, ok := d.(DescriptorProtoWrapper); ok {\n\t\t\treturn res.AsProto()\n\t\t}\n\t\treturn nil\n\t}\n}", "func (*Value) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_resourcesettings_v1_resource_settings_proto_rawDescGZIP(), []int{2}\n}", "func (*BasicStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{23}\n}", "func (*TrialSourceInfoMetric) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{11}\n}", "func (Metric_Scale) EnumDescriptor() ([]byte, []int) {\n\treturn file_api_assessment_metric_proto_rawDescGZIP(), []int{0, 0}\n}", "func (Type) EnumDescriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{0}\n}", "func (ConstantSampler_ConstantDecision) EnumDescriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{2, 0}\n}", "func (*AllowedValues) Descriptor() ([]byte, []int) {\n\treturn file_api_assessment_metric_proto_rawDescGZIP(), []int{3}\n}", "func (*BaseScore) Descriptor() ([]byte, []int) {\n\treturn file_mitre_cvss_v3_cvss_proto_rawDescGZIP(), []int{3}\n}", "func (*LoadBalancerStatsResponse) Descriptor() ([]byte, []int) {\n\treturn file_grpc_test_proto_rawDescGZIP(), []int{10}\n}", "func (*SampleBitString) Descriptor() ([]byte, []int) {\n\treturn file_pkg_asn1_testsm_test_sm_proto_rawDescGZIP(), []int{32}\n}", "func (*Span) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0}\n}", "func (*CMatchTeamTimedStats) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{10}\n}", "func (*Metric) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_analysis_proto_v1_metrics_proto_rawDescGZIP(), []int{2}\n}", "func (*TypedValue) Descriptor() ([]byte, []int) {\n\treturn file_proto_gnmi_gnmi_proto_rawDescGZIP(), []int{2}\n}", "func (*DatasetStatistics) Descriptor() ([]byte, []int) {\n\treturn file_asgt_type_dataset_statistics_proto_rawDescGZIP(), []int{0}\n}", "func (*GetBalancerBandwidthResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{19}\n}", "func (NumberType) EnumDescriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{6}\n}", "func (*DynamicSampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{5}\n}", "func (*TrialProfilerMetricsBatch) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{4}\n}", "func (*Instant) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{7}\n}", "func (*AdaptiveSampling) Descriptor() ([]byte, []int) {\n\treturn file_dynamic_sampling_proto_rawDescGZIP(), []int{4}\n}", "func (*MetricsReport) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{9}\n}", "func (StatusMessage_Reference) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_clouddebugger_v2_data_proto_rawDescGZIP(), []int{1, 0}\n}", "func (*TelemetryParams) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{62}\n}", "func (*CMatchPlayerTimedStats) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{9}\n}", "func (GameSpeed) EnumDescriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{3}\n}", "func (*MaximizeConversionValue) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v14_common_bidding_proto_rawDescGZIP(), []int{7}\n}", "func (ConstantSampler_ConstantDecision) EnumDescriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{3, 0}\n}", "func (*Score) Descriptor() ([]byte, []int) {\n\treturn file_mitre_cvss_v3_cvss_proto_rawDescGZIP(), []int{2}\n}", "func (*MemberStatisticsInfoData) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{102}\n}", "func (*Performance) Descriptor() ([]byte, []int) {\n\treturn file_commissionService_proto_rawDescGZIP(), []int{2}\n}", "func (*TrialMetrics) Descriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{8}\n}", "func (*Value) Descriptor() ([]byte, []int) {\n\treturn file_ocis_messages_settings_v0_settings_proto_rawDescGZIP(), []int{13}\n}", "func (*TelemetryExpectation) Descriptor() ([]byte, []int) {\n\treturn file_testvector_tv_proto_rawDescGZIP(), []int{8}\n}", "func (TrialProfilerMetricLabels_ProfilerMetricType) EnumDescriptor() ([]byte, []int) {\n\treturn file_determined_trial_v1_trial_proto_rawDescGZIP(), []int{3, 0}\n}", "func (*TimerInfo) Descriptor() ([]byte, []int) {\n\treturn file_grpc_proto_rawDescGZIP(), []int{0}\n}", "func (*Telemetry) Descriptor() ([]byte, []int) {\n\treturn file_huawei_telemetry_proto_rawDescGZIP(), []int{0}\n}", "func (*LoadStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_envoy_service_load_stats_v3_lrs_proto_rawDescGZIP(), []int{0}\n}", "func (Instant_Precision) EnumDescriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{7, 0}\n}", "func (ContactPointUseCode_Value) EnumDescriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{49, 0}\n}", "func (*TrafficSplitStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{25}\n}", "func (*Value) Descriptor() ([]byte, []int) {\n\treturn file_proto_gnmi_gnmi_proto_rawDescGZIP(), []int{5}\n}", "func (*PollStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_ligato_configurator_statspoller_proto_rawDescGZIP(), []int{1}\n}", "func (Span_SpanKind) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*TraceProto) Descriptor() ([]byte, []int) {\n\treturn file_internal_tracing_extended_extended_trace_proto_rawDescGZIP(), []int{0}\n}", "func (*TelemetryThreshold) Descriptor() ([]byte, []int) {\n\treturn file_huawei_telemetry_proto_rawDescGZIP(), []int{5}\n}", "func (NameUseCode_Value) EnumDescriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{56, 0}\n}", "func (*ApiWarning) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1_cloud_sql_resources_proto_rawDescGZIP(), []int{1}\n}", "func (*TcpStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{24}\n}", "func (*Span_Attributes) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*TracePercentages) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_v1_options_tracing_tracing_proto_rawDescGZIP(), []int{2}\n}", "func (*TracePercentages) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_v1_options_tracing_tracing_proto_rawDescGZIP(), []int{2}\n}", "func (EventTimingCode_Value) EnumDescriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{51, 0}\n}", "func (*CMatchPlayerTimedCustomStat) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{8}\n}", "func ConvertProtoStatValue(in *proto.StatValue) *StatValue {\n\tif in == nil {\n\t\treturn nil\n\t}\n\n\treturn &StatValue{\n\t\tFloatNumeratorVal: unwrapDouble(in.FloatNumeratorVal),\n\t\tFloatDenominatorVal: unwrapDouble(in.FloatDenominatorVal),\n\t\tIntNumeratorVal: unwrapInt64(in.IntNumeratorVal),\n\t\tIntDenominatorVal: unwrapInt64(in.IntDenominatorVal),\n\t\tStringVal: unwrapString(in.StringVal),\n\t\tBoolVal: unwrapBool(in.BoolVal),\n\t\tUnit: in.Unit,\n\t\tDesc: in.Desc,\n\t}\n}", "func (*ClrThread) Descriptor() ([]byte, []int) {\n\treturn file_language_agent_CLRMetric_proto_rawDescGZIP(), []int{3}\n}", "func (*ClientGroupedStats) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{3}\n}", "func (*HealthinessStats) Descriptor() ([]byte, []int) {\n\treturn file_data_proto_rawDescGZIP(), []int{30}\n}", "func (*LoadStatsResponse) Descriptor() ([]byte, []int) {\n\treturn file_envoy_service_load_stats_v3_lrs_proto_rawDescGZIP(), []int{1}\n}", "func (*Extension_ValueX) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{41, 0}\n}", "func (*GetStatisticsBroadcastResponse) Descriptor() ([]byte, []int) {\n\treturn file_services_core_protobuf_servers_proto_rawDescGZIP(), []int{3}\n}", "func (*GetMetricsInfoResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{44}\n}", "func (EnumValue) EnumDescriptor() ([]byte, []int) {\n\treturn file_runtime_internal_examplepb_proto3_proto_rawDescGZIP(), []int{0}\n}" ]
[ "0.66029704", "0.64383894", "0.63857913", "0.6335666", "0.62955904", "0.6280039", "0.62591803", "0.62557894", "0.6178983", "0.6160721", "0.6110993", "0.6035262", "0.6015043", "0.6011451", "0.59461766", "0.591946", "0.59136045", "0.5894612", "0.5889398", "0.5886022", "0.5875402", "0.5864953", "0.58289474", "0.5828172", "0.58192027", "0.5818238", "0.58116835", "0.57957727", "0.5768231", "0.5767659", "0.5762323", "0.57543904", "0.5741355", "0.5737765", "0.5736927", "0.5736048", "0.5724721", "0.57189614", "0.57136136", "0.5713222", "0.57112455", "0.57028043", "0.56991553", "0.5694706", "0.56937546", "0.5692838", "0.5692444", "0.5683294", "0.5681344", "0.56768066", "0.56745625", "0.56719536", "0.5671068", "0.5667511", "0.5667015", "0.56634176", "0.5662836", "0.5656259", "0.56548077", "0.56544954", "0.56493163", "0.56472534", "0.56441104", "0.56435674", "0.564334", "0.5636138", "0.56354725", "0.5628828", "0.5626862", "0.56253165", "0.5621112", "0.561992", "0.5617062", "0.561273", "0.5602911", "0.55989516", "0.55920535", "0.5584925", "0.5581719", "0.5575279", "0.5575239", "0.5572416", "0.55662787", "0.55608594", "0.55556256", "0.55554426", "0.5552408", "0.55471855", "0.55471855", "0.55426997", "0.5540894", "0.5538716", "0.55373013", "0.5536861", "0.55340636", "0.5533074", "0.5525915", "0.55256176", "0.5523456", "0.55229586" ]
0.7226101
0
Deprecated: Use PbStatsIndexList.ProtoReflect.Descriptor instead.
func (*PbStatsIndexList) Descriptor() ([]byte, []int) { return file_stats_proto_rawDescGZIP(), []int{3} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*PbStatsIndexFeed) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{4}\n}", "func (*BulkIndexRequest) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{14}\n}", "func (*BulkIndexResponse) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{15}\n}", "func (*Index) Descriptor() ([]byte, []int) {\n\treturn file_index_faults_rpc_rpc_proto_rawDescGZIP(), []int{0}\n}", "func (*Stats) Descriptor() ([]byte, []int) {\n\treturn file_ligato_configurator_statspoller_proto_rawDescGZIP(), []int{0}\n}", "func (*List) Descriptor() ([]byte, []int) {\n\treturn file_proto_ssql_proto_rawDescGZIP(), []int{11}\n}", "func (*ClientStatsBucket) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{2}\n}", "func (*MemberStatisticsInfoListReq) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{101}\n}", "func (*Index) Descriptor() ([]byte, []int) {\n\treturn file_index_proto_rawDescGZIP(), []int{0}\n}", "func (*RateLimitingSampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{4}\n}", "func (*MemberStatisticsInfoListResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{103}\n}", "func (*RateLimitingSampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{3}\n}", "func (Index_HashFunc) EnumDescriptor() ([]byte, []int) {\n\treturn file_index_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*ListMetricsRequest) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_analysis_proto_v1_metrics_proto_rawDescGZIP(), []int{0}\n}", "func (*GetStatsResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{45}\n}", "func (*StatsPayload) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{0}\n}", "func (*ClientStatsPayload) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{1}\n}", "func (*BulkDeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{16}\n}", "func (*MetricsResponse) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{25}\n}", "func (*BulkDeleteResponse) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{17}\n}", "func (*LeaderboardList) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{50}\n}", "func (*ListMetricsResponse) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_analysis_proto_v1_metrics_proto_rawDescGZIP(), []int{1}\n}", "func (*Index) Descriptor() ([]byte, []int) {\n\treturn file_threads_proto_rawDescGZIP(), []int{5}\n}", "func (*TermIndexProto) Descriptor() ([]byte, []int) {\n\treturn file_raft_proto_rawDescGZIP(), []int{9}\n}", "func (*Cluster) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{4}\n}", "func (*BasicStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{23}\n}", "func (StatusMessage_Reference) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_clouddebugger_v2_data_proto_rawDescGZIP(), []int{1, 0}\n}", "func (Service_Health) EnumDescriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_clickhouse_v1_cluster_proto_rawDescGZIP(), []int{7, 1}\n}", "func (*QueryPlanStatusResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{25}\n}", "func (*ClientGroupedStats) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{3}\n}", "func (EValveIndexComponent) EnumDescriptor() ([]byte, []int) {\n\treturn file_steammessages_accounthardware_steamclient_proto_rawDescGZIP(), []int{0}\n}", "func (*PDataSourceList) Descriptor() ([]byte, []int) {\n\treturn file_v1_Stat_proto_rawDescGZIP(), []int{9}\n}", "func (*IndexValue) Descriptor() ([]byte, []int) {\n\treturn file_openfeed_proto_rawDescGZIP(), []int{23}\n}", "func (*MemberStatisticsInfoUpdateResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{105}\n}", "func (*EventsListProto) Descriptor() ([]byte, []int) {\n\treturn file_inotify_proto_rawDescGZIP(), []int{9}\n}", "func (NumberType) EnumDescriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{6}\n}", "func (*PortList) Descriptor() ([]byte, []int) {\n\treturn file_rpc_proto_rawDescGZIP(), []int{2}\n}", "func (*LoadBalancerStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_test_proto_rawDescGZIP(), []int{9}\n}", "func (GameSpeed) EnumDescriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{3}\n}", "func (*Field_IndexConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_firestore_admin_v1beta2_field_proto_rawDescGZIP(), []int{0, 0}\n}", "func (VersionView) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_appengine_v1_appengine_proto_rawDescGZIP(), []int{0}\n}", "func (*Metadata) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{2}\n}", "func (*FaultRateLimit) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_filter_fault_v2_fault_proto_rawDescGZIP(), []int{1}\n}", "func (CVSSv3_AttackVector) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_containeranalysis_v1beta1_cvss_cvss_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*GetIndexDashboardRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_mindexd_pb_mindexd_proto_rawDescGZIP(), []int{9}\n}", "func (*ListDeleted) Descriptor() ([]byte, []int) {\n\treturn file_lists_events_proto_rawDescGZIP(), []int{0}\n}", "func (*ServerStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{26}\n}", "func (*LivenessCheckResponse) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{0}\n}", "func (*GetIndexDashboardResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_mindexd_pb_mindexd_proto_rawDescGZIP(), []int{10}\n}", "func (Cluster_Health) EnumDescriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_clickhouse_v1_cluster_proto_rawDescGZIP(), []int{0, 1}\n}", "func (*TrafficSplitStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{25}\n}", "func (*WatchResponse) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{24}\n}", "func (*HealthinessStats) Descriptor() ([]byte, []int) {\n\treturn file_data_proto_rawDescGZIP(), []int{30}\n}", "func (*IndexBloatStatistic) Descriptor() ([]byte, []int) {\n\treturn file_bloat_report_proto_rawDescGZIP(), []int{2}\n}", "func (*Metrics) Descriptor() ([]byte, []int) {\n\treturn file_grpc_proto_rawDescGZIP(), []int{0}\n}", "func (*StatusList) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{17}\n}", "func (Host_Health) EnumDescriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_clickhouse_v1_cluster_proto_rawDescGZIP(), []int{6, 1}\n}", "func (Connector_Health) EnumDescriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_kafka_v1_connector_proto_rawDescGZIP(), []int{10, 0}\n}", "func (*ListRequest) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{0}\n}", "func (*GetBalancerBandwidthResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{19}\n}", "func (*ConstantSampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{3}\n}", "func (*Deprecation) Descriptor() ([]byte, []int) {\n\treturn file_external_cfgmgmt_response_nodes_proto_rawDescGZIP(), []int{8}\n}", "func (AttackComplexity) EnumDescriptor() ([]byte, []int) {\n\treturn file_mitre_cvss_v3_cvss_proto_rawDescGZIP(), []int{1}\n}", "func (*TraceProto) Descriptor() ([]byte, []int) {\n\treturn file_internal_tracing_extended_extended_trace_proto_rawDescGZIP(), []int{0}\n}", "func (*ListRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_bucketsd_pb_bucketsd_proto_rawDescGZIP(), []int{2}\n}", "func (LobbyType) EnumDescriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{0}\n}", "func (*MemberStatisticsInfoUpdateReq) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{104}\n}", "func (StandardPTransforms_DeprecatedPrimitives) EnumDescriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{4, 1}\n}", "func (SqlUpdateTrack) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1beta4_cloud_sql_resources_proto_rawDescGZIP(), []int{13}\n}", "func (Cluster_Status) EnumDescriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_clickhouse_v1_cluster_proto_rawDescGZIP(), []int{0, 2}\n}", "func (*ListReportRequest) Descriptor() ([]byte, []int) {\n\treturn file_report_proto_rawDescGZIP(), []int{9}\n}", "func (Span_SpanKind) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 0}\n}", "func (Listener_Protocol) EnumDescriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_loadbalancer_v1_network_load_balancer_proto_rawDescGZIP(), []int{2, 0}\n}", "func (*PbStatsSampleValue) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{2}\n}", "func (Event_Type) EnumDescriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{23, 0}\n}", "func (*Index) Descriptor() ([]byte, []int) {\n\treturn file_metadata_metadata_proto_rawDescGZIP(), []int{0}\n}", "func (*ApiWarning) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1_cloud_sql_resources_proto_rawDescGZIP(), []int{1}\n}", "func (*StatsEntry) Descriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{2}\n}", "func (SubscriberQuotaUpdate_Type) EnumDescriptor() ([]byte, []int) {\n\treturn file_pipelined_proto_rawDescGZIP(), []int{14, 0}\n}", "func (*Count) Descriptor() ([]byte, []int) {\n\treturn file_services_core_protobuf_servers_proto_rawDescGZIP(), []int{17}\n}", "func (*Node) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{3}\n}", "func (*OnTargetAudienceMetrics) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{19}\n}", "func (Tanyao) EnumDescriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{5}\n}", "func (*MemberStatisticsInfoData) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{102}\n}", "func (*ConstantSampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{2}\n}", "func (ConstantSampler_ConstantDecision) EnumDescriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{2, 0}\n}", "func (*CMatchTeamTimedStats) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{10}\n}", "func (*EvictWritersResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{11}\n}", "func (*PollStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_ligato_configurator_statspoller_proto_rawDescGZIP(), []int{1}\n}", "func (SqlUpdateTrack) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1_cloud_sql_resources_proto_rawDescGZIP(), []int{8}\n}", "func (*PbStatsSampleFeed) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{0}\n}", "func (*PortList) Descriptor() ([]byte, []int) {\n\treturn file_portdomain_proto_rawDescGZIP(), []int{2}\n}", "func (*UpdateIndexRequest) Descriptor() ([]byte, []int) {\n\treturn file_cc_arduino_cli_commands_v1_commands_proto_rawDescGZIP(), []int{6}\n}", "func (*ApiWarning) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_sql_v1beta4_cloud_sql_resources_proto_rawDescGZIP(), []int{1}\n}", "func (x *fastReflection_EvidenceList) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_EvidenceList\n}", "func (*Performance) Descriptor() ([]byte, []int) {\n\treturn file_commissionService_proto_rawDescGZIP(), []int{2}\n}", "func (Instance_State) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_spanner_admin_instance_v1_spanner_instance_admin_proto_rawDescGZIP(), []int{2, 0}\n}", "func (*MemberLevelListResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{49}\n}", "func (Span_Link_Type) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 3, 0}\n}", "func (*DeployedIndexRef) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_deployed_index_ref_proto_rawDescGZIP(), []int{0}\n}" ]
[ "0.67219293", "0.65016353", "0.64582133", "0.64516765", "0.6328381", "0.63209164", "0.62839967", "0.62610024", "0.62606573", "0.6250601", "0.6246428", "0.62199354", "0.61826485", "0.617517", "0.6156711", "0.61428595", "0.61351675", "0.6117465", "0.6112063", "0.61055773", "0.61016", "0.6098906", "0.6096253", "0.6073882", "0.6070226", "0.6069526", "0.60504323", "0.6044472", "0.60439956", "0.60436434", "0.6041391", "0.6040829", "0.6039607", "0.6037755", "0.60365915", "0.60361314", "0.60360897", "0.6034529", "0.6025143", "0.60148543", "0.6006964", "0.60013986", "0.6000432", "0.59995455", "0.59902275", "0.59899634", "0.59789836", "0.5973457", "0.5972198", "0.5971681", "0.59706396", "0.5962273", "0.5955418", "0.5952476", "0.5949597", "0.59443223", "0.59434694", "0.5941552", "0.5941427", "0.5931528", "0.59314895", "0.59308463", "0.59299135", "0.5927126", "0.5924344", "0.5917261", "0.5916817", "0.59109116", "0.5907628", "0.5907231", "0.5906605", "0.59059364", "0.5902747", "0.59023476", "0.5901129", "0.58995086", "0.5897858", "0.5897143", "0.58951885", "0.5892785", "0.589124", "0.5890949", "0.5890947", "0.58898383", "0.58874273", "0.5884127", "0.5883312", "0.58827883", "0.5881202", "0.5880836", "0.5879849", "0.5879686", "0.5878758", "0.58772206", "0.58762956", "0.5868994", "0.5865363", "0.5861598", "0.5860004", "0.5853497" ]
0.74354684
0
Deprecated: Use PbStatsIndexFeed.ProtoReflect.Descriptor instead.
func (*PbStatsIndexFeed) Descriptor() ([]byte, []int) { return file_stats_proto_rawDescGZIP(), []int{4} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*PbStatsIndexList) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{3}\n}", "func (*PbStatsSampleFeed) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{0}\n}", "func (*Stats) Descriptor() ([]byte, []int) {\n\treturn file_ligato_configurator_statspoller_proto_rawDescGZIP(), []int{0}\n}", "func (*StatsPayload) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{0}\n}", "func (*BulkIndexRequest) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{14}\n}", "func (*RateLimitingSampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{4}\n}", "func (*Index) Descriptor() ([]byte, []int) {\n\treturn file_index_faults_rpc_rpc_proto_rawDescGZIP(), []int{0}\n}", "func (*ClientStatsBucket) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{2}\n}", "func (*RateLimitingSampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{3}\n}", "func (*ClientStatsPayload) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{1}\n}", "func (*BulkIndexResponse) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{15}\n}", "func (*BasicStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{23}\n}", "func (*FeedbackMetrics) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{12}\n}", "func (*Metadata) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{2}\n}", "func (*GetStatsResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{45}\n}", "func (*IndexValue) Descriptor() ([]byte, []int) {\n\treturn file_openfeed_proto_rawDescGZIP(), []int{23}\n}", "func (*MetricsResponse) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{25}\n}", "func (*MemberStatisticsInfoUpdateResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{105}\n}", "func (*Metrics) Descriptor() ([]byte, []int) {\n\treturn file_grpc_proto_rawDescGZIP(), []int{0}\n}", "func (*UpdateClusterMetadata) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_greenplum_v1_cluster_service_proto_rawDescGZIP(), []int{6}\n}", "func (*Index) Descriptor() ([]byte, []int) {\n\treturn file_index_proto_rawDescGZIP(), []int{0}\n}", "func (*Cluster) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{4}\n}", "func (*TermIndexProto) Descriptor() ([]byte, []int) {\n\treturn file_raft_proto_rawDescGZIP(), []int{9}\n}", "func (*OnTargetAudienceMetrics) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{19}\n}", "func (*Deprecation) Descriptor() ([]byte, []int) {\n\treturn file_external_cfgmgmt_response_nodes_proto_rawDescGZIP(), []int{8}\n}", "func (*TrafficSplitStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{25}\n}", "func (*TraceProto) Descriptor() ([]byte, []int) {\n\treturn file_internal_tracing_extended_extended_trace_proto_rawDescGZIP(), []int{0}\n}", "func (*ServerStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{26}\n}", "func (*GetStatisticsBroadcastRequest) Descriptor() ([]byte, []int) {\n\treturn file_services_core_protobuf_servers_proto_rawDescGZIP(), []int{2}\n}", "func (*MemberStatisticsInfoUpdateReq) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{104}\n}", "func (*StatsEntry) Descriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{2}\n}", "func (*Index) Descriptor() ([]byte, []int) {\n\treturn file_threads_proto_rawDescGZIP(), []int{5}\n}", "func (*PollStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_ligato_configurator_statspoller_proto_rawDescGZIP(), []int{1}\n}", "func (*MemberStatisticsInfoData) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{102}\n}", "func (*Listen) Descriptor() ([]byte, []int) {\n\treturn file_pkg_smgrpc_smgrpc_proto_rawDescGZIP(), []int{4}\n}", "func (*LoadBalancerStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_test_proto_rawDescGZIP(), []int{9}\n}", "func (*BaseMetrics) Descriptor() ([]byte, []int) {\n\treturn file_mitre_cvss_v3_cvss_proto_rawDescGZIP(), []int{0}\n}", "func (*BulkDeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{16}\n}", "func (*FindingTypeStats) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_websecurityscanner_v1alpha_finding_type_stats_proto_rawDescGZIP(), []int{0}\n}", "func (*FaultRateLimit) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_filter_fault_v2_fault_proto_rawDescGZIP(), []int{1}\n}", "func (*SubscriberQuotaUpdate) Descriptor() ([]byte, []int) {\n\treturn file_pipelined_proto_rawDescGZIP(), []int{14}\n}", "func (*GetIndexDashboardRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_mindexd_pb_mindexd_proto_rawDescGZIP(), []int{9}\n}", "func (*Access) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_clickhouse_v1_cluster_proto_rawDescGZIP(), []int{9}\n}", "func (VersionView) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_appengine_v1_appengine_proto_rawDescGZIP(), []int{0}\n}", "func (*ApiListener) Descriptor() ([]byte, []int) {\n\treturn file_envoy_config_listener_v2_api_listener_proto_rawDescGZIP(), []int{0}\n}", "func (*SetMetadataRequest) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{18}\n}", "func (Connector_Health) EnumDescriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_kafka_v1_connector_proto_rawDescGZIP(), []int{10, 0}\n}", "func (*Forecast) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{18}\n}", "func (*Document) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{9}\n}", "func (*Field_IndexConfig) Descriptor() ([]byte, []int) {\n\treturn file_google_firestore_admin_v1beta2_field_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*ClientGroupedStats) Descriptor() ([]byte, []int) {\n\treturn file_datadog_trace_stats_proto_rawDescGZIP(), []int{3}\n}", "func (*DeleteMetadataRequest) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{19}\n}", "func (*Preferences) Descriptor() ([]byte, []int) {\n\treturn file_google_ads_googleads_v2_services_reach_plan_service_proto_rawDescGZIP(), []int{8}\n}", "func (*BulkDeleteResponse) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{17}\n}", "func (*ServicesStatsRes) Descriptor() ([]byte, []int) {\n\treturn file_external_applications_applications_proto_rawDescGZIP(), []int{9}\n}", "func (*MetricsServing) Descriptor() ([]byte, []int) {\n\treturn file_pkg_webview_view_proto_rawDescGZIP(), []int{9}\n}", "func (*ConstantSampler) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_external_envoy_config_trace_v3_opencensus_proto_rawDescGZIP(), []int{3}\n}", "func (*Node) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{3}\n}", "func (*GetIndexDashboardResponse) Descriptor() ([]byte, []int) {\n\treturn file_api_mindexd_pb_mindexd_proto_rawDescGZIP(), []int{10}\n}", "func (*Counts) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_analysis_internal_changepoints_proto_output_buffer_proto_rawDescGZIP(), []int{2}\n}", "func (*Count) Descriptor() ([]byte, []int) {\n\treturn file_services_core_protobuf_servers_proto_rawDescGZIP(), []int{17}\n}", "func (*QueryPlanStatusResponseProto) Descriptor() ([]byte, []int) {\n\treturn file_ClientDatanodeProtocol_proto_rawDescGZIP(), []int{25}\n}", "func (NumberType) EnumDescriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{6}\n}", "func (StandardPTransforms_DeprecatedPrimitives) EnumDescriptor() ([]byte, []int) {\n\treturn file_org_apache_beam_model_pipeline_v1_beam_runner_api_proto_rawDescGZIP(), []int{4, 1}\n}", "func (*CMatchTeamTimedStats) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{10}\n}", "func (*GetStatisticsBroadcastResponse) Descriptor() ([]byte, []int) {\n\treturn file_services_core_protobuf_servers_proto_rawDescGZIP(), []int{3}\n}", "func (*WatchResponse) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{24}\n}", "func (*NetProtoTalker) Descriptor() ([]byte, []int) {\n\treturn file_pkg_smgrpc_smgrpc_proto_rawDescGZIP(), []int{1}\n}", "func (StatusMessage_Reference) EnumDescriptor() ([]byte, []int) {\n\treturn file_google_devtools_clouddebugger_v2_data_proto_rawDescGZIP(), []int{1, 0}\n}", "func (*ValidatorUpdates) Descriptor() ([]byte, []int) {\n\treturn file_core_abci_v1alpha1_abci_proto_rawDescGZIP(), []int{6}\n}", "func (*Message6024) Descriptor() ([]byte, []int) {\n\treturn file_datasets_google_message4_benchmark_message4_2_proto_rawDescGZIP(), []int{26}\n}", "func (*UpdateLimitRequest_CAS) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_limit_service_proto_rawDescGZIP(), []int{9, 0}\n}", "func (*MemberStatisticsInfoAddResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{100}\n}", "func (*Message6127) Descriptor() ([]byte, []int) {\n\treturn file_datasets_google_message4_benchmark_message4_2_proto_rawDescGZIP(), []int{24}\n}", "func (*OrderUnhandledStats) Descriptor() ([]byte, []int) {\n\treturn file_orderUnhandledStatsService_proto_rawDescGZIP(), []int{0}\n}", "func (*NumericValue) Descriptor() ([]byte, []int) {\n\treturn file_google_analytics_admin_v1alpha_access_report_proto_rawDescGZIP(), []int{10}\n}", "func (*ConstantSampler) Descriptor() ([]byte, []int) {\n\treturn file_opencensus_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{2}\n}", "func (*PbStatsSampleEntry) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{1}\n}", "func (*NetRateTalker) Descriptor() ([]byte, []int) {\n\treturn file_pkg_smgrpc_smgrpc_proto_rawDescGZIP(), []int{2}\n}", "func (*MetadataUpdateEventProto) Descriptor() ([]byte, []int) {\n\treturn file_inotify_proto_rawDescGZIP(), []int{7}\n}", "func (*UpdateTeam) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{6}\n}", "func (*DumpStatsEntry) Descriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{0}\n}", "func (GameSpeed) EnumDescriptor() ([]byte, []int) {\n\treturn file_stats_stats_proto_rawDescGZIP(), []int{3}\n}", "func (*CMsgDOTARealtimeGameStats) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_common_proto_rawDescGZIP(), []int{27}\n}", "func (*PatchCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{161}\n}", "func (*ListenerTracingSettings) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_v1_options_tracing_tracing_proto_rawDescGZIP(), []int{0}\n}", "func (*ListenerTracingSettings) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_projects_gloo_api_v1_options_tracing_tracing_proto_rawDescGZIP(), []int{0}\n}", "func (*UpdateLimitRequest) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_limit_service_proto_rawDescGZIP(), []int{9}\n}", "func (*Index) Descriptor() ([]byte, []int) {\n\treturn file_metadata_metadata_proto_rawDescGZIP(), []int{0}\n}", "func (*IndexBloatStatistic) Descriptor() ([]byte, []int) {\n\treturn file_bloat_report_proto_rawDescGZIP(), []int{2}\n}", "func (*Instant) Descriptor() ([]byte, []int) {\n\treturn file_proto_google_fhir_proto_stu3_datatypes_proto_rawDescGZIP(), []int{7}\n}", "func (*UpdateIndexRequest) Descriptor() ([]byte, []int) {\n\treturn file_cc_arduino_cli_commands_v1_commands_proto_rawDescGZIP(), []int{6}\n}", "func (Index_HashFunc) EnumDescriptor() ([]byte, []int) {\n\treturn file_index_proto_rawDescGZIP(), []int{0, 0}\n}", "func (*ValidatorUpdate) Descriptor() ([]byte, []int) {\n\treturn file_tm_replay_proto_rawDescGZIP(), []int{9}\n}", "func (*PlanChange_Removed) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_plan_change_proto_rawDescGZIP(), []int{0, 3}\n}", "func (*TcpStats) Descriptor() ([]byte, []int) {\n\treturn file_viz_proto_rawDescGZIP(), []int{24}\n}", "func (*MemberStatisticsInfoListReq) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{101}\n}", "func (*PbStatsSampleValue) Descriptor() ([]byte, []int) {\n\treturn file_stats_proto_rawDescGZIP(), []int{2}\n}", "func (*Span_Link) Descriptor() ([]byte, []int) {\n\treturn file_google_devtools_cloudtrace_v2_trace_proto_rawDescGZIP(), []int{0, 3}\n}", "func (Connector_Status) EnumDescriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_mdb_kafka_v1_connector_proto_rawDescGZIP(), []int{10, 1}\n}" ]
[ "0.6839277", "0.6659184", "0.65105623", "0.6504708", "0.6449082", "0.6407179", "0.64059883", "0.6391535", "0.6383989", "0.63711065", "0.6368005", "0.6338368", "0.63329124", "0.6324471", "0.6310324", "0.63043153", "0.62913704", "0.6273191", "0.6263567", "0.6243064", "0.62395597", "0.6232945", "0.6231908", "0.62302977", "0.6225173", "0.6223296", "0.621252", "0.620069", "0.61948955", "0.6183769", "0.6177686", "0.6176077", "0.61729455", "0.6172381", "0.6170081", "0.61700004", "0.61659306", "0.6162187", "0.6145878", "0.61443555", "0.6142782", "0.6142593", "0.613962", "0.6137087", "0.61313", "0.61284834", "0.6127579", "0.61237645", "0.6123587", "0.61227775", "0.61147344", "0.61121583", "0.61106277", "0.6109081", "0.6107081", "0.6105102", "0.61036503", "0.61035866", "0.61006826", "0.61000323", "0.60973597", "0.6096179", "0.6089525", "0.6086499", "0.6081985", "0.60791224", "0.60787284", "0.6077452", "0.6074509", "0.6073244", "0.60715413", "0.607025", "0.60684997", "0.60652596", "0.606371", "0.6062662", "0.60578185", "0.6055905", "0.6055115", "0.6053049", "0.6052302", "0.6051272", "0.6050525", "0.60500926", "0.60443115", "0.6043122", "0.6043122", "0.60426056", "0.6035701", "0.6035446", "0.6034255", "0.6032634", "0.6027473", "0.6026343", "0.60229754", "0.6017363", "0.60147977", "0.6014104", "0.60132617", "0.60113454" ]
0.7314186
0
NewTree yields a tree corresponding to the given list of symbol frequencies
func NewTree(fs []SymbolFreq) Tree { // Sort frequencies sort.Sort(byFreq(fs)) wrkList := []node{} for _, f := range fs { wrkList = append(wrkList, f) } for { if len(wrkList) < 2 { break } newNode := makeNewNode(wrkList[0], wrkList[1]) wrkList = insertItem(wrkList[2:], newNode) } return Tree{wrkList[0]} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewEncodingTree(freq map[uint8]uint) *Node {\n\tvar head Node // Fictitious head\n\n\tfor i, v := range freq {\n\t\tnode := &Node{\n\t\t\tvalue: i,\n\t\t\tweight: v,\n\t\t}\n\t\thead.insert(node)\n\t}\n\n\tfor head.next != nil && head.next.next != nil {\n\t\tl := head.popFirst()\n\t\tr := head.popFirst()\n\n\t\tnode := join(l, r)\n\t\thead.insert(node)\n\t}\n\n\t// Fictitious head point to tree root\n\tif head.next != nil {\n\t\thead.next.prev = nil\n\t}\n\treturn head.next\n}", "func newt(terms []string) Tree {\n\tkvs := make([]kv, 0, len(terms))\n\tfor i, k := range terms {\n\t\tkvs = append(kvs, kv{[]byte(k), i})\n\t}\n\tsort.Slice(kvs, func(i, j int) bool {\n\t\ta, b := kvs[i].k, kvs[j].k\n\t\tfor i := 0; i < len(a) && i < len(b); i++ {\n\t\t\tif a[i] == b[i] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn a[i] < b[i]\n\t\t}\n\t\treturn len(a) < len(b)\n\t})\n\n\tt := Tree{node{next: 1}}\n\n\tt = t.construct(kvs, 0, 0)\n\treturn t\n}", "func main() {\r\n\ttest := \"abcdefghijklmnopqrstuvwxyz\"\r\n\r\n\tsymFreqs := make(map[rune]int)\r\n\t// read each symbol and record the frequencies\r\n\tfor _, c := range test {\r\n\t\tsymFreqs[c]++\r\n\t}\r\n\r\n\t// example tree\r\n\texampleTree := buildTree(symFreqs)\r\n\r\n\t// print out results\r\n\tfmt.Println(\"SYMBOL\\tWEIGHT\\tHUFFMAN CODE\")\r\n\tprintCodes(exampleTree, []byte{})\r\n}", "func buildPrefixTree(byteFrequencies *dictionary.Dictionary) *huffmanTreeNode {\n\ttree := new(priorityqueue.PriorityQueue)\n\tkeys := byteFrequencies.Keys()\n\n\tfor i := 0; i < keys.Size(); i++ {\n\t\tbyt := keys.MustGet(i)\n\t\tfrequency, _ := byteFrequencies.Get(byt)\n\n\t\ttree.Enqueue(frequency.(int), &huffmanTreeNode{frequency: frequency.(int), value: byt.(byte)})\n\t}\n\n\tfor tree.Size() > 1 {\n\t\taPrio, a := tree.Dequeue()\n\t\tbPrio, b := tree.Dequeue()\n\n\t\tnewPrio := aPrio + bPrio\n\n\t\tnode := &huffmanTreeNode{frequency: newPrio, left: a.(*huffmanTreeNode), right: b.(*huffmanTreeNode)}\n\n\t\ttree.Enqueue(newPrio, node)\n\t}\n\n\t_, root := tree.Dequeue()\n\n\treturn root.(*huffmanTreeNode)\n}", "func newTree(segmentSize, maxsize, depth int, hashfunc func() hash.Hash) *tree {\n\tn := newNode(0, nil, hashfunc())\n\tprevlevel := []*node{n}\n\t// iterate over levels and creates 2^(depth-level) nodes\n\t// the 0 level is on double segment sections so we start at depth - 2\n\tcount := 2\n\tfor level := depth - 2; level >= 0; level-- {\n\t\tnodes := make([]*node, count)\n\t\tfor i := 0; i < count; i++ {\n\t\t\tparent := prevlevel[i/2]\n\t\t\tnodes[i] = newNode(i, parent, hashfunc())\n\t\t}\n\t\tprevlevel = nodes\n\t\tcount *= 2\n\t}\n\t// the datanode level is the nodes on the last level\n\treturn &tree{\n\t\tleaves: prevlevel,\n\t\tbuffer: make([]byte, maxsize),\n\t}\n}", "func New(k int) *Tree {\n\tvar t *Tree\n\tfor _, v := range []int{6, 4, 5, 2, 9, 8, 7, 3, 1} {\n\t\tt = insert(t, v)\n\t}\n\treturn t\n}", "func NewTree(width int, company string) *Tree {\n\theight := width / 2\n\n\tleaves := make([][]string, height)\n\n\tfor i := 0; i < height; i++ {\n\t\tleaves[i] = newLevelLeaves(width, \" \")\n\t\tif i == 0 {\n\t\t\tleaves[i][width/2] = \"★\"\n\t\t\tcontinue\n\t\t}\n\n\t\tleaves[i][height-i] = \"/\"\n\t\tleaves[i][height+i] = \"\\\\\"\n\t\tfor j := (height - i + 1); j < height+i; j++ {\n\t\t\tleaves[i][j] = leafContent()\n\t\t}\n\t}\n\n\tleaves = append(leaves, bottomLeaves(width, \"^\"), bottomLeaves(width, \" \"))\n\n\treturn &Tree{\n\t\tleaves: leaves,\n\t\tcompany: company,\n\t}\n}", "func makeTree(nums []int, startIndex int) (root *node, nextIndex int) {\n\tif startIndex >= len(nums) {\n\t\treturn\n\t}\n\tchildCount := nums[startIndex]\n\tmetadataCount := nums[startIndex+1]\n\troot = &node{\n\t\tChildren: make([]*node, childCount),\n\t\tMetadata: make([]int, metadataCount),\n\t}\n\n\tnextIndex = startIndex + 2\n\tvar child *node\n\tfor i := range root.Children {\n\t\tchild, nextIndex = makeTree(nums, nextIndex)\n\t\troot.Children[i] = child\n\t}\n\tfor i := range root.Metadata {\n\t\troot.Metadata[i] = nums[nextIndex]\n\t\tnextIndex++\n\t}\n\treturn\n}", "func NewTree(childs Childs) *Quadtree {\n\tqt, ok := nodeMap[childs]\n\tif ok {\n\t\tcacheHit++\n\t\treturn qt\n\t}\n\tcacheMiss++\n\tqt = &Quadtree{childs.NE.Level + 1, childs, childs.population(), nil}\n\tif qt.Population == 0 || qt.Level <= 16 {\n\t\tnodeMap[childs] = qt\n\t}\n\treturn qt\n}", "func NewTree(pattern string, handlers []baa.HandlerFunc) *Tree {\n\tif pattern == \"\" {\n\t\tpanic(\"tree.new: pattern can be empty\")\n\t}\n\treturn &Tree{\n\t\tstatic: true,\n\t\talpha: pattern[0],\n\t\tpattern: pattern,\n\t\tformat: []byte(pattern),\n\t\thandlers: handlers,\n\t}\n}", "func (d *decoder) createTree() *node {\n\tif val, _ := readBit(d.r); val {\n\t\treturn &node{readByte(d.r), -1, false, nil, nil}\n\t} else if d.numChars != d.numCharsDecoded {\n\t\tleft := d.createTree()\n\t\tright := d.createTree()\n\t\treturn &node{0, -1, true, left, right}\n\t}\n\n\treturn nil\n}", "func NewWildcardTree(twc []byte, h func(data ...[]byte) []byte,\n\tm map[string]interface{}) *WildcardTree {\n\twt := new(WildcardTree)\n\t// Order key-value pairs in radix order, creating a Merkle tree and saving\n\t// the resulting indices in a new (final) radix tree for easy look-up\n\tr := radix.NewFromMap(m)\n\ttmp, index := make(map[string]interface{}), 0\n\tvar data [][]byte\n\tr.WalkPrefix(\"\", func(k string, v interface{}) bool {\n\t\tp, ok := v.([][]byte)\n\t\tif !ok {\n\t\t\tpanic(\"This should never happen given the function's precondition\")\n\t\t}\n\t\ttmp[k], index = radixValue{payload: p, index: index}, index+1\n\t\tdata = append(data, append([]byte(k), h(p...)...))\n\t\treturn false\n\t})\n\twt.r = radix.NewFromMap(tmp)\n\twt.mt = NewMerkleTree(twc, leafPrefix, interiorPrefix, h, data)\n\treturn wt\n}", "func New(a []int) *PTree {\n\tn := len(a)\n\tb := make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\tb[i] = i\n\t}\n\tsort.Sort(&arrayPerm{a, b})\n\tt := &PTree{}\n\tt.a = a\n\tt.n = len(a)\n\tt.root = make([]*node, n+1)\n\tt.root[n] = t.build(b)\n\tfor i := n - 1; i >= 0; i-- {\n\t\tt.root[i] = t.del(t.root[i+1], i)\n\t}\n\treturn t\n}", "func CreateBinaryTree() {\n\tfmt.Fprintln(os.Stderr, \"CreateBinaryTree\")\n\tvar min1i, min2i, pos1, pos2 int\n\tvar point []int = make([]int, MAX_CODE_LENGTH)\n\tvar code []byte = make([]byte, MAX_CODE_LENGTH)\n\tvar count []int64 = make([]int64, vocab_size*2+1)\n\tvar binaryt []int = make([]int, vocab_size*2+1)\n\tvar parent_node []int = make([]int, vocab_size*2+1)\n\tfor a := 0; a < vocab_size; a++ {\n\t\tcount[a] = int64(vocab[a].cn)\n\t}\n\tfor a := vocab_size; a < vocab_size*2; a++ {\n\t\tcount[a] = 1e15\n\t}\n\tpos1 = vocab_size - 1\n\tpos2 = vocab_size\n\t// Following algorithm constructs the Huffman tree by adding one node at a time\n\tfor a := 0; a < vocab_size-1; a++ {\n\t\t// First, find two smallest nodes 'min1, min2'\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin1i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin1i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin1i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin2i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin2i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin2i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tcount[vocab_size+a] = count[min1i] + count[min2i]\n\t\tparent_node[min1i] = vocab_size + a\n\t\tparent_node[min2i] = vocab_size + a\n\t\tbinaryt[min2i] = 1\n\t}\n\t// Now assign binary code to each vocabulary character\n\tfor a := 0; a < vocab_size; a++ {\n\t\tb := a\n\t\ti := 0\n\t\tfor {\n\t\t\tcode[i] = byte(binaryt[b])\n\t\t\tpoint[i] = b\n\t\t\ti++\n\t\t\tb = parent_node[b]\n\t\t\tif b == vocab_size*2-2 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tvocab[a].codelen = byte(i)\n\t\tvocab[a].point[0] = vocab_size - 2\n\t\tfor b = 0; b < i; b++ {\n\t\t\tvocab[a].code[i-b-1] = code[b]\n\t\t\tvocab[a].point[i-b] = point[b] - vocab_size\n\t\t}\n\t}\n}", "func CreateTree(parties []int, B int, lambda int) []Node {\n\tnodes := make([]Node, (2*B)-1) //create length based on B\n\tfor i := 0; i < len(nodes); i++ {\n\t\tpath, nonces := CreatePath(parties, int(math.Pow(math.Log2(float64(lambda)), 2))) //use path for each node\n\t\tnodes[i].Path = path\n\t\tnodes[i].Nonces = nonces\n\t\t//assigns nodes\n\t}\n\tfactor := 0 //this makes the right parent index\n\tpivotNode := CalculatePivotNode(B)\n\tfor i := 0; i < pivotNode; i++ {\n\t\tnodes[i].Parent = &nodes[B+factor] //so the parent is the right node, and last is null\n\t\tif i%2 == 1 {\n\t\t\tfactor += 1\n\t\t}\n\t}\n\treturn nodes\n\n}", "func NewTree(from []int) *Tree {\n\ttreeSize := calcTreeSize(len(from))\n\tnodes := make([]int, treeSize)\n\n\tt := &Tree{nodes, len(from)}\n\tt.build(from, 0, 0, len(from)-1)\n\n\treturn t\n}", "func New(k int) *Tree {\n\tvar t *Tree\n\tfor _, v := range rand.Perm(10) {\n\t\tt = insert(t, (1+v)*k)\n\t}\n\treturn t\n}", "func New(k int) *Tree {\n\tvar t *Tree\n\tfor _, v := range rand.Perm(10) {\n\t\tt = insert(t, (1+v)*k)\n\t}\n\treturn t\n}", "func New(hashFunc func(i interface{}) int64) *rbTree {\n\treturn &rbTree{hashFunc: hashFunc}\n}", "func createTree(lst []int) *TreeNode {\n\tif len(lst) == 0 {\n\t\treturn nil\n\t}\n\tvar root *TreeNode = nil\n\tdeque := []*TreeNode{}\n\tflag := 0 // status\n\tfor _, val := range lst {\n\t\tvar node *TreeNode = nil\n\t\tif val != -1 {\n\t\t\tnode = &TreeNode{Val: val, Left: nil, Right: nil}\n\t\t\tdeque = append(deque, node)\n\t\t}\n\t\tif root == nil {\n\t\t\troot = node\n\t\t} else {\n\t\t\tp := deque[0]\n\t\t\tif flag == 0 { // build left child\n\t\t\t\tp.Left = node\n\t\t\t\tflag = 1\n\t\t\t} else if flag == 1 {\n\t\t\t\tp.Right = node\n\t\t\t\tflag = 0\n\t\t\t\tdeque = deque[1:]\n\t\t\t}\n\t\t}\n\t}\n\treturn root\n}", "func NewTree(n int) *Tree {\n\treturn &Tree{\n\t\tn: n,\n\t\tbit: make([]int, n+1),\n\t}\n}", "func NewTree(r RuleHandle) (*Tree, error) {\n\tif r.Detection == nil {\n\t\treturn nil, ErrMissingDetection{}\n\t}\n\texpr, ok := r.Detection[\"condition\"].(string)\n\tif !ok {\n\t\treturn nil, ErrMissingCondition{}\n\t}\n\n\tp := &parser{\n\t\tlex: lex(expr),\n\t\tcondition: expr,\n\t\tsigma: r.Detection,\n\t\tnoCollapseWS: r.NoCollapseWS,\n\t}\n\tif err := p.run(); err != nil {\n\t\treturn nil, err\n\t}\n\tt := &Tree{\n\t\tRoot: p.result,\n\t\tRule: &r,\n\t}\n\treturn t, nil\n}", "func CreateTree(file string) LongParseTree {\n\tpTree := LongParseTree{dictionary : CreateTrie(file)}\n\n\tpTree.frontDepChar = make(map[rune]bool)\n\tpTree.frontDepChar['Ð'] = true\n\tpTree.frontDepChar['Ñ'] = true\n\tpTree.frontDepChar['Ò'] = true\n\tpTree.frontDepChar['Ó'] = true\n\tpTree.frontDepChar['Ô'] = true\n\tpTree.frontDepChar['Õ'] = true\n\tpTree.frontDepChar['Ö'] = true\n\tpTree.frontDepChar['×'] = true\n\tpTree.frontDepChar['Ø'] = true\n\tpTree.frontDepChar['Ù'] = true\n\tpTree.frontDepChar['å'] = true\n\tpTree.frontDepChar['ç'] = true\n\tpTree.frontDepChar['ì'] = true\n\tpTree.frontDepChar['í'] = true\n\n\tpTree.rearDepChar = make(map[rune]bool)\n\tpTree.rearDepChar['Ñ'] = true\n\tpTree.rearDepChar['×'] = true\n\tpTree.rearDepChar['à'] = true\n\tpTree.rearDepChar['á'] = true\n\tpTree.rearDepChar['â'] = true\n\tpTree.rearDepChar['ã'] = true\n\tpTree.rearDepChar['ä'] = true\n\tpTree.rearDepChar['í'] = true\n\n\tpTree.tonalChar = make(map[rune]bool)\n\tpTree.tonalChar['è'] = true\n\tpTree.tonalChar['é'] = true\n\tpTree.tonalChar['ê'] = true\n\tpTree.tonalChar['ë'] = true\n\n\tpTree.endingChar = make(map[rune]bool)\n\tpTree.endingChar['æ'] = true\n\tpTree.endingChar['Ï'] = true\n\n\treturn pTree\n}", "func NewTree(n *node) (*Tree, error) {\n\treturn &Tree{\n\t\troot: n,\n\t\tvalues: map[string]*node{n.value: n},\n\t}, nil\n}", "func New(n, k int) *Tree {\n\tvar t *Tree\n\tfor _, v := range rand.Perm(n) {\n\t\tt = insert(t, (1+v)*k)\n\t}\n\treturn t\n}", "func makeHuffman(p priq.PriQ) *node {\n\trr, ok := p.Remove()\n\tif !ok {\n\t\tpanic(\"not enough elements in the priority queue to make a huffman tree\")\n\t}\t\n\tr := rr.(*node)\n\tll, ok := p.Remove()\n\tif !ok {\n\t\tpanic(\"not enough elements in the priority queue to make a huffman tree\")\n\t}\n\tl := ll.(*node)\t\n\tfor !p.Empty() {\n\t\tparent := new(node)\n\t\tparent.count = l.count + r.count\n\t\tparent.left = l\n\t\tparent.right = r\n\t\tp.Add(parent)\n\n\t\trr, ok = p.Remove()\n\t\tr = rr.(*node)\n\t\tll, ok = p.Remove()\n\t\tl = ll.(*node)\n\t}\n\troot := new(node)\n\troot.count = l.count + r.count\n\troot.left = l\n\troot.right = r\n\treturn root\n}", "func buildTree(index int, numbers []int) (*Tree, int) {\n\tvar child *Tree\n\tchildCount := numbers[index]\n\tmetadataCount := numbers[index+1]\n\tindex += 2\n\ttree := &Tree{children: make([]*Tree, 0), metadataSum: 0, metadata: make([]int, 0)}\n\tfor i := 0; i < childCount; i++ {\n\t\tchild, index = buildTree(index, numbers)\n\t\ttree.children = append(tree.children, child)\n\t}\n\tsum := 0\n\tfor _, number := range numbers[index : index+metadataCount] {\n\t\tsum += number\n\t}\n\ttree.metadata = numbers[index : index+metadataCount]\n\ttree.metadataSum = sum\n\ttree.childCount = childCount\n\treturn tree, index + metadataCount\n}", "func (f *Forest) New(d *crypto.Digest, l uint32) *Tree {\n\tt := &Tree{\n\t\tleaves: l,\n\t\tdig: d,\n\t\tf: f,\n\t\tlastBlockLen: BlockSize,\n\t\tleavesComplete: make([]bool, l),\n\t}\n\tf.writeTree(t)\n\treturn t\n}", "func New(dgree int, ctx interface{}) *BTree {\n\treturn NewWithFreeList(degree, NewFreeList(DefaultFreeListSize), ctx)\n}", "func NewTree() *Tree {\n\treturn &Tree{Symbol{NIL, \"NewTree holder\"}, make([]*Tree, 0, maxChildren), nil}\n}", "func getTreeGenerators(bFactors []int) ([]generator.Generator, error) {\n\tvar gens []generator.Generator\n\tfor _, b := range bFactors {\n\t\tt, err := tree.New(b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgens = append(gens, t)\n\t}\n\treturn gens, nil\n}", "func NewSymbolTable(p *SymbolTable) SymbolTable {\n\treturn SymbolTable{table: make(map[string]Symbol), parent: p}\n}", "func CreateTree(data []Tree) *Tree {\n\ttemp := make(map[int]*Tree)\n\tvar root *Tree\n\tfor i := range data {\n\t\tleaf := &data[i]\n\t\ttemp[leaf.ID] = leaf\n\t\tif leaf.ParentID == 0 {\n\t\t\troot = leaf\n\t\t}\n\t}\n\n\tfor _, v := range temp {\n\t\tif v.ParentID != 0 {\n\t\t\ttemp[v.ParentID].AddNode(v)\n\t\t}\n\t}\n\n\treturn root\n}", "func New(opts ...TreeOption) *Tree {\n\tt := &Tree{}\n\tfor _, opt := range opts {\n\t\topt(t)\n\t}\n\tt.init()\n\treturn t\n}", "func (tree *Tree) ConstructTree(details *pb.MetricDetailsResponse) error {\n\talreadyVisited := []*caching.Node{}\n\troot, err := tree.GetNode(tree.RootName)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//cycles on all the metrics of the details response.\n\t//For each metric it splits the metric name into dot separated elements. Each\n\t//element will represent a node in the tree structure.\n\t//\n\t//All the nodes will have initial Size = 0\n\tfor metric, data := range details.Metrics {\n\t\tparts := strings.Split(metric, \".\")\n\t\tleafIndex := len(parts) - 1\n\n\t\talreadyVisited = []*caching.Node{root}\n\n\t\tfor currentIndex := 0; currentIndex <= leafIndex; currentIndex++ {\n\t\t\tcurrentName := strings.Join(parts[0:currentIndex+1], \".\")\n\t\t\tif val, _ := tree.GetNodeFromRoot(currentName); val != nil {\n\t\t\t\talreadyVisited = append(alreadyVisited, val)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif currentIndex == leafIndex {\n\t\t\t\tfor index, node := range alreadyVisited {\n\t\t\t\t\tif index != len(alreadyVisited)-1 {\n\t\t\t\t\t\tnode.Leaf = false\n\t\t\t\t\t}\n\t\t\t\t\tnode.Size += data.Size_\n\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcurrentNode := &caching.Node{\n\t\t\t\tName: tree.RootName + \".\" + currentName,\n\t\t\t\tChildren: []*caching.Node{},\n\t\t\t\tLeaf: true,\n\t\t\t\tSize: int64(0),\n\t\t\t}\n\n\t\t\ttree.AddNode(currentName, currentNode)\n\t\t\ttree.AddChild(alreadyVisited[len(alreadyVisited)-1], currentNode)\n\n\t\t\talreadyVisited = append(alreadyVisited, currentNode)\n\t\t}\n\t}\n\n\treturn nil\n}", "func TreeStoreNew(types ...glib.Type) *TreeStore {\n\tgtypes := C.alloc_types(C.int(len(types)))\n\tfor n, val := range types {\n\t\tC.set_type(gtypes, C.int(n), C.GType(val))\n\t}\n\tdefer C.g_free(C.gpointer(gtypes))\n\tc := C.gtk_tree_store_newv(C.gint(len(types)), gtypes)\n\treturn wrapTreeStore(unsafe.Pointer(c))\n}", "func newStack() *stack {\n\treturn &stack{\n\t\tns: make([]*Node, 0),\n\t}\n}", "func NewTree() *Tree {\n\treturn &Tree{&bytes.Buffer{}}\n}", "func NewTree(prefix, delimiter string) *Node {\n\treturn &Node{\n\t\tname: prefix,\n\t\tdelimiter: delimiter,\n\t\tnodes: make(map[string]*Node),\n\t}\n}", "func NewTree(c *Config) *Tree {\n\treturn &Tree{c: c}\n}", "func NewTree(options *Options) *Tree {\n\tif options == nil {\n\t\toptions = new(Options)\n\t}\n\tsetDefaultOptions(options)\n\n\tidx := &Tree{\n\t\tnewBlocks: make(chan int),\n\t\tdone: make(chan bool),\n\t\tblockMap: make(map[int]int),\n\t\tmanager: newEpochManager(options.NumAllocators),\n\t}\n\n\tidx.allocators = make([]*Allocator, options.NumAllocators)\n\tidx.allocatorQueue = newSlots(len(idx.allocators))\n\tfor i := range idx.allocators {\n\t\tidx.allocators[i] = newAllocator(idx, i, blockSize, idx.newBlocks)\n\t}\n\tgo idx.blockAllocator()\n\treturn idx\n}", "func (t *BPTree) startNewTree(key []byte, pointer *Record) error {\n\tt.root = t.newLeaf()\n\tt.root.Keys[0] = key\n\tt.root.pointers[0] = pointer\n\tt.root.KeysNum = 1\n\n\treturn nil\n}", "func generateRandomTreeWithRules(branchingFactor, size int, seed int64) []*LabelNode {\n\tr := rand.New(rand.NewSource(seed))\n\tqueue := new(Queue)\n\n\t//numNodes := r.Intn(size)\n\tnumNodes := size\n\tvar nodes []*LabelNode = []*LabelNode{\n\t\t&LabelNode{\n\t\t\tId: 0,\n\t\t\tLabel: uuid.NewV4().String()},\n\t}\n\tqueue.Enqueue(nodes[0])\n\n\tnodesSoFar := 1\n\tfor len(nodes) < numNodes {\n\t\tnode := queue.Dequeue()\n\t\tif node == nil {\n\t\t\tbreak\n\t\t}\n\t\tnumChildren := r.Intn(branchingFactor) + 1\n\t\tfor i := 0; i < numChildren; i++ {\n\t\t\tnode.Children = append(node.Children, nodesSoFar)\n\t\t\tnewNode := &LabelNode{\n\t\t\t\tId: nodesSoFar,\n\t\t\t\tLabel: uuid.NewV4().String()}\n\t\t\tif r.Int()%10 == 0 {\n\t\t\t\tfor j := 0; j < r.Intn(branchingFactor); j++ {\n\t\t\t\t\tnewNode.Rule = append(newNode.Rule, nodes[r.Intn(nodesSoFar)].Label)\n\t\t\t\t}\n\t\t\t}\n\t\t\tnodesSoFar++\n\t\t\tnodes = append(nodes, newNode)\n\t\t\tqueue.Enqueue(newNode)\n\t\t}\n\t}\n\treturn nodes\n}", "func New() *Tree {\n\treturn &Tree{\n\t\tDelimiter: DefaultDelimiter,\n\t\tFormatter: SimpleFormatter,\n\t\tErrors: make(map[string]error),\n\t}\n}", "func NewTree() *BPTree {\n\treturn &BPTree{LastAddress: 0, keyPosMap: make(map[string]int64), enabledKeyPosMap: false}\n}", "func NewTree(index uint8) *RBTree {\n\tvar rbTree = &RBTree{\n\t\troot: nil,\n\t\tmLeft: nil,\n\t\tmRight: nil,\n\t\tSize: 0,\n\t\tIndex: index,\n\t}\n\treturn rbTree\n}", "func buildTree(in []int, post []int, len int) *Node {\r\n\tmp = make(map[int]int)\r\n\tfor i := range in {\r\n\t\tk := in[i]\r\n\t\tv := i\r\n\t\tmp[k] = v\r\n\t}\r\n\r\n\tindex := len - 1 //index in postorder\r\n\treturn buildUtil(in[:], post[:], 0, len-1, &index)\r\n}", "func CreateTree(pairs []string) (root Node) {\n\troot = Node{Name: \"COM\", Parent: nil, Children: nil}\n\trecursiveInsertToTree(&root, pairs)\n\treturn\n}", "func NewTree(id string, cache storage.Cache, leaves storage.Store, hasher hashing.Hasher) *Tree {\n\n\tcacheLevels := int(math.Max(0.0, math.Floor(math.Log(float64(cache.Size()))/math.Log(2.0))))\n\tdigestLength := len(hasher([]byte(\"a test event\"))) * 8\n\n\ttree := &Tree{\n\t\t[]byte(id),\n\t\tleafHasherF(hasher),\n\t\tinteriorHasherF(hasher),\n\t\tmake([][]byte, digestLength),\n\t\tcache,\n\t\tleaves,\n\t\tnew(stats),\n\t\tnewArea(digestLength-cacheLevels, digestLength),\n\t\tdigestLength,\n\t\tnil,\n\t}\n\n\t// init default hashes cache\n\ttree.defaultHashes[0] = hasher(tree.id, Empty)\n\tfor i := 1; i < int(digestLength); i++ {\n\t\ttree.defaultHashes[i] = hasher(tree.defaultHashes[i-1], tree.defaultHashes[i-1])\n\t}\n\ttree.ops = tree.operations()\n\n\treturn tree\n}", "func InitTree(symbol Symbol) (*Tree, error) {\n\thandler, err := getHandler(symbol)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Tree{symbol, make([]*Tree, 0, maxChildren), handler}, nil\n}", "func New() *Tree {\n\treturn &Tree{}\n}", "func main() {\n\tfmt.Println(genNumTreesDP(5))\n}", "func NewFamilyTree() FamilyTree {\n\tf := &familyTree{\n\t\tmembers: make(map[string]*member),\n\t\tcount: 0,\n\t}\n\tinitializeFamilyTree(f)\n\treturn f\n}", "func NewTree() *Tree {\n\treturn &Tree{\n\t\trnd: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n}", "func MakeBinaryTree() *lca.Graph {\n\tg := lca.New()\n\tfor r := 'a'; r <= 'i'; r++ {\n\t\tg.AddVertex(r, r)\n\t}\n\tg.AddEdge('a', 'b')\n\tg.AddEdge('a', 'c')\n\tg.AddEdge('b', 'd')\n\tg.AddEdge('b', 'e')\n\tg.AddEdge('e', 'g')\n\tg.AddEdge('e', 'h')\n\tg.AddEdge('c', 'f')\n\tg.AddEdge('f', 'i')\n\n\treturn g\n}", "func NewWith(comparator utils.Comparator) *Tree {\n\treturn &Tree{Comparator: comparator}\n}", "func NewTree(cs []Content) (*MerkleTree, error) {\n\troot, leafs, err := buildWithContent(cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &MerkleTree{\n\t\tRoot: root,\n\t\tmerkleRoot: root.Hash,\n\t\tLeafs: leafs,\n\t}\n\treturn t, nil\n}", "func New(name string) *Tree {\n\ttr := new(Tree)\n\ttr.Name = name\n\treturn tr\n}", "func NewTree(cs []Content) (*MerkleTree, error) {\n\tvar defaultHashStrategy = \"sha256\"\n\tt := &MerkleTree{\n\t\tHashStrategy: defaultHashStrategy,\n\t}\n\troot, leafs, err := buildWithContent(cs, t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt.Root = root\n\tt.Leafs = leafs\n\tt.MerkleRoot = root.Hash\n\treturn t, nil\n}", "func createFrequencyTable(bytes *vector.Vector) *dictionary.Dictionary {\n\tdict := dictionary.New()\n\tfor i := 0; i < bytes.Size(); i++ {\n\t\tbyt := bytes.MustGet(i)\n\n\t\tif frequency, exists := dict.Get(byt); !exists {\n\t\t\tdict.Set(byt, 1)\n\t\t} else {\n\t\t\tdict.Set(byt, frequency.(int)+1)\n\t\t}\n\t}\n\n\treturn dict\n}", "func New() *SymbolTable {\n\tst := &SymbolTable{}\n\tst.symbols = make(map[string]int)\n\n\treturn st\n}", "func NewTree(db *badger.Storage, root []byte) *Tree {\n\tt := &Tree{\n\t\tdb: newTreeDb(db),\n\t}\n\tt.cache = lru.NewCache(2048)\n\tvar zero [32]byte\n\tif root != nil && len(root) == int(32) && bytes.Compare(root, zero[:]) > common.Zero {\n\t\tt.root = t.mustLoadNode(root)\n\t}\n\n\tif err := FileExist(); err == nil {\n\t\tt.BackCommit()\n\t}\n\n\treturn t\n}", "func newLeaf(h hash.Hash, data namespace.Data) leaf {\n\t// hash the namespace id along with the\n\th.Write(append(data.NamespaceID(), data.Data()...))\n\treturn leaf{\n\t\tdata: data,\n\t\tnode: node{\n\t\t\thash: h.Sum(data.NamespaceID()),\n\t\t\tmin: data.NamespaceID(),\n\t\t\tmax: data.NamespaceID(),\n\t\t},\n\t}\n}", "func create(s string) (p program) {\n\tre := regexp.MustCompile(`\\w+`)\n\tt := re.FindAllStringSubmatch(s, -1)\n\tp.name = t[0][0]\n\tp.weight, _ = strconv.Atoi(string(t[1][0]))\n\tfor _, r := range t[2:] {\n\t\tp.children = append(p.children, program{r[0], 0, nil})\n\t}\n\treturn\n}", "func New(name string) *Tree {\n\treturn &Tree{\n\t\tName: name,\n\t}\n}", "func NewTable(syms []obj.Sym) *Table {\n\t// Put syms in address order for fast address lookup.\n\tsort.Slice(syms, func(i, j int) bool {\n\t\treturn syms[i].Value < syms[j].Value\n\t})\n\n\t// Create name map for fast name lookup.\n\tname := make(map[string]int)\n\tfor i, s := range syms {\n\t\tname[s.Name] = i\n\t}\n\n\treturn &Table{syms, name}\n}", "func NewTree() *Tree {\n\treturn new(Tree)\n}", "func New(options ...TreeOpt) (*Tree, error) {\n\ttmp := tree{obj: Tree{\n\t\talgorithm: hash.Default,\n\t\tmaxLevel: defaultMaxLevel,\n\t}}\n\n\tfor _, setter := range options {\n\t\tif err := tmp.setOption(setter); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &tmp.obj, nil\n}", "func convertBitDepthsToSymbols(depth []byte, len uint, bits []uint16) {\n\tvar bl_count = [maxHuffmanBits]uint16{0}\n\tvar next_code [maxHuffmanBits]uint16\n\tvar i uint\n\t/* In Brotli, all bit depths are [1..15]\n\t 0 bit depth means that the symbol does not exist. */\n\n\tvar code int = 0\n\tfor i = 0; i < len; i++ {\n\t\tbl_count[depth[i]]++\n\t}\n\n\tbl_count[0] = 0\n\tnext_code[0] = 0\n\tfor i = 1; i < maxHuffmanBits; i++ {\n\t\tcode = (code + int(bl_count[i-1])) << 1\n\t\tnext_code[i] = uint16(code)\n\t}\n\n\tfor i = 0; i < len; i++ {\n\t\tif depth[i] != 0 {\n\t\t\tbits[i] = reverseBits(uint(depth[i]), next_code[depth[i]])\n\t\t\tnext_code[depth[i]]++\n\t\t}\n\t}\n}", "func New() *Tree23 {\n\treturn NewCapacity(1)\n}", "func makeTree(t *testing.T, files map[string]string) (string, []string, func()) {\n\ttd, err := ioutil.TempDir(\"\", \"pre-commit-go\")\n\tut.AssertEqual(t, nil, err)\n\tcleanup := func() {\n\t\tif err := internal.RemoveAll(td); err != nil {\n\t\t\tt.Fail()\n\t\t}\n\t}\n\tallFiles := make([]string, 0, len(files))\n\tfor f, c := range files {\n\t\tallFiles = append(allFiles, f)\n\t\tp := filepath.Join(td, f)\n\t\tif err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {\n\t\t\tcleanup()\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif err := ioutil.WriteFile(p, []byte(c), 0600); err != nil {\n\t\t\tcleanup()\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\tsort.Strings(allFiles)\n\treturn td, allFiles, cleanup\n}", "func NewTree() *Tree {\n\treturn &Tree{\n\t\tBlock: *NewBlock(),\n\t\tTextStyle: Theme.Tree.Text,\n\t\tSelectedRowStyle: Theme.Tree.Text,\n\t\tWrapText: true,\n\t}\n}", "func BuildTree(platform string, low, high, key int) *Tree {\n\tif (high < low) || (low > high) {\n\t\t//base case\n\t\treturn nil\n\t} else if low == high {\n\t\t//base case\n\t\tnode1 := Tree{\n\t\t\tR: emojiDictAvg[platform][low].R,\n\t\t\tG: emojiDictAvg[platform][low].G,\n\t\t\tB: emojiDictAvg[platform][low].B,\n\t\t\tURLIndex: emojiDictAvg[platform][low].URLIndex,\n\t\t}\n\t\treturn &node1\n\t} else {\n\t\t//recursive step\n\t\t//sort colors by current key\n\t\tswitch key {\n\t\tcase 0:\n\t\t\tsort.Sort(ByRed(emojiDictAvg[platform][low:high]))\n\t\tcase 1:\n\t\t\tsort.Sort(ByGreen(emojiDictAvg[platform][low:high]))\n\t\tcase 2:\n\t\t\tsort.Sort(ByBlue(emojiDictAvg[platform][low:high]))\n\t\t}\n\n\t\t//get median\n\t\tmedianIndex := (low + high) / 2\n\t\tmedianColor := emojiDictAvg[platform][medianIndex]\n\t\tparent := Tree{\n\t\t\tR: medianColor.R,\n\t\t\tG: medianColor.G,\n\t\t\tB: medianColor.B,\n\t\t\tURLIndex: medianColor.URLIndex,\n\t\t}\n\n\t\t//create Tree struct for median and build its left and right children recursively\n\t\tkey = (key + 1) % 3\n\t\tleft := BuildTree(platform, low, medianIndex-1, key)\n\t\tright := BuildTree(platform, medianIndex+1, high, key)\n\n\t\tparent.Left = left\n\t\tparent.Right = right\n\n\t\treturn &parent\n\t}\n}", "func New(text string, children ...*ASCIITree) *ASCIITree {\n\ttree := &ASCIITree{Text: text}\n\ttree.Add(children...)\n\treturn tree\n}", "func newTreeNode(parent *treeNode, move Move, state GameState, ucbC float64) *treeNode {\n\t// Construct the new node.\n\tnode := treeNode{\n\t\tparent: parent,\n\t\tmove: move,\n\t\tstate: state,\n\t\ttotalOutcome: 0.0, // No outcome yet.\n\t\tvisits: 0, // No visits yet.\n\t\tuntriedMoves: state.AvailableMoves(), // Initially the node starts with every node unexplored.\n\t\tchildren: nil, // No children yet.\n\t\tucbC: ucbC, // Whole tree uses same constant.\n\t\tselectionScore: 0.0, // No value yet.\n\t\tplayer: state.PlayerJustMoved(),\n\t}\n\n\t// We're working with pointers.\n\treturn &node\n}", "func makeFlatTree(om orbitMap) flatTree {\n\tft := make(flatTree, len(om))\n\n\tvar buildTree func(string, uint, *tree) *tree\n\tbuildTree = func(label string, depth uint, parent *tree) *tree {\n\t\tt := tree{\n\t\t\tlabel: label,\n\t\t\tchildren: make([]*tree, 0, len(om[label])),\n\t\t\tdepth: depth,\n\t\t\tparent: parent,\n\t\t}\n\t\tfor i := range om[label] {\n\t\t\tt.children = append(t.children, buildTree(om[label][i], depth+1, &t))\n\t\t}\n\t\tft[label] = &t\n\t\treturn &t\n\t}\n\n\tbuildTree(centerOfMass, 0, nil)\n\treturn ft\n}", "func New[K, V any](cmp comparator.Comparator[K]) *RbTree[K, V] {\n\treturn &RbTree[K, V]{keyCmp: cmp}\n}", "func decodeTree(r *bitio.Reader, nTree byte) (root *Node, err error) {\n\tvar head Node\n\tvar nodes byte\n\tvar leaves byte\n\tvar u uint64\n\n\tfor nodes < nTree {\n\t\tu, err = r.ReadBits(1)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif u == 1 {\n\t\t\tleaves++\n\t\t\tsymbol, err := r.ReadBits(8)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnode := &Node{value: byte(symbol)}\n\t\t\thead.pushBack(node)\n\t\t}\n\n\t\tif u == 0 {\n\t\t\tnodes++\n\t\t\tif nodes == nTree {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tr := head.popLast()\n\t\t\tl := head.popLast()\n\t\t\tnode := join(l, r)\n\t\t\thead.pushBack(node)\n\t\t}\n\t}\n\n\tif nodes != leaves {\n\t\terr = errors.New(\"nodes != leaves\")\n\t}\n\n\treturn head.next, err\n}", "func NewObjectTree(flags byte) *ObjectTree { return new(ObjectTree).Init(flags) }", "func NewTree() InfluenceTree {\n\treturn InfluenceTree{ID: RootTree.ID}\n}", "func NewTreeHasher(h HasherFunc) *TreeHasher {\n\treturn &TreeHasher{\n\t\thasher: h,\n\t}\n}", "func generateRandomTree(branchingFactor, size int, seed int64) []*LabelNode {\n\tr := rand.New(rand.NewSource(seed))\n\tqueue := new(Queue)\n\n\t//numNodes := r.Intn(size)\n\tnumNodes := size\n\tvar nodes []*LabelNode = []*LabelNode{\n\t\t&LabelNode{\n\t\t\tId: 0,\n\t\t\tLabel: uuid.NewV4().String()},\n\t}\n\tqueue.Enqueue(nodes[0])\n\n\tnodesSoFar := 1\n\tfor len(nodes) < numNodes {\n\t\tnode := queue.Dequeue()\n\t\tif node == nil {\n\t\t\tbreak\n\t\t}\n\t\tnumChildren := r.Intn(branchingFactor) + 1\n\t\tfor i := 0; i < numChildren; i++ {\n\t\t\tnode.Children = append(node.Children, nodesSoFar)\n\t\t\tnewNode := &LabelNode{\n\t\t\t\tId: nodesSoFar,\n\t\t\t\tLabel: uuid.NewV4().String()}\n\t\t\tnodesSoFar++\n\t\t\tnodes = append(nodes, newNode)\n\t\t\tqueue.Enqueue(newNode)\n\t\t}\n\t}\n\treturn nodes\n}", "func NewInTreeRegistry() framework.Registry {\r\n\treturn framework.Registry{\r\n\t\ttainttoleration.Name: tainttoleration.New,\r\n\t\tnodeaffinity.Name: nodeaffinity.New,\r\n\t\tnodename.Name: nodename.New,\r\n\t\tnodestatus.Name: nodestatus.New,\r\n nodeports.Name: nodeports.New,\r\n nodeunschedulable.Name: nodeunschedulable.New,\r\n noderesources.FitName: noderesources.NewFit,\r\n interpodaffinity.Name: interpodaffinity.New,\r\n imagelocality.Name: imagelocality.New,\r\n volumebinding.Name: volumebinding.New,\r\n volumerestrictions.Name: volumerestrictions.New,\r\n resourcepriority.Name: resourcepriority.New,\r\n repeatpriority.Name: repeatpriority.New,\r\n\t}\r\n}", "func newModeKinds(prefix, chanModes string) (*modeKinds, error) {\n\tuserPrefixes, err := parsePrefixString(prefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tchannelModes, err := parseChannelModeKindsCSV(chanModes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &modeKinds{\n\t\tuserPrefixes: userPrefixes,\n\t\tchannelModes: channelModes,\n\t}, nil\n}", "func New() Tree {\n\treturn &Node{Value: \".\"}\n}", "func New() *Tree {\n\treturn &Tree{root: &node{}}\n}", "func generateTrees95(n int) []*TNode {\n\tif n == 0 {\n\t\treturn nil\n\t}\n\treturn helper95(1, n)\n}", "func New(p []Comparable, effort int, src rand.Source) (t *Tree, err error) {\n\tvar intn func(int) int\n\tvar shuf func(n int, swap func(i, j int))\n\tif src == nil {\n\t\tintn = rand.Intn\n\t\tshuf = rand.Shuffle\n\t} else {\n\t\trnd := rand.New(src)\n\t\tintn = rnd.Intn\n\t\tshuf = rnd.Shuffle\n\t}\n\tb := builder{work: make([]float64, len(p)), intn: intn, shuf: shuf}\n\n\tdefer func() {\n\t\tswitch r := recover(); r {\n\t\tcase nil:\n\t\tcase pointAtInfinity:\n\t\t\tt = nil\n\t\t\terr = pointAtInfinity\n\t\tdefault:\n\t\t\tpanic(r)\n\t\t}\n\t}()\n\n\tt = &Tree{\n\t\tRoot: b.build(p, effort),\n\t\tCount: len(p),\n\t}\n\treturn t, nil\n}", "func constructTree(query cqr.CommonQueryRepresentation, index InvertedIndex, seen map[uint32]logicalTreeNode) (logicalTreeNode, map[uint32]logicalTreeNode, error) {\n\tif seen == nil {\n\t\tseen = make(map[uint32]logicalTreeNode)\n\t}\n\tswitch q := query.(type) {\n\tcase cqr.Keyword:\n\t\t// Return a seen atom.\n\t\tif atom, ok := seen[HashCQR(q)]; ok {\n\t\t\treturn atom, seen, nil\n\t\t}\n\n\t\tvar docs []string\n\n\t\tq.QueryString = strings.Join(strings.Fields(q.QueryString), \" \")\n\n\t\t// Perform a phase match.\n\t\tif strings.Contains(q.QueryString, \" \") {\n\t\t\tterms := strings.Split(q.QueryString, \" \")\n\t\t\tvar atoms []logicalTreeNode\n\t\t\tfor _, field := range q.Fields {\n\t\t\t\tfor _, term := range terms {\n\t\t\t\t\tdocIDs := index.DocumentIDs(field, term)\n\t\t\t\t\td := make(Documents, len(docIDs))\n\t\t\t\t\tfor _, docID := range docIDs {\n\t\t\t\t\t\td = append(d, index.DocumentMapping[docID])\n\t\t\t\t\t}\n\t\t\t\t\ta := NewAtom(cqr.NewKeyword(term, field), d)\n\t\t\t\t\tseen[a.Hash] = a\n\t\t\t\t\tatoms = append(atoms, a)\n\t\t\t\t}\n\t\t\t}\n\t\t\top := NewAdjOperator(1, true, &index)\n\t\t\tcombined, err := op.Combine(atoms)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, seen, err\n\t\t\t}\n\t\t\tdocs = append(docs, combined...)\n\t\t} else { // Just get the documents for a term.\n\t\t\tfor _, field := range q.Fields {\n\t\t\t\tfor _, docID := range index.DocumentIDs(field, q.QueryString) {\n\t\t\t\t\tdocs = append(docs, index.DocumentMapping[docID])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Create the new atom add it to the seen list.\n\t\ta := NewAtom(q, docs)\n\t\tseen[a.Hash] = a\n\t\treturn a, seen, nil\n\tcase cqr.BooleanQuery:\n\t\tvar operator Operator\n\t\tswitch strings.ToLower(q.Operator) {\n\t\tcase \"or\":\n\t\t\toperator = OrOperator\n\t\tcase \"and\":\n\t\t\toperator = AndOperator\n\t\tcase \"not\":\n\t\t\toperator = NotOperator\n\t\tcase \"adj\":\n\t\t\tvar n float64\n\t\t\tvar inOrder bool\n\t\t\tif distance, ok := q.Options[\"distance\"].(float64); ok {\n\t\t\t\tn = distance\n\t\t\t}\n\t\t\tif o, ok := q.Options[\"in_order\"].(bool); ok {\n\t\t\t\tinOrder = o\n\t\t\t}\n\t\t\toperator = NewAdjOperator(int32(n), inOrder, &index)\n\t\tdefault:\n\t\t\toperator = OrOperator\n\t\t}\n\n\t\t// Otherwise, we can just perform the operation with a typical operator.\n\t\tclauses := make([]logicalTreeNode, len(q.Children))\n\t\tfor i, child := range q.Children {\n\t\t\tvar err error\n\t\t\tclauses[i], seen, err = constructTree(child, index, seen)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, seen, err\n\t\t\t}\n\t\t}\n\t\tc, err := NewCombinator(q, operator, clauses...)\n\t\treturn c, seen, err\n\t}\n\treturn nil, nil, errors.New(\"supplied query is not supported\")\n}", "func New() *TreeMap { return new(TreeMap) }", "func NewBinaryTree(vals []Comparable) *BinaryTree {\n\treturn new(BinaryTree).Init(vals)\n}", "func NewWithFreeList(degree int, f *FreeList, ctx interface{}) *BTree {\n\tif degree <= 1 {\n\t\tpanic(\"bad degree\")\n\t}\n\n\treturn &BTree{\n\t\tdegree: degree,\n\t\tfreelist: f,\n\t\tctx: ctx,\n\t}\n}", "func newDemoTree() TreeRoot {\n\tn1 := newNode(1)\n\n\tn2 := newNode(2)\n\tn1.Left = n2\n\n\tn3 := newNode(3)\n\tn1.Right = n3\n\n\tn4 := newNode(4)\n\tn2.Left = n4\n\n\tn5 := newNode(5)\n\tn2.Right = n5\n\n\tn6 := newNode(6)\n\tn3.Left = n6\n\n\tn7 := newNode(7)\n\tn3.Right = n7\n\n\tn8 := newNode(8)\n\tn4.Left = n8\n\n\tn9 := newNode(9)\n\tn4.Right = n9\n\n\tn10 := newNode(10)\n\tn5.Left = n10\n\n\tn11 := newNode(11)\n\tn5.Right = n11\n\n\tn12 := newNode(12)\n\tn6.Left = n12\n\n\tn13 := newNode(13)\n\tn6.Right = n13\n\n\tn14 := newNode(14)\n\tn7.Left = n14\n\n\tn15 := newNode(15)\n\tn7.Right = n15\n\n\tn16 := newNode(16)\n\tn14.Left = n16\n\n\tn17 := newNode(17)\n\tn14.Right = n17\n\n\treturn n1\n}", "func newNode() *node {\n\tvar leafs [8]octant\n\tfor i := 0; i < 8; i++ {\n\t\tleafs[i] = newLeaf(nil)\n\t}\n\treturn &node{\n\t\tleafs: &leafs,\n\t}\n}", "func minTreeFromWordList(t *testing.T, words []string) *MinTree {\n\tsort.Strings(words)\n\tintree := New()\n\tfor _, word := range words {\n\t\tintree.Insert(word)\n\t}\n\tintree.Finish()\n\n\tenc, err := new(Encoder).Encode(intree)\n\tif err != nil {\n\t\tt.Fatalf(\"Encode produced an error before we could even test the numbers: %v\", err)\n\t}\n\n\touttree, err := new(Decoder).Decode(enc)\n\tif err != nil {\n\t\tt.Fatalf(\"Decode produced an error before we could even test the numbers: %v\", err)\n\t}\n\n\treturn outtree\n}", "func New() Tree {\n\treturn &binarySearchTree{}\n}", "func parse(ts *TokenScanner) (*Tree, error) {\n\tvar tree *Tree\n\n\t// Insert dummy head to enable simplified recursion logic\n\ttree, _ = InitTree(Symbol{Dummy, dummyName})\n\n\tfor ts.hasNext() {\n\t\ttoken := ts.next()\n\n\t\tif chatty {\n\t\t\tfmt.Println(\"» parsing token =\", token)\n\t\t}\n\n\t\terr := ingest(ts, tree, token)\n\t\tif err != nil {\n\t\t\treturn nil, e(\"ingest in parse failed → \", err)\n\t\t}\n\t}\n\n\tif len(tree.Children) <= 0 {\n\t\treturn nil, e(\"no complete expression provided (empty AST)\")\n\t}\n\n\t// Remove the dummy head\n\ttree = tree.Children[0]\n\n\treturn tree, nil\n}", "func newRoot(view *View, leafAllocation int64) *root {\n\tif leafAllocation < 10 {\n\t\tleafAllocation = 10\n\t}\n\tleafNum := 3 - ((leafAllocation - 1) % 3) + leafAllocation\n\tnodeNum := (leafNum - 1) / 3\n\tr := new(root)\n\tr.leaves = make([]leaf, leafNum, leafNum)\n\tfor i := 0; i < len(r.leaves)-2; i++ {\n\t\tr.leaves[i].nextFree = &r.leaves[i+1]\n\t}\n\tr.nodes = make([]node, nodeNum, nodeNum)\n\tfor i := 0; i < len(r.nodes)-2; i++ {\n\t\tr.nodes[i].nextFree = &r.nodes[i+1]\n\t}\n\tr.freeNode = &r.nodes[0]\n\tr.freeLeaf = &r.leaves[0]\n\trootNode := r.newNode(view)\n\tr.rootNode = rootNode\n\treturn r\n}", "func getTerm(rules []string, nontermlist map[string]nonterm) map[string]term {\n\ttermlist := make(map[string]term)\n\n\tfor i:=0; i<len(rules); i++ {\n\t\tnonSymbol := rules[i][0]\n\t\t//flag is used to identify whether the terminal symbol should in the firstvt\n\t\tflag := false\n\t\t//lastTerm is used to save the last terminal symbal\n\t\tlastTerm := \"\"\n\t\tfor j:=0; j<len(rules[i]); j++ {\n\t\t\t//skip nonterminal symbol\n\t\t\tif unicode.IsUpper(rune(rules[i][j])) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t//skip space\n\t\t\tif rules[i][j] == ' ' {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t//skip arrow\n\t\t\tif rules[i][j] == '-' && rules[i][j+1] == '>' {\n\t\t\t\tj += 1\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t//skip |\n\t\t\tif rules[i][j] == '|' {\n\t\t\t\t//when scan a | , should reset flag and lastTerm, also append lastTerm to nontermlist\n\t\t\t\tflag = false\n\t\t\t\tif lastTerm != \"\" {\n\t\t\t\t\ttemp := append(nontermlist[string(nonSymbol)].last, lastTerm)\n\t\t\t\t\tnontermlist[string(nonSymbol)] = nonterm{nontermlist[string(nonSymbol)].first, temp}\n\t\t\t\t}\n\t\t\t\tlastTerm = \"\"\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t//append id and other terminal symbols to termlist\n\t\t\tif rules[i][j] == 'i' && j < len(rules[i])-1 && rules[i][j+1] == 'd' {\n\t\t\t\ttermlist[\"id\"] = term{make([]string, 0), make([]string, 0)}\n\t\t\t\t//if flag is false, then this terminal symbol should append to firstvt\n\t\t\t\tif !flag {\n\t\t\t\t\ttemp := append(nontermlist[string(nonSymbol)].first, \"id\")\n\t\t\t\t\tnontermlist[string(nonSymbol)] = nonterm{temp, nontermlist[string(nonSymbol)].last}\n\t\t\t\t\tflag = true\n\t\t\t\t\tlastTerm = \"id\"\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttermlist[string(rules[i][j])] = term{make([]string, 0), make([]string, 0)}\n\t\t\t\tif !flag {\n\t\t\t\t\ttemp := append(nontermlist[string(nonSymbol)].first, string(rules[i][j]))\n\t\t\t\t\tnontermlist[string(nonSymbol)] = nonterm{temp, nontermlist[string(nonSymbol)].last}\n\t\t\t\t\tflag = true\n\t\t\t\t}\n\t\t\t\tlastTerm = string(rules[i][j])\n\t\t\t}\n\t\t}\n\n\t\tif lastTerm != \"\" {\n\t\t\ttemp := append(nontermlist[string(nonSymbol)].last, lastTerm)\n\t\t\tnontermlist[string(nonSymbol)] = nonterm{nontermlist[string(nonSymbol)].first,temp}\n\t\t}\n\t}\n\ttermlist[\"$\"] = term{make([]string, 0), make([]string, 0)}\n\treturn termlist\n}", "func NewOperators(ops ...*Symbol) *Operators {\n\t// Construct the root\n\troot := &Operators{children: map[rune]*Operators{}}\n\n\t// Add each of the symbols to it\n\tfor _, op := range ops {\n\t\troot.Add(op)\n\t}\n\n\treturn root\n}" ]
[ "0.6538434", "0.6366622", "0.62743187", "0.58552384", "0.55338293", "0.55299264", "0.5499571", "0.526624", "0.5263907", "0.5207011", "0.5103051", "0.50884753", "0.50820345", "0.50712985", "0.5066273", "0.50051606", "0.49906793", "0.49906793", "0.49438584", "0.49127695", "0.4906513", "0.48774254", "0.48625934", "0.48527083", "0.48506257", "0.4845136", "0.48204237", "0.4815497", "0.48084947", "0.48007268", "0.47772512", "0.47714514", "0.4769525", "0.4732207", "0.47212097", "0.47145262", "0.4711145", "0.47024795", "0.4695974", "0.46950272", "0.46723038", "0.4661924", "0.46602973", "0.46197733", "0.4618087", "0.4604732", "0.45812187", "0.4580116", "0.45703495", "0.45504734", "0.45471242", "0.4544632", "0.45366418", "0.45323008", "0.4530857", "0.45305592", "0.45304278", "0.45292738", "0.4528318", "0.45096374", "0.4503163", "0.45005798", "0.4499093", "0.44961333", "0.44892538", "0.44868878", "0.44855505", "0.44806677", "0.44753164", "0.4470632", "0.445984", "0.4449028", "0.4441317", "0.44369045", "0.442812", "0.4425738", "0.44255534", "0.4421733", "0.44136932", "0.4412733", "0.4405249", "0.44047377", "0.44011104", "0.43834192", "0.43780443", "0.4372522", "0.43712252", "0.43698457", "0.4363574", "0.4363298", "0.4361332", "0.43542182", "0.43540862", "0.43445605", "0.43423048", "0.43375054", "0.43370783", "0.4336786", "0.43333527", "0.43276533" ]
0.79281396
0
NewTreeFromBS yields a tree from a bitstream encoding of a tree
func NewTreeFromBS(bs *bitstream.BitStream) Tree { root := newTreeFromBS(bs) return Tree{root: root} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewTree() *BPTree {\n\treturn &BPTree{LastAddress: 0, keyPosMap: make(map[string]int64), enabledKeyPosMap: false}\n}", "func NewBTree(\n\tctx context.Context,\n\tobjStore *objstore.ObjectStore,\n\tencConf pbobject.EncryptionConfig,\n) (*BTree, error) {\n\trootNode := &Node{}\n\trootNode.Leaf = true\n\trootRef, _, err := objStore.StoreObject(ctx, rootNode, encConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbt := &BTree{\n\t\tobjStore: objStore,\n\t\tencConf: encConf,\n\t\tfreeList: sync.Pool{New: func() interface{} { return &Node{} }},\n\t}\n\n\trootMemNod := bt.newNode()\n\trootMemNod.node = rootNode\n\tbt.root = rootMemNod\n\n\trootNod := &Root{\n\t\tRootNodeRef: rootRef,\n\t}\n\trootNodRef, _, err := objStore.StoreObject(ctx, rootNod, encConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbt.rootNod = rootNod\n\tbt.rootNodRef = rootNodRef\n\n\treturn bt, nil\n}", "func (p *Contentity) st2b_BuildIntoTree() *Contentity {\n\tif p.HasError() {\n\t\treturn p\n\t}\n\tvar e error\n\tp.GTree, e = gtree.NewGTreeFromGTags(p.GTags)\n\tif e != nil {\n\t\tprintln(\"==> mcfl.st2b: Error!:\", e.Error())\n\t\tp.WrapError(\"NewGTreeFromGTags\", e)\n\t\treturn p\n\t}\n\tif p.GTree == nil {\n\t\tprintln(\"==> mcfl.st2b: got nil Gtree: %s\", e.Error())\n\t\tp.WrapError(\"nil tree from NewGTreeFromGTags\", e)\n\t}\n\tif p.GTree != nil && p.GTreeWriter != nil &&\n\t\tp.GTreeWriter != io.Discard {\n\t\tgtoken.DumpTo(p.GTokens, p.GTreeWriter)\n\t} else {\n\t\tgtoken.DumpTo(p.GTokens, os.Stdout)\n\t}\n\treturn p\n}", "func (d *decoder) createTree() *node {\n\tif val, _ := readBit(d.r); val {\n\t\treturn &node{readByte(d.r), -1, false, nil, nil}\n\t} else if d.numChars != d.numCharsDecoded {\n\t\tleft := d.createTree()\n\t\tright := d.createTree()\n\t\treturn &node{0, -1, true, left, right}\n\t}\n\n\treturn nil\n}", "func NewEncodingTree(freq map[uint8]uint) *Node {\n\tvar head Node // Fictitious head\n\n\tfor i, v := range freq {\n\t\tnode := &Node{\n\t\t\tvalue: i,\n\t\t\tweight: v,\n\t\t}\n\t\thead.insert(node)\n\t}\n\n\tfor head.next != nil && head.next.next != nil {\n\t\tl := head.popFirst()\n\t\tr := head.popFirst()\n\n\t\tnode := join(l, r)\n\t\thead.insert(node)\n\t}\n\n\t// Fictitious head point to tree root\n\tif head.next != nil {\n\t\thead.next.prev = nil\n\t}\n\treturn head.next\n}", "func BTreeCreate(t int) *BTree {\n\t// create null node to use as place filler\n\tnullNode := &BTreeNode{}\n\tfor i := 0; i < 2*t; i++ {\n\t\tnullNode.children = append(nullNode.children, nullNode)\n\t}\n\n\t// create the tree\n\ttree := BTree{\n\t\tt: t,\n\t\tnullNode: nullNode,\n\t}\n\n\t// create root node\n\tx := tree.AllocateNode()\n\tx.leaf = true\n\ttree.root = x\n\n\t// create null node used to auto-populate children of newly allocated nodes\n\ttree.nullNode = tree.AllocateNode()\n\n\t// *Here is where we'd write the new node to disk\n\treturn &tree\n}", "func NewTreeFromState(data io.Reader) (*Tree, error) {\n\tidx := &Tree{\n\t\tnewBlocks: make(chan int),\n\t\tdone: make(chan bool),\n\t\tblockMap: make(map[int]int),\n\t}\n\tif err := idx.loadState(data); err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed loading index state : %v\", err)\n\t}\n\tgo idx.blockAllocator()\n\treturn idx, nil\n}", "func NewTree() *Tree {\n\treturn &Tree{&bytes.Buffer{}}\n}", "func NewTree(index uint8) *RBTree {\n\tvar rbTree = &RBTree{\n\t\troot: nil,\n\t\tmLeft: nil,\n\t\tmRight: nil,\n\t\tSize: 0,\n\t\tIndex: index,\n\t}\n\treturn rbTree\n}", "func New() *binaryTree {\n\treturn CreateDefaultTree()\n}", "func (t Tree) AsBitstream() bitstream.BitStream {\n\tresult := bitstream.BitStream{}\n\tt.asBitstream(&result, t.root)\n\treturn result\n}", "func NewObjectTree(flags byte) *ObjectTree { return new(ObjectTree).Init(flags) }", "func NewTree(db *badger.Storage, root []byte) *Tree {\n\tt := &Tree{\n\t\tdb: newTreeDb(db),\n\t}\n\tt.cache = lru.NewCache(2048)\n\tvar zero [32]byte\n\tif root != nil && len(root) == int(32) && bytes.Compare(root, zero[:]) > common.Zero {\n\t\tt.root = t.mustLoadNode(root)\n\t}\n\n\tif err := FileExist(); err == nil {\n\t\tt.BackCommit()\n\t}\n\n\treturn t\n}", "func CreateTree(parties []int, B int, lambda int) []Node {\n\tnodes := make([]Node, (2*B)-1) //create length based on B\n\tfor i := 0; i < len(nodes); i++ {\n\t\tpath, nonces := CreatePath(parties, int(math.Pow(math.Log2(float64(lambda)), 2))) //use path for each node\n\t\tnodes[i].Path = path\n\t\tnodes[i].Nonces = nonces\n\t\t//assigns nodes\n\t}\n\tfactor := 0 //this makes the right parent index\n\tpivotNode := CalculatePivotNode(B)\n\tfor i := 0; i < pivotNode; i++ {\n\t\tnodes[i].Parent = &nodes[B+factor] //so the parent is the right node, and last is null\n\t\tif i%2 == 1 {\n\t\t\tfactor += 1\n\t\t}\n\t}\n\treturn nodes\n\n}", "func NewRBTree(less, more, equal func(a, b interface{}) bool) *RBTree {\n\trb := new(RBTree)\n\trb.root = nil\n\trb.size = 0\n\trb.less = less\n\trb.more = more\n\trb.equal = equal\n\treturn rb\n}", "func decodeTree(r *bitio.Reader, nTree byte) (root *Node, err error) {\n\tvar head Node\n\tvar nodes byte\n\tvar leaves byte\n\tvar u uint64\n\n\tfor nodes < nTree {\n\t\tu, err = r.ReadBits(1)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif u == 1 {\n\t\t\tleaves++\n\t\t\tsymbol, err := r.ReadBits(8)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnode := &Node{value: byte(symbol)}\n\t\t\thead.pushBack(node)\n\t\t}\n\n\t\tif u == 0 {\n\t\t\tnodes++\n\t\t\tif nodes == nTree {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tr := head.popLast()\n\t\t\tl := head.popLast()\n\t\t\tnode := join(l, r)\n\t\t\thead.pushBack(node)\n\t\t}\n\t}\n\n\tif nodes != leaves {\n\t\terr = errors.New(\"nodes != leaves\")\n\t}\n\n\treturn head.next, err\n}", "func newTree(segmentSize, maxsize, depth int, hashfunc func() hash.Hash) *tree {\n\tn := newNode(0, nil, hashfunc())\n\tprevlevel := []*node{n}\n\t// iterate over levels and creates 2^(depth-level) nodes\n\t// the 0 level is on double segment sections so we start at depth - 2\n\tcount := 2\n\tfor level := depth - 2; level >= 0; level-- {\n\t\tnodes := make([]*node, count)\n\t\tfor i := 0; i < count; i++ {\n\t\t\tparent := prevlevel[i/2]\n\t\t\tnodes[i] = newNode(i, parent, hashfunc())\n\t\t}\n\t\tprevlevel = nodes\n\t\tcount *= 2\n\t}\n\t// the datanode level is the nodes on the last level\n\treturn &tree{\n\t\tleaves: prevlevel,\n\t\tbuffer: make([]byte, maxsize),\n\t}\n}", "func NewBinaryTree(vals ...interface{}) (res *BinaryTreeNode, err error) {\n\tif len(vals) == 0 {\n\t\treturn nil, ErrEmptyInput\n\t}\n\tif res, err = createNode(vals[0]); err != nil {\n\t\treturn\n\t}\n\terr = buildTree([]*BinaryTreeNode{res}, 1, vals)\n\treturn\n}", "func New(dgree int, ctx interface{}) *BTree {\n\treturn NewWithFreeList(degree, NewFreeList(DefaultFreeListSize), ctx)\n}", "func NewTree(width int, company string) *Tree {\n\theight := width / 2\n\n\tleaves := make([][]string, height)\n\n\tfor i := 0; i < height; i++ {\n\t\tleaves[i] = newLevelLeaves(width, \" \")\n\t\tif i == 0 {\n\t\t\tleaves[i][width/2] = \"★\"\n\t\t\tcontinue\n\t\t}\n\n\t\tleaves[i][height-i] = \"/\"\n\t\tleaves[i][height+i] = \"\\\\\"\n\t\tfor j := (height - i + 1); j < height+i; j++ {\n\t\t\tleaves[i][j] = leafContent()\n\t\t}\n\t}\n\n\tleaves = append(leaves, bottomLeaves(width, \"^\"), bottomLeaves(width, \" \"))\n\n\treturn &Tree{\n\t\tleaves: leaves,\n\t\tcompany: company,\n\t}\n}", "func New() *RBTree {\n\treturn &RBTree{\n\t\tlock: sync.RWMutex{},\n\t\tNode: nil,\n\t\tstack: newStack(nil),\n\t}\n}", "func NewTree(pattern string, handlers []baa.HandlerFunc) *Tree {\n\tif pattern == \"\" {\n\t\tpanic(\"tree.new: pattern can be empty\")\n\t}\n\treturn &Tree{\n\t\tstatic: true,\n\t\talpha: pattern[0],\n\t\tpattern: pattern,\n\t\tformat: []byte(pattern),\n\t\thandlers: handlers,\n\t}\n}", "func NewBST() *BSTree {\n\treturn &BSTree{nil}\n}", "func CreateBinaryTree() {\n\tfmt.Fprintln(os.Stderr, \"CreateBinaryTree\")\n\tvar min1i, min2i, pos1, pos2 int\n\tvar point []int = make([]int, MAX_CODE_LENGTH)\n\tvar code []byte = make([]byte, MAX_CODE_LENGTH)\n\tvar count []int64 = make([]int64, vocab_size*2+1)\n\tvar binaryt []int = make([]int, vocab_size*2+1)\n\tvar parent_node []int = make([]int, vocab_size*2+1)\n\tfor a := 0; a < vocab_size; a++ {\n\t\tcount[a] = int64(vocab[a].cn)\n\t}\n\tfor a := vocab_size; a < vocab_size*2; a++ {\n\t\tcount[a] = 1e15\n\t}\n\tpos1 = vocab_size - 1\n\tpos2 = vocab_size\n\t// Following algorithm constructs the Huffman tree by adding one node at a time\n\tfor a := 0; a < vocab_size-1; a++ {\n\t\t// First, find two smallest nodes 'min1, min2'\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin1i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin1i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin1i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin2i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin2i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin2i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tcount[vocab_size+a] = count[min1i] + count[min2i]\n\t\tparent_node[min1i] = vocab_size + a\n\t\tparent_node[min2i] = vocab_size + a\n\t\tbinaryt[min2i] = 1\n\t}\n\t// Now assign binary code to each vocabulary character\n\tfor a := 0; a < vocab_size; a++ {\n\t\tb := a\n\t\ti := 0\n\t\tfor {\n\t\t\tcode[i] = byte(binaryt[b])\n\t\t\tpoint[i] = b\n\t\t\ti++\n\t\t\tb = parent_node[b]\n\t\t\tif b == vocab_size*2-2 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tvocab[a].codelen = byte(i)\n\t\tvocab[a].point[0] = vocab_size - 2\n\t\tfor b = 0; b < i; b++ {\n\t\t\tvocab[a].code[i-b-1] = code[b]\n\t\t\tvocab[a].point[i-b] = point[b] - vocab_size\n\t\t}\n\t}\n}", "func LoadBTree(\n\tctx context.Context,\n\tobjStore *objstore.ObjectStore,\n\tencConf pbobject.EncryptionConfig,\n\trootRef *storageref.StorageRef,\n) (*BTree, error) {\n\tctx = objstore.WithObjStore(ctx, objStore)\n\trootNod := &Root{}\n\tif err := rootRef.FollowRef(ctx, nil, rootNod, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\tbt := &BTree{\n\t\tobjStore: objStore,\n\t\trootNod: rootNod,\n\t\trootNodRef: rootRef,\n\t\tencConf: encConf,\n\t\tfreeList: sync.Pool{New: func() interface{} { return &Node{} }},\n\t}\n\n\trootMemNode, err := bt.followNodeRef(rootNod.GetRootNodeRef())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbt.root = rootMemNode\n\n\treturn bt, nil\n}", "func NewBinaryTree() *BinaryTree {\n\tvar t BinaryTree\n\treturn &t\n}", "func DecodeTree(na ipld.NodeAssembler, rd *bufio.Reader) error {\n\tif _, err := readNullTerminatedNumber(rd); err != nil {\n\t\treturn err\n\t}\n\n\tt := Type.Tree__Repr.NewBuilder()\n\tma, err := t.BeginMap(-1)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tname, node, err := DecodeTreeEntry(rd)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tee, err := ma.AssembleEntry(name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = ee.AssignNode(node); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif err := ma.Finish(); err != nil {\n\t\treturn err\n\t}\n\treturn na.AssignNode(t.Build())\n}", "func NewTree(fs []SymbolFreq) Tree {\n\t// Sort frequencies\n\tsort.Sort(byFreq(fs))\n\n\twrkList := []node{}\n\tfor _, f := range fs {\n\t\twrkList = append(wrkList, f)\n\t}\n\n\tfor {\n\t\tif len(wrkList) < 2 {\n\t\t\tbreak\n\t\t}\n\n\t\tnewNode := makeNewNode(wrkList[0], wrkList[1])\n\n\t\twrkList = insertItem(wrkList[2:], newNode)\n\t}\n\n\treturn Tree{wrkList[0]}\n}", "func NewBSTree() *BSTree {\n\tb := &BSTree{\n\t\tleft: &BSTree{},\n\t\tright: &BSTree{},\n\t}\n\treturn b\n}", "func (t *BPTree) startNewTree(key []byte, pointer *Record) error {\n\tt.root = t.newLeaf()\n\tt.root.Keys[0] = key\n\tt.root.pointers[0] = pointer\n\tt.root.KeysNum = 1\n\n\treturn nil\n}", "func newIIDBT(s BaseSentence) (IIDBT, error) {\n\tp := newParser(s, PrefixIIDBT)\n\treturn IIDBT{\n\t\tBaseSentence: s,\n\t\tDepthFeet: p.Float64(0, \"depth (feet)\"),\n\t\tDepthMeters: p.Float64(2, \"depth (m)\"),\n\t\tDepthFathoms: p.Float64(4, \"depth (fathoms)\"),\n\t}, p.Err()\n}", "func NewTree(n int) *Tree {\n\treturn &Tree{\n\t\tn: n,\n\t\tbit: make([]int, n+1),\n\t}\n}", "func Test_Bitree(t *testing.T) {\n\tbt := &BiTree{}\n\tbt.Init(CfInt)\n\troot := NewBiTreeNode(0)\n\tn1 := NewBiTreeNode(1)\n\tn2 := NewBiTreeNode(2)\n\tn3 := NewBiTreeNode(3)\n\tn4 := NewBiTreeNode(4)\n\tn5 := NewBiTreeNode(5)\n\tn6 := NewBiTreeNode(6)\n\tvar err error\n\terr = bt.InsertAsLeftChild(nil, root)\n\tcheckErr(err, t)\n\terr = bt.InsertAsLeftChild(root, n1)\n\tcheckErr(err, t)\n\terr = bt.InsertAsRightChild(root, n2)\n\tcheckErr(err, t)\n\terr = bt.InsertAsLeftChild(n1, n3)\n\tcheckErr(err, t)\n\terr = bt.InsertAsRightChild(n1, n4)\n\tcheckErr(err, t)\n\terr = bt.InsertAsLeftChild(n2, n5)\n\tcheckErr(err, t)\n\terr = bt.InsertAsRightChild(n2, n6)\n\tcheckErr(err, t)\n\n\tt.Log(\"root\", bt.Root().Data()) //0\n\tt.Log(\"left\", bt.Root().Left().Left().Data()) //3\n\tt.Log(\"right\", bt.Root().Right().Right().Data()) //6\n\tt.Log(\"size\", bt.Size()) //7\n\n\tt.Log(\"删除左子树\")\n\tbt.RemoveLeftChild(root)\n\n\tt.Log(\"root\", bt.Root().Data()) //0\n\tt.Log(\"left\", bt.Root().Left()) //nil\n\tt.Log(\"right\", bt.Root().Right().Right().Data()) //6\n\tt.Log(\"size\", bt.Size()) //4\n\n\t//重新加回来\n\terr = bt.InsertAsLeftChild(root, n1)\n\tcheckErr(err, t)\n\terr = bt.InsertAsLeftChild(n1, n3)\n\tcheckErr(err, t)\n\terr = bt.InsertAsRightChild(n1, n4)\n\tcheckErr(err, t)\n\n\tt.Log(\"root\", bt.Root().Data()) //0\n\tt.Log(\"left\", bt.Root().Left().Left().Data()) //3\n\tt.Log(\"right\", bt.Root().Right().Right().Data()) //6\n\tt.Log(\"size\", bt.Size()) //7\n\n\tfmt.Println(\"前序\")\n\t//前序\n\tl1 := new(List)\n\tbt.Root().Preorder(l1)\n\tl1.Traverse(PrintNode)\n\n\tfmt.Println(\"前序非递归\")\n\t//前序\n\tl11 := new(List)\n\tbt.Root().PreorderNo(l11)\n\tl11.Traverse(PrintNode)\n\n\tfmt.Println(\"中序\")\n\t//中序\n\tl2 := new(List)\n\tbt.Root().Inorder(l2)\n\tl2.Traverse(PrintNode)\n\n\tfmt.Println(\"中序非递归\")\n\t//中序\n\tl22 := new(List)\n\tbt.Root().InorderNo(l22)\n\tl22.Traverse(PrintNode)\n\n\tfmt.Println(\"后序\")\n\t//后序\n\tl3 := new(List)\n\tbt.Root().Postorder(l3)\n\tl3.Traverse(PrintNode)\n\n\tfmt.Println(\"后序非递归\")\n\t//后序\n\tl33 := new(List)\n\tbt.Root().PostorderNo(l33)\n\tl33.Traverse(PrintNode)\n\n\tfmt.Println(\"后序非递归2\")\n\t//后序\n\tl332 := new(List)\n\tbt.Root().PostorderNo2(l332)\n\tl332.Traverse(PrintNode)\n\n\tfmt.Println(\"层次\")\n\t//层次\n\tl4 := new(List)\n\tbt.Root().LevelorderNo(l4)\n\tl4.Traverse(PrintNode)\n\n\tfmt.Println(\"广度优先\")\n\t//BFS\n\tl5 := new(List)\n\tbt.Root().BFS(l5)\n\tl5.Traverse(PrintNode)\n\n\tfmt.Println(\"深度优先\")\n\t//BFS\n\tl6 := new(List)\n\tbt.Root().DFS(l6)\n\tl6.Traverse(PrintNode)\n}", "func NewBinaryTree() *BinaryTree {\n\treturn &BinaryTree{}\n}", "func (bpt *BplusTree) treeNodeInit(isLeaf bool, next common.Key, prev common.Key,\n\tinitLen int) *treeNode {\n\n\tnode := defaultAlloc()\n\tnode.Children = make([]treeNodeElem, initLen, bpt.context.maxDegree)\n\tnode.IsLeaf = isLeaf\n\tnode.NextKey = next\n\tnode.PrevKey = prev\n\t// Generate a new key for the node being added.\n\tnode.NodeKey = common.Generate(bpt.context.keyType, bpt.context.pfx)\n\treturn node\n}", "func main() {\n\troot := &TreeNode{\n\t\tVal: 2,\n\t\tLeft: &TreeNode{\n\t\t\tVal: 1,\n\t\t},\n\t\tRight: &TreeNode{\n\t\t\tVal: 3,\n\t\t},\n\t}\n\tprintTreeNodeByDFS(root)\n\tfmt.Println()\n\n\tser := Constructor()\n\ttreeString := ser.serialize(root)\n\tfmt.Println(treeString)\n\tans := ser.deserialize(treeString)\n\t// printTreeNodeByBFS(ans)\n\tprintTreeNodeByDFS(ans)\n\tfmt.Println()\n}", "func NewBinaryTree(vals []Comparable) *BinaryTree {\n\treturn new(BinaryTree).Init(vals)\n}", "func New(hashFunc func(i interface{}) int64) *rbTree {\n\treturn &rbTree{hashFunc: hashFunc}\n}", "func main() {\n\tt11 := &TreeNode{Val:7}\n\tt21 := &TreeNode{Val:3}\n\tt22 := &TreeNode{Val:15}\n\t// t31 := &TreeNode{Val:1}\n\t// t32 := &TreeNode{Val:4}\n\tt33 := &TreeNode{Val:9}\n\tt34 := &TreeNode{Val:20}\n\tt11.Left = t21\n\tt11.Right = t22\n\t// t21.Left = t31\n\t// t21.Right = t32\n\tt22.Left = t33\n\tt22.Right = t34\n\n\tb1 := Constructor(t11)\n\n\tfmt.Println(b1.Data)\n\tfmt.Println(b1.Next())\n\tfmt.Println(b1.Next())\n\tfmt.Println(b1.HasNext())\n\tfmt.Println(b1.Next())\n\tfmt.Println(b1.HasNext())\n\tfmt.Println(b1.Next())\n\tfmt.Println(b1.HasNext())\n\tfmt.Println(b1.Next())\n\tfmt.Println(b1.HasNext())\n}", "func (t *BPTree) newNode() *Node {\n\tnode := &Node{\n\t\tKeys: make([][]byte, order-1),\n\t\tpointers: make([]interface{}, order),\n\t\tisLeaf: false,\n\t\tparent: nil,\n\t\tKeysNum: 0,\n\t\tAddress: t.LastAddress,\n\t}\n\tsize := getBinaryNodeSize()\n\tt.LastAddress += size\n\n\treturn node\n}", "func NewTree() *Tree {\n\treturn &Tree{\n\t\trnd: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n}", "func NewBinaryCodecFrom( b []byte ) *BinaryCodec {\n var c *BinaryCodec = &BinaryCodec{}\n buf := bytes.NewBuffer( b )\n c.buf = buf\n return c\n}", "func NewTree() *Tree {\n\treturn &Tree{Symbol{NIL, \"NewTree holder\"}, make([]*Tree, 0, maxChildren), nil}\n}", "func newBinaryTreeNode(value int) *BinaryTreeNode {\n\treturn &BinaryTreeNode{\n\t\tData: value,\n\t\tLeft: nil,\n\t\tRight: nil,\n\t}\n}", "func BstFromPreorderBak(preorder []int) *TreeNode {\n\tif len(preorder) <= 0 {\n\t\treturn nil\n\t}\n\n\troot := &TreeNode{\n\t\tVal: preorder[0],\n\t\tLeft: nil,\n\t\tRight: nil,\n\t}\n\tvar leftPos int\n\tfor i, num := range preorder[1:] {\n\t\tif num > preorder[0] {\n\t\t\tleftPos = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\troot.Left = BstFromPreorderBak(preorder[1:leftPos])\n\troot.Right = BstFromPreorderBak(preorder[leftPos:])\n\treturn root\n}", "func Constructor919(root *TreeNode) CBTInserter {\n\tinserter := CBTInserter{\n\t\tqueue: make([]*TreeNode, 0),\n\t}\n\n\tq := make([]*TreeNode, 0)\n\tif root != nil {\n\t\tq = append(q, root)\n\t\tinserter.Insert(root.Val)\n\t}\n\n\tfor len(q) > 0 {\n\t\tnode := q[0]\n\t\tq = q[1:]\n\n\t\tif node.Left != nil {\n\t\t\tq = append(q, node.Left)\n\t\t\tinserter.Insert(node.Left.Val)\n\t\t}\n\n\t\tif node.Right != nil {\n\t\t\tq = append(q, node.Right)\n\t\t\tinserter.Insert(node.Right.Val)\n\t\t}\n\t}\n\n\treturn inserter\n}", "func New(root string) *Bag {\n\treturn &Bag{root: root, Hasher: HashSHA256}\n}", "func NewEmptyTree(jsBlockService js.Value, jsPublicKeyBits js.Value) *then.Then {\n\tctx := context.TODO()\n\n\tt := then.New()\n\tgo func() {\n\t\tstore := jsstore.New(jsBlockService)\n\t\ttreeKey, err := crypto.UnmarshalPubkey(helpers.JsBufferToBytes(jsPublicKeyBits))\n\t\tif err != nil {\n\t\t\tt.Reject(err)\n\t\t\treturn\n\t\t}\n\t\tdid := consensus.EcdsaPubkeyToDid(*treeKey)\n\t\tdag := consensus.NewEmptyTree(ctx, did, store)\n\t\tt.Resolve(helpers.CidToJSCID(dag.Tip))\n\t}()\n\treturn t\n}", "func New(value interface{}, comparator comparator.Less) *RBTree {\n\treturn &RBTree{value: value, less: comparator, color: \"black\"}\n}", "func NewBst() *Bst {\n\tbint := NewBt()\n\tbst1 := Bst{*bint}\n\treturn &bst1\n}", "func (t *BPTree) ToBinary(n *Node) (result []byte, err error) {\n\tvar i int\n\tvar keys [order - 1]int64\n\n\tfor i = 0; i < n.KeysNum; i++ {\n\t\tif t.enabledKeyPosMap {\n\t\t\tif len(t.keyPosMap) == 0 {\n\t\t\t\treturn nil, errors.New(\"not set keyPosMap\")\n\t\t\t}\n\t\t\tkeys[i] = t.keyPosMap[string(n.Keys[i])]\n\t\t} else {\n\t\t\tkey, _ := strconv2.StrToInt64(string(n.Keys[i]))\n\n\t\t\tkeys[i] = key\n\t\t}\n\t}\n\n\tvar pointers [order]int64\n\n\tif !n.isLeaf {\n\t\tfor i = 0; i < n.KeysNum+1; i++ {\n\t\t\tpointers[i] = n.pointers[i].(*Node).Address\n\t\t}\n\t} else {\n\t\tfor i = 0; i < n.KeysNum; i++ {\n\t\t\tif n.pointers[i].(*Record).H != nil {\n\t\t\t\tdataPos := n.pointers[i].(*Record).H.dataPos\n\t\t\t\tpointers[i] = int64(dataPos)\n\t\t\t} else {\n\t\t\t\tpointers[i] = 0\n\t\t\t}\n\t\t}\n\t}\n\n\tvar nextAddress int64\n\tnextAddress = DefaultInvalidAddress\n\n\tif n.Next != nil {\n\t\tnextAddress = n.Next.Address\n\t}\n\n\tvar isLeaf uint16\n\tisLeaf = 0\n\n\tif n.isLeaf {\n\t\tisLeaf = 1\n\t}\n\n\tbinNode := BinaryNode{\n\t\tKeys: keys,\n\t\tPointers: pointers,\n\t\tIsLeaf: isLeaf,\n\t\tAddress: n.Address,\n\t\tNextAddress: nextAddress,\n\t\tKeysNum: uint16(n.KeysNum),\n\t}\n\n\tbuf := new(bytes.Buffer)\n\n\terr = binary.Write(buf, binary.LittleEndian, binNode)\n\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func New() Tree {\n\treturn &binarySearchTree{}\n}", "func NewBST(comparator cmp.Compare) *BST {\n\treturn &BST{Root: nil, size: 0, Cmp: comparator}\n}", "func (t *BPTree) newLeaf() *Node {\n\tleaf := t.newNode()\n\tleaf.isLeaf = true\n\treturn leaf\n}", "func NewBplusTree(ctx Context) (*BplusTree, error) {\n\tif ctx.maxDegree < 3 {\n\t\tglog.Errorf(\"invalid value for degree in the context.\")\n\t\treturn nil, common.ErrInvalidParam\n\t}\n\n\tif isEmptyInterface(ctx.dbMgr) {\n\t\tglog.Infof(\"no db manager specified. Can't move forward\\n\")\n\t\treturn nil, common.ErrInvalidParam\n\t}\n\n\tbplustree := &BplusTree{rootKey: common.Key{BPTkey: \"\"}, initialized: true, context: ctx}\n\n\tbase, err := bplustree.context.dbMgr.GetRoot()\n\tif err != nil {\n\t\tglog.Errorf(\"Fail to load the root key: (err: %v)\", err)\n\t\treturn nil, err\n\t}\n\tif base != nil {\n\t\tbplustree.rootKey = base.RootKey\n\t\tbplustree.context.maxDegree = base.Degree\n\t}\n\n\tif isEmptyInterface(ctx.lockMgr) {\n\t\tglog.Infof(\"no locker specified. Using default locker using mutex\\n\")\n\t\tbplustree.context.lockMgr = new(defaultLock)\n\t\tbplustree.context.lockMgr.Init()\n\t}\n\n\treturn bplustree, nil\n}", "func TestNewBST(t *testing.T) {\n\ttt := []struct {\n\t\tname string\n\t\tinBtree []int\n\t\toutInOrder []int\n\t}{\n\t\t{\n\t\t\tname: \"test1\",\n\t\t\tinBtree: []int{2, 1, 3},\n\t\t\toutInOrder: []int{1, 2, 3},\n\t\t},\n\t\t{\n\t\t\tname: \"test2\",\n\t\t\tinBtree: []int{5, 6, 4, 2, 3, 1, 7, 8, 9},\n\t\t\toutInOrder: []int{1, 2, 3, 4, 5, 6, 7, 8, 9},\n\t\t},\n\t\t{\n\t\t\tname: \"test3\",\n\t\t\tinBtree: []int{100, 50, 60, 30, 10, 55, 80, 90, 75, 1},\n\t\t\toutInOrder: []int{1, 10, 30, 50, 55, 60, 75, 80, 90, 100},\n\t\t},\n\t}\n\n\tfor _, tc := range tt {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\ttree := newBST(tc.inBtree[:1][0], tc.inBtree[1:])\n\t\t\tresult := []int{}\n\t\t\tresult = tree.inOrderTraverseRecursive(result)\n\t\t\tif !reflect.DeepEqual(result, tc.outInOrder) {\n\t\t\t\tt.Fatalf(\"result: \\n %v, want: \\n %v\", result, tc.outInOrder)\n\t\t\t}\n\t\t})\n\t}\n}", "func NewTree(c *Config) *Tree {\n\treturn &Tree{c: c}\n}", "func createBinaryTree(rootAddress **BinaryTreeNode) {\n\troot := newBinaryTreeNode(4)\n\troot.Left = newBinaryTreeNode(2)\n\troot.Left.Left = newBinaryTreeNode(1)\n\troot.Left.Right = newBinaryTreeNode(3)\n\troot.Right = newBinaryTreeNode(6)\n\troot.Right.Left = newBinaryTreeNode(5)\n\troot.Right.Right = newBinaryTreeNode(8)\n\troot.Left.Left.Left = newBinaryTreeNode(0)\n\troot.Right.Right.Left = newBinaryTreeNode(7)\n\n\t*rootAddress = root\n}", "func NewTree(cs []Content) (*MerkleTree, error) {\n\troot, leafs, err := buildWithContent(cs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &MerkleTree{\n\t\tRoot: root,\n\t\tmerkleRoot: root.Hash,\n\t\tLeafs: leafs,\n\t}\n\treturn t, nil\n}", "func convertBST(root *data.TreeNode) *data.TreeNode {\n\tsum := 0\n\tdfs538(root, &sum)\n\treturn root\n}", "func BinaryTree(nums ...int) *BST {\n\troot := Node{val: nums[0]}\n\tbst := BST{root: &root, size: 1, depth: 1}\n\tfor i, num := range nums {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// traverses bst for given input\n\t\tnode, depth := bst.traverse(num)\n\n\t\t// constructs a new node\n\t\tnewNode := Node{val: num}\n\n\t\t// sets as right child if greater\n\t\t// and left if less than\n\t\t// ignores duplicte entries\n\t\tif num > node.val {\n\t\t\tnode.right = &newNode\n\t\t} else if num < node.val {\n\t\t\tnode.left = &newNode\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\n\t\t// if we've exceeded our max depth, we increase\n\t\t// the max depth of the BST\n\t\tif depth > bst.depth {\n\t\t\tbst.depth = depth\n\t\t}\n\n\t\t// we increase our BST size\n\t\tbst.size++\n\n\t}\n\treturn &bst\n}", "func NewTree(childs Childs) *Quadtree {\n\tqt, ok := nodeMap[childs]\n\tif ok {\n\t\tcacheHit++\n\t\treturn qt\n\t}\n\tcacheMiss++\n\tqt = &Quadtree{childs.NE.Level + 1, childs, childs.population(), nil}\n\tif qt.Population == 0 || qt.Level <= 16 {\n\t\tnodeMap[childs] = qt\n\t}\n\treturn qt\n}", "func NewTree(options *Options) *Tree {\n\tif options == nil {\n\t\toptions = new(Options)\n\t}\n\tsetDefaultOptions(options)\n\n\tidx := &Tree{\n\t\tnewBlocks: make(chan int),\n\t\tdone: make(chan bool),\n\t\tblockMap: make(map[int]int),\n\t\tmanager: newEpochManager(options.NumAllocators),\n\t}\n\n\tidx.allocators = make([]*Allocator, options.NumAllocators)\n\tidx.allocatorQueue = newSlots(len(idx.allocators))\n\tfor i := range idx.allocators {\n\t\tidx.allocators[i] = newAllocator(idx, i, blockSize, idx.newBlocks)\n\t}\n\tgo idx.blockAllocator()\n\treturn idx\n}", "func MakeBinaryTree() *lca.Graph {\n\tg := lca.New()\n\tfor r := 'a'; r <= 'i'; r++ {\n\t\tg.AddVertex(r, r)\n\t}\n\tg.AddEdge('a', 'b')\n\tg.AddEdge('a', 'c')\n\tg.AddEdge('b', 'd')\n\tg.AddEdge('b', 'e')\n\tg.AddEdge('e', 'g')\n\tg.AddEdge('e', 'h')\n\tg.AddEdge('c', 'f')\n\tg.AddEdge('f', 'i')\n\n\treturn g\n}", "func (bt *Tree) Copy() *Tree {\n\tcp := &Tree{bytes: bt.bytes, length: bt.length, root: &node{}}\n\tnodes := make([]*node, 0, bt.Length())\n\tnodeCopies := make([]*node, 0, bt.Length())\n\tnodes = append(nodes, bt.root)\n\tnodeCopies = append(nodeCopies, cp.root)\n\n\tfor {\n\t\tif len(nodes) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tn := nodes[0]\n\t\tcpn := nodeCopies[0]\n\t\tnodes = nodes[1:]\n\t\tnodeCopies = nodeCopies[1:]\n\t\tfor _, e := range n.edges {\n\t\t\tcpt := &node{key: e.target.key, data: e.target.data}\n\t\t\tcpn.edges = append(cpn.edges, &edge{label: e.label, target: cpt})\n\t\t\tnodes = append(nodes, e.target)\n\t\t\tnodeCopies = append(nodeCopies, cpt)\n\t\t}\n\t}\n\n\treturn cp\n}", "func CreateVEBTree(u int) *VEBTree {\n\tnull := -1\n\tv := &VEBTree{\n\t\tu: u,\n\t\tnull: null,\n\t\tmin: null,\n\t\tmax: null,\n\t}\n\n\tif u > 2 {\n\t\trootU := v.rootU()\n\t\tv.summary = CreateVEBTree(rootU)\n\t\tfor i := 0; i < rootU; i++ {\n\t\t\tv.cluster = append(v.cluster, CreateVEBTree(rootU))\n\t\t}\n\t}\n\n\treturn v\n}", "func CreateBST(compare func(interface{}, interface{}) int) RedBlackTree {\n\treturn (&Impl{nil, nil}).Create(compare)\n}", "func NewBTSVTable(path string, ast ASTNode, hash hash.Hash) *btsvTable {\n\tt := &btsvTable{\n\t\tast: ast,\n\t\thash: hash,\n\t\tdir: path,\n\t}\n\treturn t\n}", "func TestBTreeFreeTypedness(t *testing.T) {\n\ta := MakeBinaryTree(\"a\")\n\tb := MakeBinaryTreeWithLeftSubtree(\"b\", a)\n\te := MakeBinaryTree(\"e\")\n\td := MakeBinaryTreeWithRightSubtree(\"d\", e)\n\tc := MakeBinaryTreeWithSubtrees(\"c\", d, b)\n\n\tConvey(\"Test BTrees\", t, func() {\n\t\t//c.prefixPrint()\n\t\tSo(a.IsLeaf(), ShouldBeTrue)\n\t\tSo(b.IsLeaf(), ShouldBeFalse)\n\t\tSo(c.IsLeaf(), ShouldBeFalse)\n\t})\n\n}", "func New() *Bst {\n\treturn new(Bst).Init()\n}", "func newTreeNode(parent *treeNode, move Move, state GameState, ucbC float64) *treeNode {\n\t// Construct the new node.\n\tnode := treeNode{\n\t\tparent: parent,\n\t\tmove: move,\n\t\tstate: state,\n\t\ttotalOutcome: 0.0, // No outcome yet.\n\t\tvisits: 0, // No visits yet.\n\t\tuntriedMoves: state.AvailableMoves(), // Initially the node starts with every node unexplored.\n\t\tchildren: nil, // No children yet.\n\t\tucbC: ucbC, // Whole tree uses same constant.\n\t\tselectionScore: 0.0, // No value yet.\n\t\tplayer: state.PlayerJustMoved(),\n\t}\n\n\t// We're working with pointers.\n\treturn &node\n}", "func B(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"b\", Attributes: attrs, Children: children}\n}", "func NewTree(n *node) (*Tree, error) {\n\treturn &Tree{\n\t\troot: n,\n\t\tvalues: map[string]*node{n.value: n},\n\t}, nil\n}", "func NewTree(cs []Content) (*MerkleTree, error) {\n\tvar defaultHashStrategy = \"sha256\"\n\tt := &MerkleTree{\n\t\tHashStrategy: defaultHashStrategy,\n\t}\n\troot, leafs, err := buildWithContent(cs, t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt.Root = root\n\tt.Leafs = leafs\n\tt.MerkleRoot = root.Hash\n\treturn t, nil\n}", "func Json2Nbt(b []byte, byteOrder binary.ByteOrder) ([]byte, error) {\n\tnbtOut := new(bytes.Buffer)\n\tvar nbtJsonData NbtJson\n\tvar nbtTag interface{}\n\tvar nbtArray []interface{}\n\tvar err error\n\td := json.NewDecoder(bytes.NewBuffer(b))\n\td.UseNumber()\n\n\terr = d.Decode(&nbtJsonData)\n\tif err != nil {\n\t\treturn nil, JsonParseError{\"Error parsing JSON input. Is input JSON-formatted?\", err}\n\t}\n\ttemp, err := json.Marshal(nbtJsonData.Nbt)\n\tif err != nil {\n\t\treturn nil, JsonParseError{\"Error marshalling nbt: json.RawMessage\", err}\n\t}\n\td2 := json.NewDecoder(bytes.NewBuffer(temp))\n\td2.UseNumber()\n\terr = d2.Decode(&nbtArray)\n\n\tif err != nil {\n\t\treturn nil, JsonParseError{\"Error unmarshalling nbt: value\", err}\n\t}\n\tfor _, nbtTag = range nbtArray {\n\t\terr = writeTag(nbtOut, byteOrder, nbtTag)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn nbtOut.Bytes(), nil\n}", "func (p *Contentity) st2_Tree() *Contentity {\n\tif p.HasError() {\n\t\treturn p\n\t}\n\tp.logStg = \"22\"\n\tp.L(LProgress, \"=== 22:Tree ===\")\n\treturn p.\n\t\tst2a_PrepareToTree().\n\t\tst2b_BuildIntoTree().\n\t\tst2c_PostTreeMeta().\n\t\tst2d_NormalizeTree()\n}", "func NewTree(from []int) *Tree {\n\ttreeSize := calcTreeSize(len(from))\n\tnodes := make([]int, treeSize)\n\n\tt := &Tree{nodes, len(from)}\n\tt.build(from, 0, 0, len(from)-1)\n\n\treturn t\n}", "func (p *Contentity) st2a_PrepareToTree() *Contentity {\n\tif p.HasError() {\n\t\treturn p\n\t}\n\tp.logStg = \"2a\"\n\tvar e error\n\tswitch p.MarkupType() {\n\tcase SU.MU_type_XML:\n\t\tp.GTags, e = gtree.MakeGTagsFromGTokens(p.GTokens)\n\t\tif e != nil {\n\t\t\tp.WrapError(\"can't make gtags from xml gtokens\", e)\n\t\t\treturn p\n\t\t}\n\tcase SU.MU_type_MKDN:\n\t\tp.GTags, e = gtree.MakeGTagsFromGTokens(p.GTokens)\n\t\tif e != nil {\n\t\t\tp.WrapError(\"can't make gtags from mkdn gtokens\", e)\n\t\t\treturn p\n\t\t}\n\tcase SU.MU_type_HTML:\n\t\tp.GTags, e = gtree.MakeGTagsFromGTokens(p.GTokens)\n\t\tif e != nil {\n\t\t\tp.WrapError(\"can't make gtags from html gtokens\", e)\n\t\t\treturn p\n\t\t}\n\t}\n\treturn p\n}", "func getTreeGenerators(bFactors []int) ([]generator.Generator, error) {\n\tvar gens []generator.Generator\n\tfor _, b := range bFactors {\n\t\tt, err := tree.New(b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tgens = append(gens, t)\n\t}\n\treturn gens, nil\n}", "func NewTree() *Tree {\n\treturn new(Tree)\n}", "func GetDummyBinaryTree2() *TreeNode {\n\n\tsix := &TreeNode{Val: 6, Left: nil, Right: nil}\n\tfive := &TreeNode{Val: 5, Left: nil, Right: six}\n\tfour := &TreeNode{Val: 4, Left: nil, Right: nil}\n\tthree := &TreeNode{Val: 3, Left: nil, Right: nil}\n\ttwo := &TreeNode{Val: 2, Left: four, Right: five}\n\troot := &TreeNode{Val: 1, Left: two, Right: three}\n\treturn root\n}", "func NewBundParser(input antlr.TokenStream) *BundParser {\n\tthis := new(BundParser)\n\tdeserializer := antlr.NewATNDeserializer(nil)\n\tdeserializedATN := deserializer.DeserializeFromUInt16(parserATN)\n\tdecisionToDFA := make([]*antlr.DFA, len(deserializedATN.DecisionToState))\n\tfor index, ds := range deserializedATN.DecisionToState {\n\t\tdecisionToDFA[index] = antlr.NewDFA(ds, index)\n\t}\n\tthis.BaseParser = antlr.NewBaseParser(input)\n\n\tthis.Interpreter = antlr.NewParserATNSimulator(this, deserializedATN, decisionToDFA, antlr.NewPredictionContextCache())\n\tthis.RuleNames = ruleNames\n\tthis.LiteralNames = literalNames\n\tthis.SymbolicNames = symbolicNames\n\tthis.GrammarFileName = \"Bund.g4\"\n\n\treturn this\n}", "func NewTree(repo *Repository, id SHA1) *Tree {\n\treturn &Tree{\n\t\tID: id,\n\t\trepo: repo,\n\t}\n}", "func NewFromString(s string) (*Tree, error) {\n\treturn New(strings.NewReader(s))\n}", "func Yaml2Nbt(b []byte, byteOrder binary.ByteOrder) ([]byte, error) {\n\tmyJson, err := yaml.YAMLToJSON(b)\n\tif err != nil {\n\t\treturn nil, JsonParseError{\"Error converting YAML to JSON\", err}\n\t}\n\tnbtOut, err := Json2Nbt(myJson, byteOrder)\n\tif err != nil {\n\t\treturn nbtOut, err\n\t}\n\treturn nbtOut, nil\n}", "func NewString() *Tree {\n\ttree := &Tree{\n\t\tdatatype: containers.StringContainer(\"A\"),\n\t}\n\t// The below handling is required to achieve method overriding.\n\t// Refer: https://stackoverflow.com/questions/38123911/golang-method-override\n\ttree.TreeOperations = interface{}(tree).(binarytrees.TreeOperations)\n\treturn tree\n}", "func GenerateUnboundBinaryTree() UnboundBinaryTree {\n\treturn &ubtTree{}\n}", "func newAlohaTree(t *testing.T, db dbm.DB) (*iavl.MutableTree, types.CommitID) {\n\tt.Helper()\n\ttree := iavl.NewMutableTree(db, cacheSize, false, log.NewNopLogger())\n\n\tfor k, v := range treeData {\n\t\t_, err := tree.Set([]byte(k), []byte(v))\n\t\trequire.NoError(t, err)\n\t}\n\n\tfor i := 0; i < nMoreData; i++ {\n\t\tkey := randBytes(12)\n\t\tvalue := randBytes(50)\n\t\t_, err := tree.Set(key, value)\n\t\trequire.NoError(t, err)\n\t}\n\n\thash, ver, err := tree.SaveVersion()\n\trequire.Nil(t, err)\n\n\treturn tree, types.CommitID{Version: ver, Hash: hash}\n}", "func InitTree(symbol Symbol) (*Tree, error) {\n\thandler, err := getHandler(symbol)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Tree{symbol, make([]*Tree, 0, maxChildren), handler}, nil\n}", "func makeTree() redBlackTree {\n\ttree := redBlackTree{}\n\n\ttree.Insert(treeTestInt(1), \"one\")\n\ttree.Insert(treeTestInt(2), \"two\")\n\ttree.Insert(treeTestInt(3), \"three\")\n\ttree.Insert(treeTestInt(4), \"four\")\n\ttree.Insert(treeTestInt(5), \"five\")\n\ttree.Insert(treeTestInt(6), \"six\")\n\ttree.Insert(treeTestInt(7), \"seven\")\n\ttree.Insert(treeTestInt(8), \"eight\")\n\n\t// 4,B\n\t// / \\\n\t// 2,R 6,R\n\t// / \\ / \\\n\t// 1,B 3,B 5,B 7,B\n\t// \\\n\t// 8,R\n\n\treturn tree\n}", "func (f *Forest) New(d *crypto.Digest, l uint32) *Tree {\n\tt := &Tree{\n\t\tleaves: l,\n\t\tdig: d,\n\t\tf: f,\n\t\tlastBlockLen: BlockSize,\n\t\tleavesComplete: make([]bool, l),\n\t}\n\tf.writeTree(t)\n\treturn t\n}", "func main() {\n\tbase := initBTree()\n\tfmt.Println(\"pre order\")\n\tbase.preOrder()\n\tfmt.Println(\"in order\")\n\tbase.inOrder()\n\tfmt.Println(\"post order\")\n\tbase.postOrder()\n}", "func New() *Tree {\n\treturn &Tree{root: &node{}}\n}", "func New() Tree {\n\treturn &Node{Value: \".\"}\n}", "func New() *Tree {\n\treturn &Tree{}\n}", "func reconstructBSTFromTraversalData(ints ...int) *binaryTree {\n\n\tif len(ints) == 0 {\n\t\treturn nil\n\t}\n\tif len(ints) == 1 {\n\t\treturn &binaryTree{ints[0], \"\", nil, nil, nil}\n\t}\n\tif len(ints) == 2 && ints[0] > ints[1] {\n\t\tleft := &binaryTree{ints[1], \"\", nil, nil, nil}\n\t\troot := &binaryTree{ints[0], \"\", nil, left, nil}\n\t\treturn root\n\t}\n\tif len(ints) == 2 && ints[0] < ints[1] {\n\t\tright := &binaryTree{ints[1], \"\", nil, nil, nil}\n\t\troot := &binaryTree{ints[0], \"\", nil, nil, right}\n\t\treturn root\n\t}\n\n\trootData := ints[0]\n\troot := &binaryTree{rootData, \"\", nil, nil, nil}\n\tleftSubtree := []int{}\n\trightSubtree := []int{}\n\tlr := ints[1:]\n\tfor _, val := range lr {\n\t\tif val < rootData {\n\t\t\tleftSubtree = append(leftSubtree, val)\n\t\t} else {\n\t\t\trightSubtree = append(rightSubtree, val)\n\t\t}\n\t}\n\troot.left = reconstructBSTFromTraversalData(leftSubtree...)\n\troot.right = reconstructBSTFromTraversalData(rightSubtree...)\n\n\treturn root\n}", "func getTree(st interface{}, tree []interface{}, bp map[SubTree]interface{}) []interface{} {\n\tswitch vv := st.(type) {\n\tcase UnaryRule:\n\t\ttree = append(tree, vv.X)\n\t\ttree = append(tree, vv.Y)\n\tcase BPSubTree:\n\t\tleft := getTree(bp[vv.Left], tree, bp)\n\t\tright := getTree(bp[vv.Right], tree, bp)\n\t\ttree = append(tree, vv.Root)\n\t\ttree = append(tree, left)\n\t\ttree = append(tree, right)\n\t}\n\treturn tree\n}", "func TestNewBinarySearchTree(t *testing.T) {\n\tNewBinarySearchTree()\n}", "func NewTreeSaver(ctx context.Context, wg *errgroup.Group, treeWorkers uint, saveBlob func(ctx context.Context, t restic.BlobType, buf *Buffer, cb func(res SaveBlobResponse)), errFn ErrorFunc) *TreeSaver {\n\tch := make(chan saveTreeJob)\n\n\ts := &TreeSaver{\n\t\tch: ch,\n\t\tsaveBlob: saveBlob,\n\t\terrFn: errFn,\n\t}\n\n\tfor i := uint(0); i < treeWorkers; i++ {\n\t\twg.Go(func() error {\n\t\t\treturn s.worker(ctx, ch)\n\t\t})\n\t}\n\n\treturn s\n}", "func New() *Tree {\n\treturn &Tree{\n\t\tDelimiter: DefaultDelimiter,\n\t\tFormatter: SimpleFormatter,\n\t\tErrors: make(map[string]error),\n\t}\n}" ]
[ "0.62798727", "0.6265652", "0.6131476", "0.60316855", "0.598983", "0.5987959", "0.586644", "0.57734203", "0.5725015", "0.56773776", "0.5623112", "0.5601665", "0.5570188", "0.55306107", "0.54862183", "0.5454313", "0.5434976", "0.5397777", "0.53739434", "0.5341786", "0.53324336", "0.53078514", "0.53063756", "0.5298782", "0.52875924", "0.52699655", "0.5259695", "0.5242571", "0.5241595", "0.5222703", "0.52179164", "0.52159756", "0.5214729", "0.5213161", "0.520312", "0.51905364", "0.51890785", "0.514286", "0.51413566", "0.5137309", "0.5118594", "0.51159674", "0.51142174", "0.51050645", "0.50845325", "0.5078457", "0.50755244", "0.5068458", "0.5066423", "0.5064024", "0.50600964", "0.5027253", "0.50227547", "0.50134665", "0.5008246", "0.5006713", "0.50001854", "0.49888432", "0.49851584", "0.49842942", "0.49840784", "0.49796164", "0.49788594", "0.4962247", "0.49543485", "0.49466085", "0.4945169", "0.49379566", "0.49300632", "0.49047807", "0.48874745", "0.4883548", "0.48784897", "0.48463845", "0.48444474", "0.48297486", "0.48206934", "0.48202658", "0.48034966", "0.47844943", "0.47835067", "0.47805", "0.47698915", "0.47465655", "0.47434682", "0.4730771", "0.47288528", "0.47192731", "0.47121167", "0.46953478", "0.46903136", "0.4685659", "0.46841347", "0.46806082", "0.46743676", "0.4673452", "0.46723983", "0.46665084", "0.46624282", "0.46431714" ]
0.8195643
0
Dictionary returns the dictionary defined by this Huffman tree
func (t Tree) Dictionary() DictionaryType { result := DictionaryType{} t.buildDictionary(result, bitstream.BitStream{}, t.root) return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateBinaryTree() {\n\tfmt.Fprintln(os.Stderr, \"CreateBinaryTree\")\n\tvar min1i, min2i, pos1, pos2 int\n\tvar point []int = make([]int, MAX_CODE_LENGTH)\n\tvar code []byte = make([]byte, MAX_CODE_LENGTH)\n\tvar count []int64 = make([]int64, vocab_size*2+1)\n\tvar binaryt []int = make([]int, vocab_size*2+1)\n\tvar parent_node []int = make([]int, vocab_size*2+1)\n\tfor a := 0; a < vocab_size; a++ {\n\t\tcount[a] = int64(vocab[a].cn)\n\t}\n\tfor a := vocab_size; a < vocab_size*2; a++ {\n\t\tcount[a] = 1e15\n\t}\n\tpos1 = vocab_size - 1\n\tpos2 = vocab_size\n\t// Following algorithm constructs the Huffman tree by adding one node at a time\n\tfor a := 0; a < vocab_size-1; a++ {\n\t\t// First, find two smallest nodes 'min1, min2'\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin1i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin1i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin1i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin2i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin2i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin2i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tcount[vocab_size+a] = count[min1i] + count[min2i]\n\t\tparent_node[min1i] = vocab_size + a\n\t\tparent_node[min2i] = vocab_size + a\n\t\tbinaryt[min2i] = 1\n\t}\n\t// Now assign binary code to each vocabulary character\n\tfor a := 0; a < vocab_size; a++ {\n\t\tb := a\n\t\ti := 0\n\t\tfor {\n\t\t\tcode[i] = byte(binaryt[b])\n\t\t\tpoint[i] = b\n\t\t\ti++\n\t\t\tb = parent_node[b]\n\t\t\tif b == vocab_size*2-2 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tvocab[a].codelen = byte(i)\n\t\tvocab[a].point[0] = vocab_size - 2\n\t\tfor b = 0; b < i; b++ {\n\t\t\tvocab[a].code[i-b-1] = code[b]\n\t\t\tvocab[a].point[i-b] = point[b] - vocab_size\n\t\t}\n\t}\n}", "func buildPrefixTree(byteFrequencies *dictionary.Dictionary) *huffmanTreeNode {\n\ttree := new(priorityqueue.PriorityQueue)\n\tkeys := byteFrequencies.Keys()\n\n\tfor i := 0; i < keys.Size(); i++ {\n\t\tbyt := keys.MustGet(i)\n\t\tfrequency, _ := byteFrequencies.Get(byt)\n\n\t\ttree.Enqueue(frequency.(int), &huffmanTreeNode{frequency: frequency.(int), value: byt.(byte)})\n\t}\n\n\tfor tree.Size() > 1 {\n\t\taPrio, a := tree.Dequeue()\n\t\tbPrio, b := tree.Dequeue()\n\n\t\tnewPrio := aPrio + bPrio\n\n\t\tnode := &huffmanTreeNode{frequency: newPrio, left: a.(*huffmanTreeNode), right: b.(*huffmanTreeNode)}\n\n\t\ttree.Enqueue(newPrio, node)\n\t}\n\n\t_, root := tree.Dequeue()\n\n\treturn root.(*huffmanTreeNode)\n}", "func buildPatternDict(root *Node) (map[byte]ByteSeq, error) {\n\tleafNodes := make([]*Node, 0)\n\troot.InOrderTraversal(func(n *Node) {\n\t\tif n.IsLeaf() {\n\t\t\tleafNodes = append(leafNodes, n)\n\t\t}\n\t})\n\n\tdict := make(map[byte]ByteSeq)\n\tfor i := 0; i < len(leafNodes); i++ {\n\n\t\t// traverse to root\n\t\tvar byteSeq ByteSeq\n\t\tn := leafNodes[i]\n\t\tfor n != nil {\n\t\t\tp := n.parent\n\t\t\tif p == nil {\n\t\t\t\t// we are at the root, stop processing\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// add a bit depending on the if we are the left or right child\n\t\t\tif p.left == n {\n\t\t\t\tbyteSeq.AddBit(0)\n\t\t\t} else if p.right == n {\n\t\t\t\tbyteSeq.AddBit(1)\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"current node is not a child of its parent\")\n\t\t\t}\n\n\t\t\t// keep going up\n\t\t\tn = p\n\t\t}\n\n\t\tdict[leafNodes[i].symbol] = byteSeq\n\t}\n\n\treturn dict, nil\n}", "func makeHuffman(p priq.PriQ) *node {\n\trr, ok := p.Remove()\n\tif !ok {\n\t\tpanic(\"not enough elements in the priority queue to make a huffman tree\")\n\t}\t\n\tr := rr.(*node)\n\tll, ok := p.Remove()\n\tif !ok {\n\t\tpanic(\"not enough elements in the priority queue to make a huffman tree\")\n\t}\n\tl := ll.(*node)\t\n\tfor !p.Empty() {\n\t\tparent := new(node)\n\t\tparent.count = l.count + r.count\n\t\tparent.left = l\n\t\tparent.right = r\n\t\tp.Add(parent)\n\n\t\trr, ok = p.Remove()\n\t\tr = rr.(*node)\n\t\tll, ok = p.Remove()\n\t\tl = ll.(*node)\n\t}\n\troot := new(node)\n\troot.count = l.count + r.count\n\troot.left = l\n\troot.right = r\n\treturn root\n}", "func Constructor() WordDictionary {\n\treturn WordDictionary{root:newNode2(),size:0}\n}", "func GetTree() map[string]interface{} {\n\n\treturn tree\n\n}", "func NewHuffmanEncoder(inp io.ReadSeeker, wc io.Writer) *HuffmanEncoder {\n\the := new(HuffmanEncoder)\n\tfreq := make(map[byte]int)\n\n\tvar b [1]byte\n\t// using the reader, count the frequency of bytes\n\tfor {\n\t\t_, err := inp.Read(b[:])\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tpanic(err)\n\t\t}\n\n\t\t_, ok := freq[b[0]]\n\t\tif !ok {\n\t\t\tfreq[b[0]] = 0\n\t\t}\n\t\tfreq[b[0]]++\n\t}\n\t_, err := inp.Seek(0, io.SeekStart)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tpQ := make(PriorityQueue, len(freq))\n\ti := 0\n\tfor v, f := range freq {\n\t\tpQ[i] = NewHNode(v, f)\n\t\ti++\n\t}\n\n\theap.Init(&pQ)\n\n\tfor pQ.Len() > 1 {\n\t\tzero := pQ.Pop()\n\t\tl := zero.(Item)\n\t\tone := pQ.Pop()\n\t\tr := one.(Item)\n\t\tht := NewHTree(l, r)\n\t\theap.Push(&pQ, ht)\n\t}\n\n\thtree := pQ.Pop()\n\troot, ok := htree.(*HTree)\n\tif !ok {\n\t\tpanic(\"Huffman Tree\")\n\t}\n\the.root = root\n\the.dict = make(map[byte]Huffcode)\n\tfilldict(he.root, \"\", he.dict)\n\the.bw = bs.NewWriter(wc)\n\treturn he\n}", "func NewEncodingTree(freq map[uint8]uint) *Node {\n\tvar head Node // Fictitious head\n\n\tfor i, v := range freq {\n\t\tnode := &Node{\n\t\t\tvalue: i,\n\t\t\tweight: v,\n\t\t}\n\t\thead.insert(node)\n\t}\n\n\tfor head.next != nil && head.next.next != nil {\n\t\tl := head.popFirst()\n\t\tr := head.popFirst()\n\n\t\tnode := join(l, r)\n\t\thead.insert(node)\n\t}\n\n\t// Fictitious head point to tree root\n\tif head.next != nil {\n\t\thead.next.prev = nil\n\t}\n\treturn head.next\n}", "func Constructor() WordDictionary {\n\troot := TrieNode{}\n\troot.next = make([]*TrieNode, 26)\n\tw := WordDictionary{&root}\n\treturn w\n}", "func Constructor() WordDictionary {\n\treturn WordDictionary{head: &trieNode{}}\n}", "func Encode(input string) (string, *tree.Node[string]) {\n\t// Create huffman tree and map\n\thTree := getHuffmanTree(input)\n\tprintTree(hTree)\n\thMap := getHuffmanEncodingMap(hTree)\n\tbuilder := strings.Builder{}\n\tfor i := 0; i < len(input); i++ {\n\t\tbuilder.WriteString(hMap[string(input[i])])\n\t}\n\treturn builder.String(), hTree\n}", "func Constructor() WordDictionary {\n\treturn WordDictionary{\n\t\tTree: new(Trie),\n\t}\n}", "func main() {\r\n\ttest := \"abcdefghijklmnopqrstuvwxyz\"\r\n\r\n\tsymFreqs := make(map[rune]int)\r\n\t// read each symbol and record the frequencies\r\n\tfor _, c := range test {\r\n\t\tsymFreqs[c]++\r\n\t}\r\n\r\n\t// example tree\r\n\texampleTree := buildTree(symFreqs)\r\n\r\n\t// print out results\r\n\tfmt.Println(\"SYMBOL\\tWEIGHT\\tHUFFMAN CODE\")\r\n\tprintCodes(exampleTree, []byte{})\r\n}", "func dict(interpreter *Interpreter) {\n\tinterpreter.Push(NewDictionary(interpreter.PopInt()))\n}", "func constructTrie (p []string) (trie map[int]map[uint8]int, stateIsTerminal []bool, f map[int][]int) {\n trie = make(map[int]map[uint8]int)\n stateIsTerminal = make([]bool, 1)\n f = make(map[int][]int) \n state := 1\n if debugMode==true {\n fmt.Printf(\"\\n\\nTrie construction: \\n\")\n }\n createNewState(0, trie)\n for i:=0; i<len(p); i++ {\n current := 0\n j := 0\n for j < len(p[i]) && getTransition(current, p[i][j], trie) != -1 {\n current = getTransition(current, p[i][j], trie)\n j++\n }\n for j < len(p[i]) {\n stateIsTerminal = boolArrayCapUp(stateIsTerminal)\n createNewState(state, trie)\n stateIsTerminal[state] = false\n createTransition(current, p[i][j], state, trie)\n current = state\n j++\n state++\n }\n if stateIsTerminal[current] {\n newArray := intArrayCapUp(f[current])\n newArray[len(newArray)-1] = i\n f[current] = newArray //F(Current) <- F(Current) union {i}\n if debugMode==true {\n fmt.Printf(\" and %d\", i)\n }\n } else {\n stateIsTerminal[current] = true\n f[current] = []int {i} //F(Current) <- {i}\n if debugMode==true {\n fmt.Printf(\"\\n%d is terminal for word number %d\", current, i) \n }\n }\n }\n return trie, stateIsTerminal, f\n}", "func Constructor() WordDictionary {\n\treturn WordDictionary{\n\t\troot: getNode(),\n\t}\n}", "func BuildJpegHuffmanTable(count_in, symbols []int, lut []HuffmanTableEntry) int {\n\tvar (\n\t\tcode HuffmanTableEntry // current table entry\n\t\ttable []HuffmanTableEntry // next available space in table\n\t\tlength int // current code length\n\t\tidx int // symbol index\n\t\tkey int // prefix code\n\t\treps int // number of replicate key values in current table\n\t\tlow int // low bits for current root entry\n\t\ttable_bits int // key length of current table\n\t\ttable_size int // size of current table\n\t\ttotal_size int // sum of root table size and 2nd level table sizes\n\t)\n\n\t// Make a local copy of the input bit length histogram.\n\tvar count [kJpegHuffmanMaxBitLength + 1]int\n\ttotal_count := 0\n\tfor length = 1; length <= kJpegHuffmanMaxBitLength; length++ {\n\t\tcount[length] = count_in[length]\n\t\ttotal_count += count[length]\n\t}\n\n\ttable = lut\n\t// table_delta used in go version, to work around pointer arithmetic\n\ttable_delta := 0\n\ttable_bits = kJpegHuffmanRootTableBits\n\ttable_size = 1 << uint(table_bits)\n\ttotal_size = table_size\n\n\t// Special case code with only one value.\n\tif total_count == 1 {\n\t\tcode.bits = 0\n\t\tcode.value = uint16(symbols[0])\n\t\tfor key = 0; key < total_size; key++ {\n\t\t\ttable[key] = code\n\t\t}\n\t\treturn total_size\n\t}\n\n\t// Fill in root table.\n\tkey = 0\n\tidx = 0\n\tfor length = 1; length <= kJpegHuffmanRootTableBits; length++ {\n\t\tfor ; count[length] > 0; count[length]-- {\n\t\t\tcode.bits = uint8(length)\n\t\t\tcode.value = uint16(symbols[idx])\n\t\t\tidx++\n\t\t\treps = 1 << uint(kJpegHuffmanRootTableBits-length)\n\t\t\tfor ; reps > 0; reps-- {\n\t\t\t\ttable[key] = code\n\t\t\t\tkey++\n\t\t\t}\n\t\t}\n\t}\n\n\t// Fill in 2nd level tables and add pointers to root table.\n\ttable = table[table_size:]\n\ttable_delta += table_size\n\ttable_size = 0\n\tlow = 0\n\tfor length = kJpegHuffmanRootTableBits + 1; length <= kJpegHuffmanMaxBitLength; length++ {\n\t\tfor ; count[length] > 0; count[length]-- {\n\t\t\t// Start a new sub-table if the previous one is full.\n\t\t\tif low >= table_size {\n\t\t\t\ttable = table[table_size:]\n\t\t\t\ttable_delta += table_size\n\t\t\t\ttable_bits = NextTableBitSize(count[:], length)\n\t\t\t\ttable_size = 1 << uint(table_bits)\n\t\t\t\ttotal_size += table_size\n\t\t\t\tlow = 0\n\t\t\t\tlut[key].bits = uint8(table_bits + kJpegHuffmanRootTableBits)\n\t\t\t\tlut[key].value = uint16(table_delta - key)\n\t\t\t\tkey++\n\t\t\t}\n\t\t\tcode.bits = uint8(length - kJpegHuffmanRootTableBits)\n\t\t\tcode.value = uint16(symbols[idx])\n\t\t\tidx++\n\t\t\treps = 1 << uint(table_bits-int(code.bits))\n\t\t\tfor ; reps > 0; reps-- {\n\t\t\t\ttable[low] = code\n\t\t\t\tlow++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn total_size\n}", "func (t *Tree) Hash() []byte {\n\treturn t.rootNode.getHash()\n}", "func NewHuffmanEncoderWithDict(wc io.Writer, dict []byte) *HuffmanEncoder {\n\the := new(HuffmanEncoder)\n\n\tpQ := make(PriorityQueue, len(dict))\n\tMaxPri := len(dict)\n\tfor i, v := range dict {\n\t\tpQ[i] = NewHNode(v, MaxPri - i)\t// prioritize in order of dict\n\t}\n\n\theap.Init(&pQ)\n\n\tfor pQ.Len() > 1 {\n\t\tzero := pQ.Pop()\n\t\tl := zero.(Item)\n\t\tone := pQ.Pop()\n\t\tr := one.(Item)\n\t\tht := NewHTree(l, r)\n\t\theap.Push(&pQ, ht)\n\t}\n\n\thtree := pQ.Pop()\n\troot, ok := htree.(*HTree)\n\tif !ok {\n\t\tpanic(\"Huffman Tree\")\n\t}\n\the.root = root\n\the.dict = make(map[byte]Huffcode)\n\tfilldict(he.root, \"\", he.dict)\n\the.bw = bs.NewWriter(wc)\n\treturn he\n}", "func (t *Trie) Tree() gotree.Tree {\n\ttree := gotree.New(t.Name)\n\n\tt.treeAtNode(t.Root, tree)\n\n\treturn tree\n}", "func (d *Dictionary) Dictionary() arrow.Array {\n\tif d.dict == nil {\n\t\td.dict = MakeFromData(d.data.dictionary)\n\t}\n\treturn d.dict\n}", "func buildCodes(root *huffmanTreeNode, code *vector.Vector, result *dictionary.Dictionary) {\n\tif root == nil {\n\t\treturn\n\t}\n\n\tif isLeafNode(root) {\n\t\tresult.Set(root.value, code)\n\t}\n\n\tbuildCodes(root.left, code.AppendToCopy(byte(0)), result)\n\tbuildCodes(root.right, code.AppendToCopy(byte(1)), result)\n}", "func (j *JPEG) decodeHuffman(r io.Reader, h *huffman) (uint8, error) {\n\tif h.nCodes == 0 {\n\t\treturn 0, fmt.Errorf(\"uninitialized Huffman table\")\n\t}\n\n\t/*if d.bits.n < 8 {\n\t if err := d.ensureNBits(8); err != nil {\n\t if err != errMissingFF00 && err != errShortHuffmanData {\n\t return 0, err\n\t }\n\t // There are no more bytes of data in this segment, but we may still\n\t // be able to read the next symbol out of the previously read bits.\n\t // First, undo the readByte that the ensureNBits call made.\n\t if d.bytes.nUnreadable != 0 {\n\t d.unreadByteStuffedByte()\n\t }\n\t goto slowPath\n\t }\n\t }\n\t if v := h.lut[(d.bits.a>>uint32(d.bits.n-lutSize))&0xff]; v != 0 {\n\t n := (v & 0xff) - 1\n\t d.bits.n -= int32(n)\n\t d.bits.m >>= n\n\t return uint8(v >> 8), nil\n\t }*/\n\n\t//slowPath:\n\tfor i, code := 0, int32(0); i < maxCodeLength; i++ {\n\t\tif j.bits.n == 0 {\n\t\t\tif err := j.ensureNBits(r, 1); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t\tif j.bits.a&j.bits.m != 0 {\n\t\t\tcode |= 1\n\t\t}\n\t\tj.bits.n--\n\t\tj.bits.m >>= 1\n\t\tif code <= h.maxCodes[i] {\n\t\t\treturn h.vals[h.valsIndices[i]+code-h.minCodes[i]], nil\n\t\t}\n\t\tcode <<= 1\n\t}\n\treturn 0, fmt.Errorf(\"bad Huffman code\")\n}", "func filenodehash(filename string,ch string,nodenum int64,readbitlen int64) []byte{\n\t//H(ch)is parsed into k indexes.\n\t//Calculate the hash value HCH of ch\n\tvar Hch string = GetSHA256HashCodeString(ch)\n\tvar Hchbyte, _ = hex.DecodeString(Hch)\n\t//Hch,_ := hex.DecodeString(ch)\n\tfmt.Println(\"Hch is \", Hch)\n\tfmt.Println(\"Hchbyte is \", Hchbyte)\n\t//Convert Hch to 01 string\n\tvar Hchstring string = biu.ToBinaryString(Hchbyte)\n\t//remove all \"[\"\n\tHchstring = strings.Replace(Hchstring, \"[\", \"\", -1)\n\t//remove all \"]\"\n\tHchstring = strings.Replace(Hchstring, \"]\", \"\", -1)\n\t//remove all space\n\tHchstring = strings.Replace(Hchstring, \" \", \"\", -1)\n\tfmt.Println(\"Hchstring is \", Hchstring)\n\t//convert nodenum to 01\n\tvar bittosting string = biu.ToBinaryString(nodenum)\n\n\tbittosting = strings.Replace(bittosting, \"[\", \"\", -1)\n\tbittosting = strings.Replace(bittosting, \"]\", \"\", -1)\n\tbittosting = strings.Replace(bittosting, \" \", \"\", -1)\n\tvar stringlen = len(bittosting)\n\n\tfmt.Println(\"nodenum is \", bittosting)\n\tfmt.Println(\"stringlen is \", stringlen)\n\n\tvar stringiter int = 0\n\tvar zerolen int = 0\n\tfor stringiter = 0; stringiter < stringlen; stringiter++ {\n\t\tif '0' != bittosting[stringiter] {\n\t\t\t//zerolen = stringiter + 1\n\t\t\tzerolen = stringiter\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Println(\"zerolen is \", zerolen)\n\n\n\n\t//The calculation requires eachlen bits to represent the total number of leaf nodes.\n\t//For example, if the number of leaf nodes is 245441, 17 bits are needed to represent it\n\tvar eachlen uintptr = ((unsafe.Sizeof(nodenum) * 8) - uintptr(zerolen))\n\tfmt.Println(\"eachlen is \", eachlen)\n\n\n\n\t//由Hchstring切割得到原文件序号\n\tvar fileposition []int64\n\t//将Hchstring的bit字符串按每eachlen一份进行切割,生成[]string\n\tvar Hcharray []string = ChunkString(Hchstring, int(eachlen))\n\t//fmt.Println(\"chunkarray is \", chunkarray)\n\tvar filebititer int = 0\n\tfor filebititer = 0; filebititer < len(Hcharray); filebititer++ {\n\t\tvar tmpint int64 = 0\n\t\tvar partiter int = 0\n\t\tfor partiter = 0; partiter < len(Hcharray[filebititer]); partiter++ {\n\t\t\ttmpint = (tmpint << 1)\n\t\t\tif '1' == Hcharray[filebititer][partiter] {\n\t\t\t\ttmpint = (tmpint) ^ 1\n\t\t\t}\n\t\t\tif tmpint >= nodenum {\n\t\t\t\ttmpint = tmpint % nodenum\n\t\t\t}\n\n\t\t}\n\t\tfileposition = append(fileposition, tmpint)\n\t}\n\n\tfmt.Println(\"fileposition is \", fileposition)\n\tfileposition = RemoveRepeatedElement(fileposition)\n\tfmt.Println(\"fileposition is \", fileposition)\n\tvar fileretdata []byte\n\t//retdata, _ := ReadBlock(filename, readbitlen, 0*readbitlen)\n\t//fmt.Println(\"000000000000retdata is \", retdata)\n\tvar readiter int\n\tfor readiter = 0; readiter < len(fileposition); readiter++ {\n\t\t//fmt.Println(\"readiter is \", readiter)\n\t\t//fmt.Println(\"now fileposition is \", fileposition[readiter])\n\t\tretdata, _ := ReadBlock(filename, readbitlen, (fileposition[readiter])*readbitlen)\n\t\t//fmt.Println(\"retdata is \", retdata)\n\t\tfor _,nounceum := range retdata{\n\t\t\tfileretdata=append(fileretdata,nounceum)\n\t\t}\n\n\t}\n\tfmt.Println(\"fileretdata is \", fileretdata)\n\tfileretdata_hash := GetSHA256HashCode([]byte(fileretdata))\n\n\tvar filebyte_hash []byte\n\tfilebyte_hash, _ = hex.DecodeString(fileretdata_hash)\n\tfmt.Println(\"filebyte_hash is \", filebyte_hash)\n\treturn filebyte_hash\n\n}", "func decodeHuffmanCode(codes *vector.Vector, index int, root *huffmanTreeNode, to *vector.Vector) (int, error) {\n\tif root == nil {\n\t\treturn 0, errors.New(\"No prefix tree supplied\")\n\t}\n\n\tif isLeafNode(root) {\n\t\tto.Append(root.value)\n\t\treturn index, nil\n\t}\n\n\tnext := codes.MustGet(index)\n\tswitch next {\n\tcase byte(0):\n\t\treturn decodeHuffmanCode(codes, index+1, root.left, to)\n\tcase byte(1):\n\t\treturn decodeHuffmanCode(codes, index+1, root.right, to)\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"An unexpected symbol %x found in the compressed data\", next)\n\t}\n}", "func (mt *MerkleTree) HashCode() []byte {\n\treturn mt.hashCode\n}", "func Constructor() MyHashMap {\n\treturn MyHashMap{[10005][]Node{}}\n}", "func Constructor() MyHashMap {\n\treturn MyHashMap{0, InitContainer, make([]*Node, InitContainer)}\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tif root == nil {\n\t\treturn \"\"\n\t}\n\tmaps := make(map[int64]int)\n\n\tmaps[1] = root.Val\n\tinnerSerialize(root.Right, &maps, 3)\n\tinnerSerialize(root.Left, &maps, 2)\n\tfmt.Println(maps)\n\n\treturn stringfy(&maps)\n}", "func NewDict() *Dictionary {\n\treturn &Dictionary{trie: cedar.New()}\n}", "func Constructor() MyHashMap {\n\treturn MyHashMap{make([]*Node, 10000), 10000}\n}", "func (n *ForNode) Tree() *Tree { return n.tree }", "func Constructor() MyHashMap {\n\treturn MyHashMap{\n\t\t[1111]*Node{},\n\t}\n}", "func (enc *HuffmanEncoder) WriteHeader() error {\n\t// for iterative tree walking use savedict\n\t// for recursive, use rsavedict\n\n\t// if err := savedict(enc.bw, enc.root); err != nil {\n\tif err := rsavedict(enc.bw, enc.root); err != nil {\t\t// recursive version\n\t\treturn err\n\t}\n\treturn enc.bw.WriteBit(bs.Zero) // end of dictionary indicator\n}", "func buildTree(in []int, post []int, len int) *Node {\r\n\tmp = make(map[int]int)\r\n\tfor i := range in {\r\n\t\tk := in[i]\r\n\t\tv := i\r\n\t\tmp[k] = v\r\n\t}\r\n\r\n\tindex := len - 1 //index in postorder\r\n\treturn buildUtil(in[:], post[:], 0, len-1, &index)\r\n}", "func decompressPrefixTree(compressed *vector.Vector, index int) (*huffmanTreeNode, int) {\n\tbyt := compressed.MustGet(index).(byte)\n\tswitch byt {\n\tcase byte(0):\n\t\tleft, nextIndex := decompressPrefixTree(compressed, index+1)\n\t\tright, nextIndex := decompressPrefixTree(compressed, nextIndex)\n\t\treturn &huffmanTreeNode{left: left, right: right}, nextIndex\n\n\tcase byte(1):\n\t\treturn &huffmanTreeNode{value: compressed.MustGet(index + 1).(byte)}, index + 2\n\n\tdefault:\n\t\treturn nil, index + 1\n\t}\n}", "func Constructor() WordDictionary {\n \n}", "func buildNodeRegistry(g *simple.DirectedGraph) map[string]Node {\n\tres := make(map[string]Node)\n\n\tnodeIt := g.Nodes()\n\n\tfor nodeIt.Next() {\n\t\tif dpNode, ok := nodeIt.Node().(Node); ok {\n\t\t\tres[dpNode.RefID()] = dpNode\n\t\t}\n\t}\n\n\treturn res\n}", "func main() {\n\tvar n int\n\t_, _ = fmt.Scanf(\"%d\", &n)\n\ttree := make(map[int][]int)\n\n\tvar parent, root int\n\tfor i := 0; i < n; i++ {\n\t\t_, _ = fmt.Scanf(\"%d\", &parent)\n\t\tif parent == -1 {\n\t\t\troot = i\n\t\t} else {\n\t\t\ttree[parent] = append(tree[parent], i)\n\t\t}\n\t}\n\n\theight := heightTree(tree, root)\n\n\tfmt.Printf(\"%d\", height)\n}", "func Constructor() MyHashMap {\n\tsize := 100\n\thm := MyHashMap{\n\t\tArrays: make([]*Node, size),\n\t\tSize: 100,\n\t\tHashFunc: func(key int) int {\n\t\t\treturn key % size\n\t\t},\n\t}\n\n\treturn hm\n}", "func (enc *HuffmanEncoder) Write(p []byte) (n int, err error) {\n\tfor _, v := range p {\n\t\tcode, ok := enc.dict[v]\n\t\tif !ok {\n\t\t\tpanic(errors.New(\"non-existant uncompressed code \" + string(v)))\n\t\t}\n\n\t\terr = enc.bw.WriteBits(code.hcode, code.nbits)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn len(p), nil\n}", "func CreateDictionary(corpus io.Reader) Dictionary {\n\troot := trie.CreateNode(\"\")\n\tscanner := bufio.NewScanner(corpus)\n\n\tisDelimiter := func(c rune) bool {\n\t\treturn !unicode.IsLetter(c)\n\t}\n\n\tfor scanner.Scan() {\n\t\ts := scanner.Text()\n\t\tfor _, w := range strings.FieldsFunc(s, isDelimiter) {\n\t\t\troot.Insert(strings.ToLower(w))\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn Dictionary{Root: &root}\n}", "func CreateTree(file string) LongParseTree {\n\tpTree := LongParseTree{dictionary : CreateTrie(file)}\n\n\tpTree.frontDepChar = make(map[rune]bool)\n\tpTree.frontDepChar['Ð'] = true\n\tpTree.frontDepChar['Ñ'] = true\n\tpTree.frontDepChar['Ò'] = true\n\tpTree.frontDepChar['Ó'] = true\n\tpTree.frontDepChar['Ô'] = true\n\tpTree.frontDepChar['Õ'] = true\n\tpTree.frontDepChar['Ö'] = true\n\tpTree.frontDepChar['×'] = true\n\tpTree.frontDepChar['Ø'] = true\n\tpTree.frontDepChar['Ù'] = true\n\tpTree.frontDepChar['å'] = true\n\tpTree.frontDepChar['ç'] = true\n\tpTree.frontDepChar['ì'] = true\n\tpTree.frontDepChar['í'] = true\n\n\tpTree.rearDepChar = make(map[rune]bool)\n\tpTree.rearDepChar['Ñ'] = true\n\tpTree.rearDepChar['×'] = true\n\tpTree.rearDepChar['à'] = true\n\tpTree.rearDepChar['á'] = true\n\tpTree.rearDepChar['â'] = true\n\tpTree.rearDepChar['ã'] = true\n\tpTree.rearDepChar['ä'] = true\n\tpTree.rearDepChar['í'] = true\n\n\tpTree.tonalChar = make(map[rune]bool)\n\tpTree.tonalChar['è'] = true\n\tpTree.tonalChar['é'] = true\n\tpTree.tonalChar['ê'] = true\n\tpTree.tonalChar['ë'] = true\n\n\tpTree.endingChar = make(map[rune]bool)\n\tpTree.endingChar['æ'] = true\n\tpTree.endingChar['Ï'] = true\n\n\treturn pTree\n}", "func (d *decoder) createTree() *node {\n\tif val, _ := readBit(d.r); val {\n\t\treturn &node{readByte(d.r), -1, false, nil, nil}\n\t} else if d.numChars != d.numCharsDecoded {\n\t\tleft := d.createTree()\n\t\tright := d.createTree()\n\t\treturn &node{0, -1, true, left, right}\n\t}\n\n\treturn nil\n}", "func (dict Dictionary) State() DictionaryState {\n\treturn DictionaryState{\n\t\tStoreState: dict.Store.State(),\n\t\tShortIndex: len(dict.shortIndex),\n\t\tLongIndex: len(dict.longIndex),\n\t}\n}", "func (n *node) Hash() []byte {\n\treturn n.hash\n}", "func (*MerkleHash) Descriptor() ([]byte, []int) {\n\treturn file_proof_proto_rawDescGZIP(), []int{0}\n}", "func Encode(in, out *os.File) {\n\tcounts := count(in)\n\tp := makePQ(counts)\n\th := makeHuffman(p)\n\tm := make(map[byte]string)\n\tfillMap(h, m, \"\")\n\tfor k, v := range m {\n\t\tfmt.Printf(\"k: %c, v: %s\\n\", k, v)\n\t}\n}", "func (d *Dictionary) GetBinaryCodec() binary.Codec {\n\treturn new(dictionaryCodec)\n}", "func (t *BinaryTree) Size() int { return t.count }", "func (node *avlBetterTreeNode) values() (key string, value interface{}) {\n\treturn node.k, node.v\n}", "func BuildTree(platform string, low, high, key int) *Tree {\n\tif (high < low) || (low > high) {\n\t\t//base case\n\t\treturn nil\n\t} else if low == high {\n\t\t//base case\n\t\tnode1 := Tree{\n\t\t\tR: emojiDictAvg[platform][low].R,\n\t\t\tG: emojiDictAvg[platform][low].G,\n\t\t\tB: emojiDictAvg[platform][low].B,\n\t\t\tURLIndex: emojiDictAvg[platform][low].URLIndex,\n\t\t}\n\t\treturn &node1\n\t} else {\n\t\t//recursive step\n\t\t//sort colors by current key\n\t\tswitch key {\n\t\tcase 0:\n\t\t\tsort.Sort(ByRed(emojiDictAvg[platform][low:high]))\n\t\tcase 1:\n\t\t\tsort.Sort(ByGreen(emojiDictAvg[platform][low:high]))\n\t\tcase 2:\n\t\t\tsort.Sort(ByBlue(emojiDictAvg[platform][low:high]))\n\t\t}\n\n\t\t//get median\n\t\tmedianIndex := (low + high) / 2\n\t\tmedianColor := emojiDictAvg[platform][medianIndex]\n\t\tparent := Tree{\n\t\t\tR: medianColor.R,\n\t\t\tG: medianColor.G,\n\t\t\tB: medianColor.B,\n\t\t\tURLIndex: medianColor.URLIndex,\n\t\t}\n\n\t\t//create Tree struct for median and build its left and right children recursively\n\t\tkey = (key + 1) % 3\n\t\tleft := BuildTree(platform, low, medianIndex-1, key)\n\t\tright := BuildTree(platform, medianIndex+1, high, key)\n\n\t\tparent.Left = left\n\t\tparent.Right = right\n\n\t\treturn &parent\n\t}\n}", "func newTree(segmentSize, maxsize, depth int, hashfunc func() hash.Hash) *tree {\n\tn := newNode(0, nil, hashfunc())\n\tprevlevel := []*node{n}\n\t// iterate over levels and creates 2^(depth-level) nodes\n\t// the 0 level is on double segment sections so we start at depth - 2\n\tcount := 2\n\tfor level := depth - 2; level >= 0; level-- {\n\t\tnodes := make([]*node, count)\n\t\tfor i := 0; i < count; i++ {\n\t\t\tparent := prevlevel[i/2]\n\t\t\tnodes[i] = newNode(i, parent, hashfunc())\n\t\t}\n\t\tprevlevel = nodes\n\t\tcount *= 2\n\t}\n\t// the datanode level is the nodes on the last level\n\treturn &tree{\n\t\tleaves: prevlevel,\n\t\tbuffer: make([]byte, maxsize),\n\t}\n}", "func Constructor() WordDictionary {\n\treturn WordDictionary{\n\t\tNexts: make([]*WordDictionary, 26),\n\t}\n}", "func encodeToHuffmanCodes(uncompressed *vector.Vector, codes *dictionary.Dictionary) *vector.Vector {\n\tencodedHuffmanCodes := vector.New()\n\n\tfor i := 0; i < uncompressed.Size(); i++ {\n\t\tbyt := uncompressed.MustGet(i)\n\n\t\tiCode, _ := codes.Get(byt)\n\t\tcode := iCode.(*vector.Vector)\n\n\t\tfor j := 0; j < code.Size(); j++ {\n\t\t\tencodedHuffmanCodes.Append(code.MustGet(j))\n\t\t}\n\t}\n\n\treturn encodedHuffmanCodes\n}", "func (enc *HuffmanEncoder) ShowHuffTree() {\n\ttraverse(enc.root, \"\")\n}", "func (h *BSTHandler) CalculateTreeWidth() {\n\n}", "func (freqs frequencies) getCodes(root node) (c Code) {\n\tc = make(Code)\n\tfor _, n := range freqs {\n\t\tc[n.b], _ = root.find(n)\n\t}\n\treturn\n}", "func main() {\n\torbits := tree{}\n\n\tif len(os.Args) < 2 {\n\t\tlog.Fatalf(\"Missing parameter, provide file name!\")\n\t\treturn\n\t}\n\n\t// raw reading of the file\n\tdata, err := ioutil.ReadFile(os.Args[1])\n\tif err != nil {\n\t\tlog.Fatalf(\"Can't read file: %v\\n\", os.Args[1])\n\t\tpanic(err)\n\t}\n\n\t// take the read file and convert it from strings to ints\n\tfor _, line := range bytes.Split(data, []byte(\"\\n\")) {\n\t\tplanets := strings.Split(strings.TrimSpace(string(line)), \")\")\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Could not extract planets from line. %v\\n\", err)\n\t\t}\n\n\t\torbits[planets[0]] = append(orbits[planets[0]], planets[1])\n\t}\n\n\tspew.Dump(\"Result:\")\n\t//\tspew.Dump(orbits)\n\n\t//\tfmt.Printf(\"nodes:%d\\n\", orbits.height(\"COM\"))\n\t//\tfmt.Printf(\"count:%d\\n\", orbits.count(\"COM\", 0))\n\tfmt.Printf(\"p:%v\\n\", orbits.parent(\"B\"))\n\tfmt.Printf(\"p:%v\\n\", orbits.parent(\"COM\"))\n\tfmt.Printf(\"q:%v\\n\", orbits.ancestry(\"YOU\"))\n\tfmt.Printf(\"q:%v\\n\", orbits.ancestry(\"SAN\"))\n\tfmt.Printf(\"q:%v\\n\", orbits.transfers(\"YOU\", \"SAN\"))\n\n}", "func (self *PEFile) GetDirectories() *ordereddict.Dict {\n\tresult := ordereddict.NewDict()\n\n\tfor _, i := range []struct {\n\t\tidx int64\n\t\tname string\n\t}{\n\t\t{IMAGE_DIRECTORY_ENTRY_ARCHITECTURE, \"Architecture_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_BASERELOC, \"Base_Relocation_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT, \"Bound_Import_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, \"DotNet_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_DEBUG, \"Debug_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT, \"Delay_Imports_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_EXCEPTION, \"Exception_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_EXPORT, \"Export_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_GLOBALPTR, \"Global_Ptr_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_IAT, \"IAT_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_IMPORT, \"Import_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, \"Load_Config_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_RESOURCE, \"Resource_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_SECURITY, \"Security_Directory\"},\n\t\t{IMAGE_DIRECTORY_ENTRY_TLS, \"TLS_Directory\"},\n\t} {\n\t\tdir := self.nt_header.DataDirectory(i.idx)\n\t\tif dir.DirSize() > 0 {\n\t\t\tfile_address := dir.VirtualAddress()\n\t\t\tvar section_name string\n\n\t\t\tsection := findSection(self.Sections, int64(file_address))\n\t\t\tif section != nil {\n\t\t\t\tsection_name = section.Name\n\t\t\t}\n\n\t\t\tgen_dir := self.nt_header.Profile.GENERIC_DIRECTORY(\n\t\t\t\tself.nt_header.Reader, int64(dir.VirtualAddress()))\n\t\t\tresult.Set(i.name, Directory{\n\t\t\t\tSize: dir.DirSize(),\n\t\t\t\t// This is really a file address\n\t\t\t\tFileAddress: file_address,\n\t\t\t\tTimestamp: gen_dir.TimeDateStamp().Time,\n\t\t\t\tTimestampRaw: gen_dir.TimeDateStamp().Raw,\n\t\t\t\tSectionName: section_name,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn result\n}", "func (s *SymbolDictionary) IsHuffmanEncoded() bool {\n\treturn s.isHuffmanEncoded\n}", "func HuffmanOnlyDeflate(d policies.DEFLATE,data []byte) []byte {\n\tbuf := new(bytes.Buffer)\n\tw,e := flate.NewWriter(buf,flate.HuffmanOnly)\n\tif e!=nil { panic(e) }\n\tw.Write(data)\n\tw.Close()\n\treturn buf.Bytes()\n}", "func (r *Repository) Tree(h plumbing.Hash) (*Tree, error) {\n\ttree, err := r.Object(plumbing.TreeObject, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tree.(*Tree), nil\n}", "func HashToTree(hash map[Point][]*Point, root Point) Tree {\n\t// Build a tree and specify the value\n\tvar tree Tree\n\ttree.Value = root\n\n\t// Iterate over every element of this root\n\tfor i := 0; i < len(hash[root]); i++ {\n\t\tnewRootPointer := hash[root][i]\n\n\t\t// TODO: The slice shouldn't contain the key-root\n\t\t// (second condition of the if statement should\n\t\t// always be false)\n\t\tif newRootPointer == nil || *newRootPointer == root {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Form a tree with each children\n\t\tvar newTree = HashToTree(hash, *newRootPointer)\n\n\t\t// Append the formed tree to this element's nodes\n\t\ttree.Nodes = append(tree.Nodes, &newTree)\n\t}\n\treturn tree\n}", "func (me *TrieNode) height() int {\n\tif me == nil {\n\t\treturn 0\n\t}\n\treturn int(me.h)\n}", "func (n *TreeNode) Weight() Value {\n\treturn n.weight\n}", "func buildAndStoreCommandPrefixCode(histogram []uint32, depth []byte, bits []uint16, storage_ix *uint, storage []byte) {\n\tvar tree [129]huffmanTree\n\tvar cmd_depth = [numCommandSymbols]byte{0}\n\t/* Tree size for building a tree over 64 symbols is 2 * 64 + 1. */\n\n\tvar cmd_bits [64]uint16\n\tcreateHuffmanTree(histogram, 64, 15, tree[:], depth)\n\tcreateHuffmanTree(histogram[64:], 64, 14, tree[:], depth[64:])\n\n\t/* We have to jump through a few hoops here in order to compute\n\t the command bits because the symbols are in a different order than in\n\t the full alphabet. This looks complicated, but having the symbols\n\t in this order in the command bits saves a few branches in the Emit*\n\t functions. */\n\tcopy(cmd_depth[:], depth[24:][:24])\n\n\tcopy(cmd_depth[24:][:], depth[:8])\n\tcopy(cmd_depth[32:][:], depth[48:][:8])\n\tcopy(cmd_depth[40:][:], depth[8:][:8])\n\tcopy(cmd_depth[48:][:], depth[56:][:8])\n\tcopy(cmd_depth[56:][:], depth[16:][:8])\n\tconvertBitDepthsToSymbols(cmd_depth[:], 64, cmd_bits[:])\n\tcopy(bits, cmd_bits[24:][:8])\n\tcopy(bits[8:], cmd_bits[40:][:8])\n\tcopy(bits[16:], cmd_bits[56:][:8])\n\tcopy(bits[24:], cmd_bits[:24])\n\tcopy(bits[48:], cmd_bits[32:][:8])\n\tcopy(bits[56:], cmd_bits[48:][:8])\n\tconvertBitDepthsToSymbols(depth[64:], 64, bits[64:])\n\t{\n\t\t/* Create the bit length array for the full command alphabet. */\n\t\tvar i uint\n\t\tfor i := 0; i < int(64); i++ {\n\t\t\tcmd_depth[i] = 0\n\t\t} /* only 64 first values were used */\n\t\tcopy(cmd_depth[:], depth[24:][:8])\n\t\tcopy(cmd_depth[64:][:], depth[32:][:8])\n\t\tcopy(cmd_depth[128:][:], depth[40:][:8])\n\t\tcopy(cmd_depth[192:][:], depth[48:][:8])\n\t\tcopy(cmd_depth[384:][:], depth[56:][:8])\n\t\tfor i = 0; i < 8; i++ {\n\t\t\tcmd_depth[128+8*i] = depth[i]\n\t\t\tcmd_depth[256+8*i] = depth[8+i]\n\t\t\tcmd_depth[448+8*i] = depth[16+i]\n\t\t}\n\n\t\tstoreHuffmanTree(cmd_depth[:], numCommandSymbols, tree[:], storage_ix, storage)\n\t}\n\n\tstoreHuffmanTree(depth[64:], 64, tree[:], storage_ix, storage)\n}", "func (o *wordTrie) put(key ngram) {\n\tcurrent := o.root\n\tvar i int\n\tfor ; i < len(key)-1; i++ {\n\t\tcurrent = current.children[key[i]]\n\t}\n\tnode, ok := current.children[key[i]]\n\tif ok {\n\t\tnode.freq++\n\t} else {\n\t\tnode = newNode(1)\n\t\tcurrent.children[key[i]] = node\n\t}\n\tnode.prob = float64(node.freq) / float64(current.freq)\n}", "func Constructor() MapSum {\n\treturn MapSum{\n\t\thash: make(map[string]int),\n\t\troot: &TrieNode{children: make(map[byte]*TrieNode)},\n\t}\n}", "func (t *Tree) Digest() *crypto.Digest { return t.dig }", "func Constructor() WordDictionary {\n\treturn WordDictionary{}\n}", "func New() Hashmap {\n\treturn Hashmap{make([]node, defaultSize), defaultSize, 0}\n}", "func (*Dict) Descriptor() ([]byte, []int) {\n\treturn file_message_proto_rawDescGZIP(), []int{2}\n}", "func calculateHeightmap(c *Chunk) heightmap {\n\th := make(heightmap, 256)\n\n\thighestY := 0\n\tfor y := range c.sub {\n\t\tif c.sub[y] != nil {\n\t\t\thighestY = (y << 4) + 15\n\t\t}\n\t}\n\tif highestY == 0 {\n\t\t// No sub chunks present at all.\n\t\treturn h\n\t}\n\n\tfor x := uint8(0); x < 16; x++ {\n\t\tfor z := uint8(0); z < 16; z++ {\n\t\t\tfor y := highestY; y >= 0; y-- {\n\t\t\t\tyVal := uint8(y)\n\t\t\t\tlocalYVal := uint8(y) & 0xf\n\t\t\t\tsub := subByY(yVal, c)\n\t\t\t\tif filterLevel(sub, x, localYVal, z) > 0 {\n\t\t\t\t\th.set(x, z, yVal)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn h\n}", "func NewDictionary() *Dictionary {\n\tds := make(map[string]handle.Handler)\n\td := &Dictionary{\n\t\thandle: 0,\n\t\titem: ds,\n\t}\n\treturn d\n}", "func (l *labelInfo) getHash() (LabelHash, error) {\n\ttargetBytes, err := json.Marshal(*l)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar targetMap map[string]any\n\tif err = json.Unmarshal(targetBytes, &targetMap); err != nil {\n\t\treturn \"\", err\n\t}\n\ts := sortMap(targetMap)\n\ts = sortSimpleMap(s)\n\treturn LabelHash(rawHash(s)), nil\n}", "func (m RedisPlugin) GraphDefinition() map[string](mp.Graphs) {\n\tlabelPrefix := strings.Title(m.Prefix)\n\treturn map[string](mp.Graphs){\n\t\tm.Prefix: mp.Graphs{\n\t\t\tLabel: labelPrefix,\n\t\t\tUnit: \"float\",\n\t\t\tMetrics: [](mp.Metrics){\n\t\t\t\tmp.Metrics{Name: m.metricName(), Label: m.SubRedisOpt.Addr},\n\t\t\t},\n\t\t},\n\t}\n}", "func (s *cayleyStore) Tree(in string, dir Direction) *Vertex {\n\tif err := s.ctx.Err(); err != nil {\n\t\treturn nil\n\t}\n\tdefer s.Unlock()\n\ts.Lock()\n\tvisited := make(map[string]*Vertex)\n\t// follow in a recursive approach for now\n\t// XXX-TBD(sanjayt): Move to a stack based non-recursive approach\n\treturn s.getVertex(in, dir, visited)\n}", "func (g *DGraph) Dump() AdjacencyList {\n\tresult := make(map[string][]string, len(g.Set))\n\n\tfor key, node := range g.Set {\n\t\tchildren := make([]string, 0, len(node.Children))\n\n\t\tfor k, _ := range node.Children {\n\t\t\tchildren = append(children, k)\n\t\t}\n\n\t\tresult[key] = children\n\t}\n\n\treturn result\n}", "func HashTreeSize(leafs Nodes) int64 {\n\treturn HashNumber(leafs, Levels(leafs), 0)\n}", "func getdict(interpreter *Interpreter) {\n\tkey := interpreter.PopName()\n\tdictionary := interpreter.Pop().(Dictionary)\n\tinterpreter.Push(dictionary[key])\n}", "func (cd *ContinueDecompress) DictionarySize() int {\n\treturn cd.dictionarySize\n}", "func createGraph() *Graph {\n var g = Graph{}\n g.adjList = make(map[int]set)\n return &g\n}", "func Constructor() Trie {\n\treturn Trie{data: [26]*Trie{}}\n}", "func (cc *ContinueCompress) DictionarySize() int {\n\treturn cc.dictionarySize\n}", "func Constructor() MagicDictionary {\n\twords := make(map[int][]string)\n\treturn MagicDictionary{words: words}\n}", "func New(hashFunc func(i interface{}) int64) *rbTree {\n\treturn &rbTree{hashFunc: hashFunc}\n}", "func mkNumCompressDFA() map[Tri]int {\n\t// symbols := \"cd.\"\n\tdfa := make(map[Tri]int)\n\n\tdfa[Tri{state: START, word: \"X\", pos: \"cd\"}] = START\n\tdfa[Tri{state: INTERM, word: \"X\", pos: \"cd\"}] = ACCEPT\n\tdfa[Tri{state: REJECT, word: \"X\", pos: \"cd\"}] = START\n\tdfa[Tri{state: ACCEPT, word: \"X\", pos: \"cd\"}] = START\n\n\tdfa[Tri{state: START, word: \".\", pos: \".\"}] = INTERM\n\tdfa[Tri{state: INTERM, word: \".\", pos: \".\"}] = REJECT\n\tdfa[Tri{state: REJECT, word: \".\", pos: \".\"}] = REJECT\n\tdfa[Tri{state: ACCEPT, word: \".\", pos: \".\"}] = REJECT\n\n\tdfa[Tri{state: START, word: \"?\", pos: \".\"}] = REJECT\n\tdfa[Tri{state: INTERM, word: \"?\", pos: \".\"}] = REJECT\n\tdfa[Tri{state: REJECT, word: \"?\", pos: \".\"}] = REJECT\n\tdfa[Tri{state: ACCEPT, word: \"?\", pos: \".\"}] = REJECT\n\n\tdfa[Tri{state: START, word: \"!\", pos: \".\"}] = REJECT\n\tdfa[Tri{state: INTERM, word: \"!\", pos: \".\"}] = REJECT\n\tdfa[Tri{state: REJECT, word: \"!\", pos: \".\"}] = REJECT\n\tdfa[Tri{state: ACCEPT, word: \"!\", pos: \".\"}] = REJECT\n\n\tdfa[Tri{state: START, word: \"X\", pos: \"X\"}] = REJECT\n\tdfa[Tri{state: INTERM, word: \"X\", pos: \"X\"}] = REJECT\n\tdfa[Tri{state: REJECT, word: \"X\", pos: \"X\"}] = REJECT\n\tdfa[Tri{state: ACCEPT, word: \"X\", pos: \"X\"}] = REJECT\n\n\treturn dfa\n}", "func Constructor() Trie {\n return Trie{newNode()}\n}", "func (algo *GPSW06) KeyGen(tree Node, msk *MasterKey) (*DecryptKey, error) {\n\t// polynomials holds a mapping of Node to slice of coefficients for\n\t// the polynomial of corresponding node.\n\t// Length of each slice equals to Threshold of node\n\tpolynomials := make(map[Node]*polynomial)\n\n\t// leaves stores the computed decryption keys of each of the leaf attributes\n\tleaves := make(map[int]*G1)\n\n\t// queue holds the children nodes which will be processed later.\n\tqueue := []Node{tree}\n\n\t// Breadth first traversal of tree\n\tvar current Node\n\tfor len(queue) > 0 {\n\t\t// Dequeue\n\t\tcurrent, queue = queue[0], queue[1:]\n\n\t\t// Define degree of polynomial\n\t\tpolynomials[current] = newPolynomial(current.Threshold())\n\n\t\t// if current node is root\n\t\tif current.Parent() == nil {\n\t\t\t// Set q_r(0) as y\n\t\t\tpolynomials[current].c[0] = pairing.NewZr().Set(msk.y)\n\t\t} else {\n\t\t\t// for any other node,\n\t\t\t// set q_x(0) = q_parent(x) (Index(x))\n\t\t\tindex := pairing.NewZr().SetInt32(int32(current.Index()))\n\t\t\tpolynomials[current].c[0] = polynomials[current.Parent()].evaluate(index)\n\t\t}\n\n\t\t// Randomly choose the rest of the coefficients to completely define q_x\n\t\tfor i := 1; i < len(polynomials[current].c); i++ {\n\t\t\tpolynomials[current].c[i] = pairing.NewZr().Rand()\n\t\t}\n\n\t\tswitch node := current.(type) {\n\t\tcase *leafNode:\n\t\t\t// Compute q_x(0) / t_i\n\t\t\tqx := polynomials[current].evaluate(zero).ThenDiv(msk.t[node.Attr])\n\t\t\t// Compute g^(q_x(0) / t_i)\n\t\t\tleaves[node.Attr] = pairing.NewG1().PowZn(g1, qx)\n\t\tcase *nonLeafNode:\n\t\t\t// Enqueue the current node's children\n\t\t\tqueue = append(queue, node.Children...)\n\t\tdefault:\n\t\t\treturn nil, ErrUnknownNodeType\n\t\t}\n\t}\n\n\tn, err := tree.MarshalJSON()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &DecryptKey{leaves, n}, nil\n}", "func newTrieNode() *trieNode {\n\treturn &trieNode{\n\t\tchildren: make(map[rune]*trieNode),\n\t}\n}", "func (p InodePlugin) GraphDefinition() map[string]mp.Graphs {\n\treturn map[string]mp.Graphs{\n\t\t\"inode.count.#\": {\n\t\t\tLabel: \"Inode\",\n\t\t\tUnit: \"integer\",\n\t\t\tMetrics: []mp.Metrics{\n\t\t\t\t{Name: \"used\", Label: \"used\"},\n\t\t\t\t{Name: \"free\", Label: \"free\"},\n\t\t\t\t{Name: \"total\", Label: \"total\"},\n\t\t\t},\n\t\t},\n\t\t\"inode.percentage.#\": {\n\t\t\tLabel: \"Inode Percentage\",\n\t\t\tUnit: \"percentage\",\n\t\t\tMetrics: []mp.Metrics{\n\t\t\t\t{Name: \"used\", Label: \"used %\"},\n\t\t\t},\n\t\t},\n\t}\n}", "func (s *SymbolDictionary) GetDictionary() ([]*bitmap.Bitmap, error) {\n\tcommon.Log.Trace(\"[SYMBOL-DICTIONARY] GetDictionary begins...\")\n\tdefer func() {\n\t\tcommon.Log.Trace(\"[SYMBOL-DICTIONARY] GetDictionary finished\")\n\t}()\n\n\tif s.exportSymbols == nil {\n\t\tvar err error\n\t\tif s.useRefinementAggregation {\n\t\t\ts.sbSymCodeLen = s.getSbSymCodeLen()\n\t\t}\n\n\t\tif !s.isHuffmanEncoded {\n\t\t\tif err = s.setCodingStatistics(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\t// 6.5.5. 1)\n\t\ts.newSymbols = make([]*bitmap.Bitmap, s.numberOfNewSymbols)\n\n\t\t// 6.5.5. 2)\n\t\tvar newSymbolsWidth []int\n\t\tif s.isHuffmanEncoded && !s.useRefinementAggregation {\n\t\t\tnewSymbolsWidth = make([]int, s.numberOfNewSymbols)\n\t\t}\n\n\t\tif err = s.setSymbolsArray(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// 6.5.5 3)\n\t\tvar heightClassHeight, temp int64\n\t\ts.numberOfDecodedSymbols = 0\n\n\t\t// 6.5.5 4 a)\n\t\tfor s.numberOfDecodedSymbols < s.numberOfNewSymbols {\n\t\t\t// 6.5.5 4 b)\n\t\t\ttemp, err = s.decodeHeightClassDeltaHeight()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\theightClassHeight += temp\n\n\t\t\tvar symbolWidth, totalWidth int\n\t\t\theightClassFirstSymbolIndex := s.numberOfDecodedSymbols\n\n\t\t\t// 6.5.5 4 c)\n\t\t\t// Repeat until OOB - OOB sends a break\n\t\t\tfor {\n\t\t\t\t// 4 c) i)\n\t\t\t\tvar differenceWidth int64\n\t\t\t\tdifferenceWidth, err = s.decodeDifferenceWidth()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tif differenceWidth == math.MaxInt64 || s.numberOfDecodedSymbols >= s.numberOfNewSymbols {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tsymbolWidth += int(differenceWidth)\n\t\t\t\ttotalWidth += symbolWidth\n\n\t\t\t\t//* 4 c) ii)\n\t\t\t\tif !s.isHuffmanEncoded || s.useRefinementAggregation {\n\n\t\t\t\t\tif !s.useRefinementAggregation {\n\t\t\t\t\t\t// 6.5.8.1 - Directly coded\n\t\t\t\t\t\terr = s.decodeDirectlyThroughGenericRegion(symbolWidth, int(heightClassHeight))\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// 6.5.8.2 - Refinement / Aggregate -coded\n\t\t\t\t\t\terr = s.decodeAggregate(symbolWidth, int(heightClassHeight))\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if s.isHuffmanEncoded && !s.useRefinementAggregation {\n\t\t\t\t\t// 4 c) iii)\n\t\t\t\t\tnewSymbolsWidth[s.numberOfDecodedSymbols] = symbolWidth\n\t\t\t\t}\n\t\t\t\ts.numberOfDecodedSymbols++\n\t\t\t}\n\n\t\t\t// 6.5.5 4 d)\n\t\t\tif s.isHuffmanEncoded && !s.useRefinementAggregation {\n\t\t\t\tvar bmSize int64\n\t\t\t\tif s.sdHuffBMSizeSelection == 0 {\n\t\t\t\t\tvar st huffman.Tabler\n\t\t\t\t\tst, err = huffman.GetStandardTable(1)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tbmSize, err = st.Decode(s.r)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tbmSize, err = s.huffDecodeBmSize()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ts.r.Align()\n\n\t\t\t\tvar heightClassCollectiveBitmap *bitmap.Bitmap\n\t\t\t\theightClassCollectiveBitmap, err = s.decodeHeightClassCollectiveBitmap(\n\t\t\t\t\tbmSize, int(heightClassHeight), totalWidth)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\terr = s.decodeHeightClassBitmap(\n\t\t\t\t\theightClassCollectiveBitmap, heightClassFirstSymbolIndex,\n\t\t\t\t\tint(heightClassHeight), newSymbolsWidth,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// 5)\n\t\t// 6.5.10 1) - 5\n\t\texFlags, err := s.getToExportFlags()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.setExportedSymbols(exFlags)\n\t}\n\treturn s.exportSymbols, nil\n}", "func createFrequencyTable(bytes *vector.Vector) *dictionary.Dictionary {\n\tdict := dictionary.New()\n\tfor i := 0; i < bytes.Size(); i++ {\n\t\tbyt := bytes.MustGet(i)\n\n\t\tif frequency, exists := dict.Get(byt); !exists {\n\t\t\tdict.Set(byt, 1)\n\t\t} else {\n\t\t\tdict.Set(byt, frequency.(int)+1)\n\t\t}\n\t}\n\n\treturn dict\n}", "func (*ZkContractToTreeWitnessInfo) Descriptor() ([]byte, []int) {\n\treturn file_witness_proto_rawDescGZIP(), []int{21}\n}", "func (n *Node) Code() (r uint64, bits byte) {\n\tfor parent := n.Parent; parent != nil; n, parent = parent, parent.Parent {\n\t\tif parent.Right == n { // bit 1\n\t\t\tr |= 1 << bits\n\t\t} // else bit 0 => nothing to do with r\n\t\tbits++\n\t}\n\treturn\n}", "func GetCharDict() (charDict, error) {\n\tresp, err := http.Get(\n\t\t\"https://commons.wikimedia.org/wiki/Commons:Chinese_characters_decomposition\")\n\n\tif err != nil {\n\t\treturn charDict{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\traw, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn charDict{}, err\n\t}\n\n\tl, err := extractTableLines(raw)\n\tif err != nil {\n\t\treturn charDict{}, err\n\t}\n\n\tcd := charDict{sha: sha256.Sum256(raw)}\n\tcd.populate(l)\n\n\treturn cd, nil\n}", "func (m *Machine) Data() map[string]any {\n\tm.dataMu.Lock()\n\tdefer m.dataMu.Unlock()\n\n\tres := make(map[string]any, len(m.data))\n\tfor k, v := range m.data {\n\t\tres[k] = v\n\t}\n\n\treturn res\n}", "func NewDictionary(strs ...string) *DFA {\n\tb := NewBuilder()\n\tsort.Strings(strs)\n\tfor _, str := range strs {\n\t\tif err := b.Add(str, 1); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn b.Build()\n}", "func (it *Iter) Key() byte { return it.top().key }" ]
[ "0.5447956", "0.538165", "0.5371014", "0.5146767", "0.5137261", "0.51136523", "0.5054502", "0.5002691", "0.49787515", "0.49382988", "0.49126276", "0.48784593", "0.4843514", "0.4808261", "0.48030126", "0.4782607", "0.4734426", "0.46656606", "0.4654483", "0.46402845", "0.4590309", "0.4581705", "0.45572463", "0.45501485", "0.45331088", "0.45205247", "0.45202845", "0.44964817", "0.44946265", "0.4480179", "0.44799122", "0.44762635", "0.44561604", "0.44201228", "0.4409916", "0.43717793", "0.43692327", "0.43640834", "0.4345346", "0.4341059", "0.4323698", "0.43159753", "0.430291", "0.42994976", "0.42974734", "0.42764553", "0.42742512", "0.42368782", "0.42344624", "0.42271334", "0.42268467", "0.42224988", "0.42150897", "0.42146543", "0.42062837", "0.42050245", "0.41851136", "0.41817823", "0.41635835", "0.41631544", "0.41610223", "0.41424274", "0.41092244", "0.41079485", "0.41063344", "0.40982977", "0.4094921", "0.40913227", "0.40908214", "0.40899754", "0.4075516", "0.40701377", "0.40699962", "0.40568104", "0.4047849", "0.40291753", "0.4025316", "0.4023659", "0.40186492", "0.4006074", "0.4003836", "0.40012875", "0.39978993", "0.39840475", "0.39827764", "0.397675", "0.39758676", "0.39708656", "0.39698318", "0.39612743", "0.39582774", "0.39573422", "0.3956241", "0.39559835", "0.3955883", "0.39529642", "0.3951435", "0.39500013", "0.39495137", "0.3946718" ]
0.634084
0
Interpret yilds a byte by interpreting the given bitstream on this Huffman tree
func (t Tree) Interpret(bs *bitstream.BitStream) byte { return t.walk(t.root, bs) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func decodeHuffmanCode(codes *vector.Vector, index int, root *huffmanTreeNode, to *vector.Vector) (int, error) {\n\tif root == nil {\n\t\treturn 0, errors.New(\"No prefix tree supplied\")\n\t}\n\n\tif isLeafNode(root) {\n\t\tto.Append(root.value)\n\t\treturn index, nil\n\t}\n\n\tnext := codes.MustGet(index)\n\tswitch next {\n\tcase byte(0):\n\t\treturn decodeHuffmanCode(codes, index+1, root.left, to)\n\tcase byte(1):\n\t\treturn decodeHuffmanCode(codes, index+1, root.right, to)\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"An unexpected symbol %x found in the compressed data\", next)\n\t}\n}", "func (s *scanner) Process(b byte) (oper op, err error) {\n\tvar include bool\n\tnext := s.s\n\n\t// 1. Determine State Transition\n\t//\n\t// Find out what the next state of our byte-interpretation (scanState)\n\t// is. Determine the high level operation that needs to happen, if any\n\t// need to. Determine whether to include the examined byte as a value\n\t// in our buffer: not all semantic bytes that are examined have value,\n\t// for example the prototypical 't' for true is both a semantic and\n\t// value byte, 'i' denoting an int is only semantically meaningful but\n\t// provides no value to the integer being described.\n\tswitch s.s {\n\tcase scanFindToken:\n\t\tnext, oper, include, err = s.enc.mustFindToken(b)\n\tcase scanTokenLen:\n\t\tnext, oper, include, err = s.enc.scanTokenLen(b)\n\tcase scanSymbol:\n\t\tnext, oper, include = s.processLengthDeterminedType(valSymbolOp)\n\tcase scanString:\n\t\tnext, oper, include = s.processLengthDeterminedType(valStringOp)\n\tcase scanByteArr:\n\t\tnext, oper, include = s.processLengthDeterminedType(valByteArrOp)\n\tcase scanInt:\n\t\tnext, oper, include, err = s.enc.scanIntToken(b)\n\tcase scanFirstInt:\n\t\tnext, oper, include, err = s.enc.scanFirstIntToken(b)\n\tcase scanFloat64:\n\t\tnext, oper, include, err = s.enc.scanFloat64Token(b)\n\tcase scanFloat32:\n\t\tnext, oper, include, err = s.enc.scanFloat32Token(b)\n\tdefault:\n\t\terr = fmt.Errorf(\"syrup unknown scanstate: %d\", s.s)\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// 2. Include the bytes into the buffer if necessary.\n\tif include {\n\t\t// strings.Builder.WriteByte always returns 'nil'\n\t\t_ = s.buf.WriteByte(b)\n\t}\n\t// 3. In the special case of parsing a token-length, set our internal\n\t// buffer and length counters appropriately.\n\t//\n\t// Unfortunately this is a leak between the encoding and this generic\n\t// scanner.\n\tif s.s == scanTokenLen && next != scanTokenLen {\n\t\tif oper, err = s.processParsedLen(next); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\t// 4. Finally, transition to the next state.\n\ts.s = next\n\t// 5. If a value-op was returned, it is up to the caller to ensure they\n\t// call one of the value functions, which has the side effect of\n\t// clearing the internal buffer.\n\treturn\n}", "func (j *JPEG) decodeHuffman(r io.Reader, h *huffman) (uint8, error) {\n\tif h.nCodes == 0 {\n\t\treturn 0, fmt.Errorf(\"uninitialized Huffman table\")\n\t}\n\n\t/*if d.bits.n < 8 {\n\t if err := d.ensureNBits(8); err != nil {\n\t if err != errMissingFF00 && err != errShortHuffmanData {\n\t return 0, err\n\t }\n\t // There are no more bytes of data in this segment, but we may still\n\t // be able to read the next symbol out of the previously read bits.\n\t // First, undo the readByte that the ensureNBits call made.\n\t if d.bytes.nUnreadable != 0 {\n\t d.unreadByteStuffedByte()\n\t }\n\t goto slowPath\n\t }\n\t }\n\t if v := h.lut[(d.bits.a>>uint32(d.bits.n-lutSize))&0xff]; v != 0 {\n\t n := (v & 0xff) - 1\n\t d.bits.n -= int32(n)\n\t d.bits.m >>= n\n\t return uint8(v >> 8), nil\n\t }*/\n\n\t//slowPath:\n\tfor i, code := 0, int32(0); i < maxCodeLength; i++ {\n\t\tif j.bits.n == 0 {\n\t\t\tif err := j.ensureNBits(r, 1); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t\tif j.bits.a&j.bits.m != 0 {\n\t\t\tcode |= 1\n\t\t}\n\t\tj.bits.n--\n\t\tj.bits.m >>= 1\n\t\tif code <= h.maxCodes[i] {\n\t\t\treturn h.vals[h.valsIndices[i]+code-h.minCodes[i]], nil\n\t\t}\n\t\tcode <<= 1\n\t}\n\treturn 0, fmt.Errorf(\"bad Huffman code\")\n}", "func decodeTree(r *bitio.Reader, nTree byte) (root *Node, err error) {\n\tvar head Node\n\tvar nodes byte\n\tvar leaves byte\n\tvar u uint64\n\n\tfor nodes < nTree {\n\t\tu, err = r.ReadBits(1)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif u == 1 {\n\t\t\tleaves++\n\t\t\tsymbol, err := r.ReadBits(8)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnode := &Node{value: byte(symbol)}\n\t\t\thead.pushBack(node)\n\t\t}\n\n\t\tif u == 0 {\n\t\t\tnodes++\n\t\t\tif nodes == nTree {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tr := head.popLast()\n\t\t\tl := head.popLast()\n\t\t\tnode := join(l, r)\n\t\t\thead.pushBack(node)\n\t\t}\n\t}\n\n\tif nodes != leaves {\n\t\terr = errors.New(\"nodes != leaves\")\n\t}\n\n\treturn head.next, err\n}", "func (this *ExpGolombDecoder) DecodeByte() byte {\n\tif this.bitstream.ReadBit() == 1 {\n\t\treturn 0\n\t}\n\n\t// Decode unsigned\n\tlog2 := uint(1)\n\n\tfor {\n\t\tif this.bitstream.ReadBit() == 1 {\n\t\t\tbreak\n\t\t}\n\n\t\tlog2++\n\t}\n\n\tif this.signed == true {\n\t\t// Decode signed: read value + sign\n\t\tval := this.bitstream.ReadBits(log2 + 1)\n\t\tres := val>>1 + 1<<log2 - 1\n\n\t\tif val&1 == 1 {\n\t\t\treturn byte(^res + 1)\n\t\t}\n\n\t\treturn byte(res)\n\t}\n\n\t// Decode unsigned\n\tval := this.bitstream.ReadBits(log2)\n\treturn byte((1 << log2) - 1 + val)\n}", "func (d *decoder) decodeHeader() {\n\t// first byte is the number of leaf nodes\n\td.numChars = uint8(readByte(d.r))\n\n\t// read in the total number of characters in the encoded data\n\tbuf := make([]byte, 2)\n\tbuf[0] = readByte(d.r)\n\tbuf[1] = readByte(d.r)\n\n\td.numCharsEncoded = binary.LittleEndian.Uint16(buf)\n\n\t// deserialize the tree\n\td.root = d.createTree()\n}", "func (r *Reader) readHuff(data block, off int, table []uint16) (tableBits, roff int, err error) {\n\tif off >= len(data) {\n\t\treturn 0, 0, r.makeEOFError(off)\n\t}\n\n\thdr := data[off]\n\toff++\n\n\tvar weights [256]uint8\n\tvar count int\n\tif hdr < 128 {\n\t\t// The table is compressed using an FSE. RFC 4.2.1.2.\n\t\tif len(r.fseScratch) < 1<<6 {\n\t\t\tr.fseScratch = make([]fseEntry, 1<<6)\n\t\t}\n\t\tfseBits, noff, err := r.readFSE(data, off, 255, 6, r.fseScratch)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\t\tfseTable := r.fseScratch\n\n\t\tif off+int(hdr) > len(data) {\n\t\t\treturn 0, 0, r.makeEOFError(off)\n\t\t}\n\n\t\trbr, err := r.makeReverseBitReader(data, off+int(hdr)-1, noff)\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\n\t\tstate1, err := rbr.val(uint8(fseBits))\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\n\t\tstate2, err := rbr.val(uint8(fseBits))\n\t\tif err != nil {\n\t\t\treturn 0, 0, err\n\t\t}\n\n\t\t// There are two independent FSE streams, tracked by\n\t\t// state1 and state2. We decode them alternately.\n\n\t\tfor {\n\t\t\tpt := &fseTable[state1]\n\t\t\tif !rbr.fetch(pt.bits) {\n\t\t\t\tif count >= 254 {\n\t\t\t\t\treturn 0, 0, rbr.makeError(\"Huffman count overflow\")\n\t\t\t\t}\n\t\t\t\tweights[count] = pt.sym\n\t\t\t\tweights[count+1] = fseTable[state2].sym\n\t\t\t\tcount += 2\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tv, err := rbr.val(pt.bits)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, 0, err\n\t\t\t}\n\t\t\tstate1 = uint32(pt.base) + v\n\n\t\t\tif count >= 255 {\n\t\t\t\treturn 0, 0, rbr.makeError(\"Huffman count overflow\")\n\t\t\t}\n\n\t\t\tweights[count] = pt.sym\n\t\t\tcount++\n\n\t\t\tpt = &fseTable[state2]\n\n\t\t\tif !rbr.fetch(pt.bits) {\n\t\t\t\tif count >= 254 {\n\t\t\t\t\treturn 0, 0, rbr.makeError(\"Huffman count overflow\")\n\t\t\t\t}\n\t\t\t\tweights[count] = pt.sym\n\t\t\t\tweights[count+1] = fseTable[state1].sym\n\t\t\t\tcount += 2\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tv, err = rbr.val(pt.bits)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, 0, err\n\t\t\t}\n\t\t\tstate2 = uint32(pt.base) + v\n\n\t\t\tif count >= 255 {\n\t\t\t\treturn 0, 0, rbr.makeError(\"Huffman count overflow\")\n\t\t\t}\n\n\t\t\tweights[count] = pt.sym\n\t\t\tcount++\n\t\t}\n\n\t\toff += int(hdr)\n\t} else {\n\t\t// The table is not compressed. Each weight is 4 bits.\n\n\t\tcount = int(hdr) - 127\n\t\tif off+((count+1)/2) >= len(data) {\n\t\t\treturn 0, 0, io.ErrUnexpectedEOF\n\t\t}\n\t\tfor i := 0; i < count; i += 2 {\n\t\t\tb := data[off]\n\t\t\toff++\n\t\t\tweights[i] = b >> 4\n\t\t\tweights[i+1] = b & 0xf\n\t\t}\n\t}\n\n\t// RFC 4.2.1.3.\n\n\tvar weightMark [13]uint32\n\tweightMask := uint32(0)\n\tfor _, w := range weights[:count] {\n\t\tif w > 12 {\n\t\t\treturn 0, 0, r.makeError(off, \"Huffman weight overflow\")\n\t\t}\n\t\tweightMark[w]++\n\t\tif w > 0 {\n\t\t\tweightMask += 1 << (w - 1)\n\t\t}\n\t}\n\tif weightMask == 0 {\n\t\treturn 0, 0, r.makeError(off, \"bad Huffman weights\")\n\t}\n\n\ttableBits = 32 - bits.LeadingZeros32(weightMask)\n\tif tableBits > maxHuffmanBits {\n\t\treturn 0, 0, r.makeError(off, \"bad Huffman weights\")\n\t}\n\n\tif len(table) < 1<<tableBits {\n\t\treturn 0, 0, r.makeError(off, \"Huffman table too small\")\n\t}\n\n\t// Work out the last weight value, which is omitted because\n\t// the weights must sum to a power of two.\n\tleft := (uint32(1) << tableBits) - weightMask\n\tif left == 0 {\n\t\treturn 0, 0, r.makeError(off, \"bad Huffman weights\")\n\t}\n\thighBit := 31 - bits.LeadingZeros32(left)\n\tif uint32(1)<<highBit != left {\n\t\treturn 0, 0, r.makeError(off, \"bad Huffman weights\")\n\t}\n\tif count >= 256 {\n\t\treturn 0, 0, r.makeError(off, \"Huffman weight overflow\")\n\t}\n\tweights[count] = uint8(highBit + 1)\n\tcount++\n\tweightMark[highBit+1]++\n\n\tif weightMark[1] < 2 || weightMark[1]&1 != 0 {\n\t\treturn 0, 0, r.makeError(off, \"bad Huffman weights\")\n\t}\n\n\t// Change weightMark from a count of weights to the index of\n\t// the first symbol for that weight. We shift the indexes to\n\t// also store how many we have seen so far,\n\tnext := uint32(0)\n\tfor i := 0; i < tableBits; i++ {\n\t\tcur := next\n\t\tnext += weightMark[i+1] << i\n\t\tweightMark[i+1] = cur\n\t}\n\n\tfor i, w := range weights[:count] {\n\t\tif w == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tlength := uint32(1) << (w - 1)\n\t\ttval := uint16(i)<<8 | (uint16(tableBits) + 1 - uint16(w))\n\t\tstart := weightMark[w]\n\t\tfor j := uint32(0); j < length; j++ {\n\t\t\ttable[start+j] = tval\n\t\t}\n\t\tweightMark[w] += length\n\t}\n\n\treturn tableBits, off, nil\n}", "func (e EmptyNode) DecodeBinary(*io.BinReader) {\n}", "func decodeNode(hash, buf []byte, cachegen uint16) (node, error) {\n\tif len(buf) == 0 {\n\t\treturn nil, io.ErrUnexpectedEOF\n\t}\n\telems, _, err := ser.SplitList(buf)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"decode error: %v\", err)\n\t}\n\tswitch c, _ := ser.CountValues(elems); c {\n\tcase 2:\n\t\tn, err := decodeShort(hash, elems, cachegen)\n\t\treturn n, wrapError(err, \"short\")\n\tcase 17:\n\t\tn, err := decodeFull(hash, elems, cachegen)\n\t\treturn n, wrapError(err, \"full\")\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid number of list elements: %v\", c)\n\t}\n}", "func getBitFromByte(b byte, indexInByte int) byte {\n\tb = b << uint(indexInByte)\n\tvar mask byte = 0x80\n\n\tvar bit byte = mask & b\n\n\tif bit == 128 {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (t *Tokeniser) tokeniseByte(b byte) bool {\n\tif t.escapeNextChar {\n\t\tt.put(b)\n\t\tt.escapeNextChar = false\n\t\treturn false\n\t}\n\n\tfuncs := map[quoteType]func(b byte) bool{\n\t\tnone: t.tokeniseNoQuotes,\n\t\tsingle: t.tokeniseSingleQuotes,\n\t\tdouble: t.tokeniseDoubleQuotes,\n\t}\n\n\treturn funcs[t.currentQuoteType](b)\n}", "func decompressPrefixTree(compressed *vector.Vector, index int) (*huffmanTreeNode, int) {\n\tbyt := compressed.MustGet(index).(byte)\n\tswitch byt {\n\tcase byte(0):\n\t\tleft, nextIndex := decompressPrefixTree(compressed, index+1)\n\t\tright, nextIndex := decompressPrefixTree(compressed, nextIndex)\n\t\treturn &huffmanTreeNode{left: left, right: right}, nextIndex\n\n\tcase byte(1):\n\t\treturn &huffmanTreeNode{value: compressed.MustGet(index + 1).(byte)}, index + 2\n\n\tdefault:\n\t\treturn nil, index + 1\n\t}\n}", "func (p *Parser) emitByte(b byte) {\n\tp.chunk.Write(b, p.previous.line)\n}", "func (p *ubPayload) Decode(enc []byte) (graph.NodePayload, error) {\n\tin := string(enc)\n\tl := in[0] - charOffset\n\tflags, e := strconv.Atoi(in[1 : 1+l])\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tret := &ubPayload{flags: flags, suffix: in[1+l:]}\n\treturn ret, nil\n}", "func parseBranch(data []byte, i int) (Node, int) {\n\tif data[i] != '(' {\n\t\tpanic(fmt.Sprintf(\"internal error at offset %d: expected '(', got %c\", i, data[i]))\n\t}\n\ti++\n\tvar br BranchNode\n\tfor i < len(data) {\n\t\tnode, j := parseSequence(data, i)\n\t\tif j > i {\n\t\t\tbr = append(br, node)\n\t\t}\n\t\tswitch data[j] {\n\t\tcase ')':\n\t\t\treturn br, j\n\t\tcase '|':\n\t\t\ti = j + 1\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"parse error at offset %d: expected ')' or '|', got %c (%[1]d)\", j, data[j]))\n\t\t}\n\t}\n\tpanic(\"unexpected end of input\")\n}", "func (p *Lexer) Byte() (byte, error) {\n\tif p.lastByte < bufSize && p.r >= p.lastByte {\n\t\tp.r = p.lastByte + 1\n\t\treturn 0, ErrEOS\n\t}\n\n\tc := p.buf[p.r]\n\tp.r++\n\tp.fill()\n\treturn c, nil\n}", "func filenodehash(filename string,ch string,nodenum int64,readbitlen int64) []byte{\n\t//H(ch)is parsed into k indexes.\n\t//Calculate the hash value HCH of ch\n\tvar Hch string = GetSHA256HashCodeString(ch)\n\tvar Hchbyte, _ = hex.DecodeString(Hch)\n\t//Hch,_ := hex.DecodeString(ch)\n\tfmt.Println(\"Hch is \", Hch)\n\tfmt.Println(\"Hchbyte is \", Hchbyte)\n\t//Convert Hch to 01 string\n\tvar Hchstring string = biu.ToBinaryString(Hchbyte)\n\t//remove all \"[\"\n\tHchstring = strings.Replace(Hchstring, \"[\", \"\", -1)\n\t//remove all \"]\"\n\tHchstring = strings.Replace(Hchstring, \"]\", \"\", -1)\n\t//remove all space\n\tHchstring = strings.Replace(Hchstring, \" \", \"\", -1)\n\tfmt.Println(\"Hchstring is \", Hchstring)\n\t//convert nodenum to 01\n\tvar bittosting string = biu.ToBinaryString(nodenum)\n\n\tbittosting = strings.Replace(bittosting, \"[\", \"\", -1)\n\tbittosting = strings.Replace(bittosting, \"]\", \"\", -1)\n\tbittosting = strings.Replace(bittosting, \" \", \"\", -1)\n\tvar stringlen = len(bittosting)\n\n\tfmt.Println(\"nodenum is \", bittosting)\n\tfmt.Println(\"stringlen is \", stringlen)\n\n\tvar stringiter int = 0\n\tvar zerolen int = 0\n\tfor stringiter = 0; stringiter < stringlen; stringiter++ {\n\t\tif '0' != bittosting[stringiter] {\n\t\t\t//zerolen = stringiter + 1\n\t\t\tzerolen = stringiter\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Println(\"zerolen is \", zerolen)\n\n\n\n\t//The calculation requires eachlen bits to represent the total number of leaf nodes.\n\t//For example, if the number of leaf nodes is 245441, 17 bits are needed to represent it\n\tvar eachlen uintptr = ((unsafe.Sizeof(nodenum) * 8) - uintptr(zerolen))\n\tfmt.Println(\"eachlen is \", eachlen)\n\n\n\n\t//由Hchstring切割得到原文件序号\n\tvar fileposition []int64\n\t//将Hchstring的bit字符串按每eachlen一份进行切割,生成[]string\n\tvar Hcharray []string = ChunkString(Hchstring, int(eachlen))\n\t//fmt.Println(\"chunkarray is \", chunkarray)\n\tvar filebititer int = 0\n\tfor filebititer = 0; filebititer < len(Hcharray); filebititer++ {\n\t\tvar tmpint int64 = 0\n\t\tvar partiter int = 0\n\t\tfor partiter = 0; partiter < len(Hcharray[filebititer]); partiter++ {\n\t\t\ttmpint = (tmpint << 1)\n\t\t\tif '1' == Hcharray[filebititer][partiter] {\n\t\t\t\ttmpint = (tmpint) ^ 1\n\t\t\t}\n\t\t\tif tmpint >= nodenum {\n\t\t\t\ttmpint = tmpint % nodenum\n\t\t\t}\n\n\t\t}\n\t\tfileposition = append(fileposition, tmpint)\n\t}\n\n\tfmt.Println(\"fileposition is \", fileposition)\n\tfileposition = RemoveRepeatedElement(fileposition)\n\tfmt.Println(\"fileposition is \", fileposition)\n\tvar fileretdata []byte\n\t//retdata, _ := ReadBlock(filename, readbitlen, 0*readbitlen)\n\t//fmt.Println(\"000000000000retdata is \", retdata)\n\tvar readiter int\n\tfor readiter = 0; readiter < len(fileposition); readiter++ {\n\t\t//fmt.Println(\"readiter is \", readiter)\n\t\t//fmt.Println(\"now fileposition is \", fileposition[readiter])\n\t\tretdata, _ := ReadBlock(filename, readbitlen, (fileposition[readiter])*readbitlen)\n\t\t//fmt.Println(\"retdata is \", retdata)\n\t\tfor _,nounceum := range retdata{\n\t\t\tfileretdata=append(fileretdata,nounceum)\n\t\t}\n\n\t}\n\tfmt.Println(\"fileretdata is \", fileretdata)\n\tfileretdata_hash := GetSHA256HashCode([]byte(fileretdata))\n\n\tvar filebyte_hash []byte\n\tfilebyte_hash, _ = hex.DecodeString(fileretdata_hash)\n\tfmt.Println(\"filebyte_hash is \", filebyte_hash)\n\treturn filebyte_hash\n\n}", "func (this *Codec) deserialize(data string) *TreeNode { \n list := strings.Split(data, \",\")\n var dfs func() *TreeNode\n dfs = func() *TreeNode {\n val := list[0]\n list = list[1:]\n if val == \"x\" {\n return nil\n }\n Val,_ := strconv.Atoi(val)\n root := &TreeNode{Val: Val}\n root.Left = dfs()\n root.Right = dfs()\n return root\n }\n return dfs()\n}", "func (this *Codec) deserialize(data string) *TreeNode {\n\tvar root *TreeNode\n\tif len(data) == 0 || data[0] == ' ' {\n\t\treturn root\n\t}\n\tnode := new(TreeNode)\n\troot = node\n\tnode.Val = int(data[0])\n\tqueue := new(Queue)\n\tqueue.EnQueue(node)\n\tfor index := 1; index < len(data); {\n\t\tif !queue.IsEmpty() {\n\t\t\tgenerics := queue.DeQueue()\n\t\t\tswitch t := generics.(type) {\n\t\t\tcase *TreeNode:\n\t\t\t\tif data[index] == ' ' {\n\t\t\t\t\tt.Left = nil\n\t\t\t\t} else {\n\t\t\t\t\tt.Left = new(TreeNode)\n\t\t\t\t\tt.Val = int(data[index])\n\t\t\t\t\tqueue.EnQueue(t.Left)\n\t\t\t\t}\n\t\t\t\tindex++\n\t\t\t\tif index >= len(data) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif data[index] == ' ' {\n\t\t\t\t\tt.Right = nil\n\t\t\t\t} else {\n\t\t\t\t\tt.Right = new(TreeNode)\n\t\t\t\t\tt.Val = int(data[index])\n\t\t\t\t\tqueue.EnQueue(t.Right)\n\t\t\t\t}\n\t\t\t\tindex++\n\t\t\t}\n\t\t}\n\t}\n\treturn root\n}", "func (this *Codec) deserialize(data string) *TreeNode {\n\tif len(data) == 0 {\n\t\treturn nil\n\t}\n\tq := strings.Split(data, \" \")\n\tif len(q) == 0 {\n\t\treturn nil\n\t}\n\n\t// 큐 맨 앞값 파악\n\tmin := -1 << 31\n\tmax := 1<<31 - 1\n\treturn _to_BinaryTreeNode(&q, min, max)\n}", "func (leaf *Node) Decode() ([]byte, error) {\n\tif len(leaf.ContentEncoding) == 0 {\n\t\tleaf.plainv = leaf.V\n\t\treturn leaf.plainv, nil\n\t}\n\n\tleaf.plainv = leaf.plainv[:0]\n\n\tif leaf.ContentEncoding == EncodingGzip {\n\t\tr, err := gzip.NewReader(bytes.NewReader(leaf.V))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tbuf := make([]byte, 1024)\n\t\tfor {\n\t\t\tn, err := r.Read(buf)\n\t\t\tif n > 0 {\n\t\t\t\tleaf.plainv = append(leaf.plainv, buf[:n]...)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tbuf = buf[0:]\n\t\t}\n\t}\n\n\treturn leaf.plainv, nil\n}", "func readString(dst, b []byte) ([]byte, []byte, error) {\n\tvar n uint64\n\tvar err error\n\tmustDecode := (b[0]&128 == 128) // huffman encoded\n\tb, n, err = readInt(7, b)\n\tif err == nil && uint64(len(b)) < n {\n\t\terr = fmt.Errorf(\"unexpected size: %d < %d\", len(b), n)\n\t}\n\tif err == nil {\n\t\tif mustDecode {\n\t\t\tdst = HuffmanDecode(dst, b[:n])\n\t\t} else {\n\t\t\tdst = append(dst, b[:n]...)\n\t\t}\n\t\tb = b[n:]\n\t}\n\treturn b, dst, err\n}", "func decodeValue(r BytesReader) (interface{}, error) {\n\tch, err := r.ReadByte()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar val interface{}\n\tswitch ch {\n\tcase '+':\n\t\t// Simple string\n\t\tval, err = decodeSimpleString(r)\n\tcase '-':\n\t\t// Error\n\t\tval, err = decodeError(r)\n\tcase ':':\n\t\t// Integer\n\t\tval, err = decodeInteger(r)\n\tcase '$':\n\t\t// Bulk string\n\t\tval, err = decodeBulkString(r)\n\tcase '*':\n\t\t// Array\n\t\tval, err = decodeArray(r)\n\tdefault:\n\t\terr = ErrInvalidPrefix\n\t}\n\n\treturn val, err\n}", "func (z *Tokenizer) nextByte() byte {\n\tif z.err == io.EOF {\n\t\treturn 0\n\t}\n\tby, err := z.r.ReadByte()\n\tif err == io.EOF {\n\t\tz.err = io.EOF\n\t\treturn 0\n\t} else if err != nil {\n\t\tpanic(err)\n\t}\n\treturn by\n}", "func uleb128dec(bout []byte) (value int, count int) {\n\t/* To decode:\n\tStart at bit-position 0\n\tRead one byte from the file\n\tStore whether the high bit is set, and mask it away\n\tOR in the rest of the byte into your final value, at the bit-position you're at\n\tIf the high bit was set, increase the bit-position by 7, and repeat the steps,\n\tskipping the first one (don't reset the bit-position). */\n\n\tif len(bout) < 10 {\n\t\tpanic(\"Need to give a buffer of at least 10\")\n\t}\n\tvar lower7bits, shift byte\n\n\tfor more, i := true, 0; more; i++ {\n\t\tlower7bits = bout[i]\n\t\tmore = (lower7bits & 128) != 0\n\t\tvalue |= int(lower7bits&0x7f) << shift\n\t\tshift += 7\n\t\tcount++\n\n\t}\n\treturn value, count\n\n}", "func (interrupt *FuseInterruptIn) ParseBinary(bcontent []byte) error {\n\n\tlength := len(bcontent)\n\n\tif length < 8 {\n\t\treturn ErrDataLen\n\t}\n\n\terr := common.ParseBinary(bcontent, interrupt)\n\n\treturn err\n}", "func (d *Decoder) Byte() byte {\n\tb, err := d.buf.ReadByte()\n\tif err != nil {\n\t\tpanic(\"unmarshalByte\")\n\t}\n\treturn b\n}", "func Parse(b []byte) (Packet, error) {\n var p Packet\n opcode := binary.BigEndian.Uint16(b[:TFTP_HEADER_SIZE])\n\n switch opcode {\n case RRQ_CODE:\n fallthrough\n case WRQ_CODE:\n p = &Request{Opcode: opcode}\n case DATA_CODE:\n p = &Data{}\n case ACK_CODE:\n p = &Ack{}\n case ERR_CODE:\n p = &Err{}\n default:\n return nil, fmt.Errorf(\"invalid opcode %v found\", opcode)\n }\n err := p.Build(b)\n return p, err\n}", "func binaryDecode(dst, src []byte) int {\n\tvar v, d byte\n\n\tfor i := 0; i < len(src); i++ {\n\t\tv, d = src[i], d<<1\n\t\tif isSpace(v) { // found a space, so between groups\n\t\t\tif i == 0 {\n\t\t\t\treturn 1\n\t\t\t}\n\t\t\treturn i\n\t\t}\n\t\tif v == '1' {\n\t\t\td ^= 1\n\t\t} else if v != '0' {\n\t\t\treturn i // will catch issues like \"000000: \"\n\t\t}\n\t}\n\n\tdst[0] = d\n\treturn -1\n}", "func (forget *FuseBatchForgetIn) ParseBinary(bcontent []byte) error {\n\n\tlength := len(bcontent)\n\n\tif length < 8 {\n\t\treturn ErrDataLen\n\t}\n\n\tcommon.ParseBinary(bcontent[4:8], &forget.Dummy)\n\n\tforget.NodeList = make([]FuseForgetOne, forget.Count)\n\tvar i uint32\n\tfor i = 0; i < forget.Count; i++ {\n\n\t\tvar temp = FuseForgetOne{}\n\t\tcommon.ParseBinary(bcontent[8*(i+1):16*(i+1)], &temp)\n\t\tforget.NodeList[i] = temp\n\t}\n\n\treturn nil\n}", "func (p *PacketParser) ParseByte(value byte) bool {\n\tswitch p.State {\n\tcase idle:\n\t\t// append the value into the PreambleBuffer\n\t\tp.PreambleBuffer = append(p.PreambleBuffer, value)\n\t\tif len(p.PreambleBuffer) == 2 {\n\t\t\tif p.PreambleBuffer[0] == 'G' && p.PreambleBuffer[1] == 'T' {\n\t\t\t\tp.State = preambleRecvd\n\t\t\t\tp.Offset = 2 // Preamble offset\n\t\t\t\tp.PreambleBuffer = make([]byte, 0)\n\t\t\t} else {\n\t\t\t\t// pop off the first element of preamble buffer, continue waiting.\n\t\t\t\tp.PreambleBuffer = p.PreambleBuffer[1:]\n\t\t\t}\n\t\t}\n\tcase preambleRecvd:\n\t\tp.PacketBuffer[p.Offset] = value\n\t\tp.Offset++\n\t\tif p.Offset >= len(p.PacketBuffer) {\n\t\t\tp.State = idle\n\t\t\treturn true\n\t\t}\n\tdefault:\n\t\tlog.Println(\"Unrecognized packet parser state: \", p.State)\n\t\tp.State = idle\n\t\tp.PreambleBuffer = make([]byte, 0)\n\n\t}\n\treturn false\n}", "func ByteParser(data []byte) osm.Parser {\r\n\treturn Parser(bytes.NewReader(data))\r\n}", "func (u *utf8) add(c byte) (r rune, size int) {\n\tswitch u.state {\n\tcase getByte0:\n\t\tif c&0x80 == 0 {\n\t\t\t// 1 byte\n\t\t\treturn rune(c), 1\n\t\t} else if c&0xe0 == 0xc0 {\n\t\t\t// 2 byte\n\t\t\tu.val = int32(c&0x1f) << 6\n\t\t\tu.count = 2\n\t\t\tu.state = get1More\n\t\t\treturn KeycodeNull, 0\n\t\t} else if c&0xf0 == 0xe0 {\n\t\t\t// 3 bytes\n\t\t\tu.val = int32(c&0x0f) << 6\n\t\t\tu.count = 3\n\t\t\tu.state = get2More\n\t\t\treturn KeycodeNull, 0\n\t\t} else if c&0xf8 == 0xf0 {\n\t\t\t// 4 bytes\n\t\t\tu.val = int32(c&0x07) << 6\n\t\t\tu.count = 4\n\t\t\tu.state = get3More\n\t\t\treturn KeycodeNull, 0\n\t\t}\n\tcase get3More:\n\t\tif c&0xc0 == 0x80 {\n\t\t\tu.state = get2More\n\t\t\tu.val |= int32(c & 0x3f)\n\t\t\tu.val <<= 6\n\t\t\treturn KeycodeNull, 0\n\t\t}\n\tcase get2More:\n\t\tif c&0xc0 == 0x80 {\n\t\t\tu.state = get1More\n\t\t\tu.val |= int32(c & 0x3f)\n\t\t\tu.val <<= 6\n\t\t\treturn KeycodeNull, 0\n\t\t}\n\tcase get1More:\n\t\tif c&0xc0 == 0x80 {\n\t\t\tu.state = getByte0\n\t\t\tu.val |= int32(c & 0x3f)\n\t\t\treturn rune(u.val), u.count\n\t\t}\n\t}\n\t// Error\n\tu.state = getByte0\n\treturn unicode.ReplacementChar, 1\n}", "func (serv *Server) handleBin(conn int, payload []byte) {}", "func (this *Codec) deserialize(data string) *TreeNode {\n\n\tif len(data) == 0 {\n\t\treturn nil\n\t}\n\n\tcode := data[1:]\n\tcode = code[:len(code)-1]\n\tnodeStr := strings.Split(code, \",\")\n\tif len(nodeStr) == 0 {\n\t\treturn nil\n\t}\n\n\tif nodeStr[0] == \"null\" {\n\t\treturn nil\n\t}\n\n\tnodes := []*TreeNode{}\n\tv, _ := strconv.Atoi(nodeStr[0])\n\troot := &TreeNode{\n\t\tVal: v,\n\t}\n\tnodes = append(nodes, root)\n\n\tnodeStr = nodeStr[1:]\n\tfor len(nodeStr) > 0 {\n\n\t\tnewNodes := []*TreeNode{}\n\t\tchildNum := 2 * len(nodes)\n\t\tif childNum > len(nodeStr) {\n\t\t\tchildNum = len(nodeStr)\n\t\t}\n\n\t\tfor j := 0; j < childNum; j++ {\n\t\t\tvar curNode *TreeNode\n\t\t\tif nodeStr[j] != \"null\" {\n\t\t\t\tv, _ := strconv.Atoi(nodeStr[j])\n\t\t\t\tcurNode = &TreeNode{\n\t\t\t\t\tVal: v,\n\t\t\t\t}\n\n\t\t\t\tnewNodes = append(newNodes, curNode)\n\t\t\t}\n\n\t\t\tparNode := nodes[j/2]\n\t\t\tif j&1 == 0 {\n\t\t\t\tparNode.Left = curNode\n\t\t\t} else {\n\t\t\t\tparNode.Right = curNode\n\t\t\t}\n\t\t}\n\n\t\tnodeStr = nodeStr[childNum:]\n\t\tnodes = newNodes\n\t}\n\n\treturn root\n}", "func setBitInByte(b byte, indexInByte uint32, bit byte) byte {\n\tvar mask byte = 0x80\n\tmask = mask >> uint(indexInByte)\n\n\tif bit == 0 {\n\t\tmask = ^mask\n\t\tb = b & mask\n\t} else if bit == 1 {\n\t\tb = b | mask\n\t}\n\treturn b\n}", "func readModUTF8(b []byte) rune {\n\tvar res rune\n\tc := b[0] >> 4\n\tif len(b) == 1 {\n\t\tres = rune(c >> 4)\n\t} else if len(b) == 2 {\n\t\tres = rune(((c & 0x1F) << 6) | (b[1] & 0x3F))\n\t} else if len(b) == 3 {\n\t\tfmt.Println(\"case3\")\n\t\t//var j uint16 = ((c & 0x0f) << 12)\n\t\tres = rune(((c & 0x0F) << 12) |\n\t\t\t((b[1] & 0x3F) << 6) |\n\t\t\t((b[2] & 0x3F) << 0))\n\t}\n\treturn res\n}", "func compress(chars []byte) int {\n \n}", "func (c *Processor) readByte(ea uint16) (b byte, opr string, err error) {\n\tmod := ea & 0x38 >> 3\n\treg := ea & 0x07\n\tswitch mod {\n\tdefault:\n\t\terr = errBadAddress\n\t\treturn\n\n\tcase 0x00: // data register\n\t\tb = byte(c.D[reg])\n\t\topr = fmt.Sprintf(\"D%d\", reg)\n\n\tcase 0x01: // address register\n\t\tb = byte(c.A[reg])\n\t\topr = fmt.Sprintf(\"A%d\", reg)\n\n\tcase 0x02: // memory address\n\t\tb, err = c.M.Byte(int(c.A[reg]))\n\t\topr = fmt.Sprintf(\"(A%d)\", reg)\n\n\tcase 0x03: // memory address with post-increment\n\t\tb, err = c.M.Byte(int(c.A[reg]))\n\t\tc.A[reg]++\n\t\tif reg == 7 {\n\t\t\tc.A[reg]++ // align stack pointer to 16-bit\n\t\t}\n\t\topr = fmt.Sprintf(\"(A%d)+\", reg)\n\n\tcase 0x04: // memory address with pre-decrement\n\t\tc.A[reg]--\n\t\tif reg == 7 {\n\t\t\tc.A[reg]-- // align stack pointer to 16-bit\n\t\t}\n\t\tb, err = c.M.Byte(int(c.A[reg]))\n\t\topr = fmt.Sprintf(\"-(A%d)\", reg)\n\n\tcase 0x05: // memory address with displacement\n\t\tvar d int16\n\t\td, err = c.M.Sword(int(c.PC))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tc.PC += 2\n\t\taddr := int(c.A[reg]) + int(d)\n\t\tb, err = c.M.Byte(addr)\n\t\topr = fmt.Sprintf(\"($%X,A%d)\", d, reg)\n\n\tcase 0x07: // other\n\t\tswitch reg {\n\t\tdefault:\n\t\t\terr = errBadAddress\n\t\t\treturn\n\n\t\tcase 0x00: // absolute word\n\t\t\tvar addr uint16\n\t\t\taddr, err = c.M.Word(int(c.PC))\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.PC += 2\n\t\t\tb, err = c.M.Byte(int(addr))\n\t\t\topr = fmt.Sprintf(\"$%X\", addr)\n\n\t\tcase 0x01: // absolute long\n\t\t\tvar addr uint32\n\t\t\taddr, err = c.M.Long(int(c.PC))\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.PC += 4\n\t\t\tb, err = c.M.Byte(int(addr))\n\t\t\topr = fmt.Sprintf(\"$%X\", addr)\n\n\t\tcase 0x04: // immediate byte\n\t\t\tvar n uint16\n\t\t\tn, err = c.M.Word(int(c.PC))\n\t\t\tb = byte(n)\n\t\t\tc.PC += 2\n\t\t\topr = fmt.Sprintf(\"#$%X\", byteToInt32(b))\n\t\t}\n\t}\n\treturn\n}", "func Digraph(b byte) (byte, byte) {\n\tr128 := uint(b) >> 1\n\tcfbit := b & 1\n\n\tif r128 < 120 {\n\t\td0 := vowels[r128/20]\n\t\td1 := consonants[r128%20]\n\t\tif cfbit == 0 {\n\t\t\treturn d0, d1\n\t\t} else {\n\t\t\treturn d1, d0\n\t\t}\n\t}\n\n\ttable := vowels\n\tif cfbit != 0 {\n\t\ttable = consonants\n\t}\n\n\tr8 := r128 - 120\n\treturn table[r8/3], table[r8%3+3]\n}", "func (d *decoder) createTree() *node {\n\tif val, _ := readBit(d.r); val {\n\t\treturn &node{readByte(d.r), -1, false, nil, nil}\n\t} else if d.numChars != d.numCharsDecoded {\n\t\tleft := d.createTree()\n\t\tright := d.createTree()\n\t\treturn &node{0, -1, true, left, right}\n\t}\n\n\treturn nil\n}", "func (this *Codec) deserialize(data string) *TreeNode {\n\tdata = data[1 : len(data)-1]\n\tthis.data = strings.Split(data, \",\")\n\tn := this.d()\n\treturn n\n}", "func Decode(w Word) (op, a, b Word) {\n\treturn w & 0x1f, (w >> 5) & 0x1f, (w >> 10) & 0x3f\n}", "func decode(src []byte) ([]byte, int, error) {\n\tb := string(src)\n\tanswer := big.NewInt(0)\n\tj := big.NewInt(1)\n\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\ttmp := strings.IndexAny(base58table, string(b[i]))\n\t\tif tmp == -1 {\n\t\t\tfmt.Println(b)\n\t\t\treturn []byte(\"\"), 0,\n\t\t\t\terrors.New(\"encoding/base58: invalid character found: ~\" +\n\t\t\t\t\tstring(b[i]) + \"~\")\n\t\t}\n\t\tidx := big.NewInt(int64(tmp))\n\t\ttmp1 := big.NewInt(0)\n\t\ttmp1.Mul(j, idx)\n\n\t\tanswer.Add(answer, tmp1)\n\t\tj.Mul(j, big.NewInt(radix))\n\t}\n\n\ttmpval := answer.Bytes()\n\n\tvar numZeros int\n\tfor numZeros = 0; numZeros < len(b); numZeros++ {\n\t\tif b[numZeros] != base58table[0] {\n\t\t\tbreak\n\t\t}\n\t}\n\tflen := numZeros + len(tmpval)\n\tval := make([]byte, flen, flen)\n\tcopy(val[numZeros:], tmpval)\n\treturn val, len(val), nil\n}", "func (this *Codec) deserialize(data string) *TreeNode {\n\tif len(data) == 0 {\n\t\treturn nil\n\t}\n\n\tres := strings.Split(data, \",\")\n\troot := &TreeNode{}\n\troot.Val, _ = strconv.Atoi(res[0])\n\tres = res[1:]\n\tqueue := make([]*TreeNode, 0)\n\tqueue = append(queue, root)\n\tfor len(queue) > 0 {\n\t\tif res[0] != \"#\" {\n\t\t\tleftVal, _ := strconv.Atoi(res[0])\n\t\t\tqueue[0].Left.Val = leftVal\n\t\t\tqueue = append(queue, queue[0].Left)\n\t\t}\n\t\tif res[1] != \"#\" {\n\t\t\trightVal, _ := strconv.Atoi(res[1])\n\t\t\tqueue[1].Right.Val = rightVal\n\t\t\tqueue = append(queue, queue[0].Right)\n\t\t}\n\t\tres = res[2:]\n\t\tqueue = queue[1:]\n\t}\n\treturn root\n}", "func decompress(str string, recursionLevel int) (length int) {\n\tvar index int\n\ttheMultiplierPattern := regexp.MustCompile(\"\\\\(([0-9x]*)\\\\)\")\n\n\tfor index < len(str) {\n\t\t// Search for start Character\n\t\tif str[index] == '(' {\n\t\t\t//\tlog.Printf(\"Recursion Level %v\\n\", recursionLevel)\n\n\t\t\t// extract Header info\n\t\t\ttheMultiplier := theMultiplierPattern.FindStringSubmatch(str[index:])[1]\n\t\t\tnums := strings.Split(theMultiplier, \"x\")\n\n\t\t\tcount, _ := strconv.Atoi(nums[0])\n\t\t\trepetitions, _ := strconv.Atoi(nums[1])\n\t\t\t//log.Printf(\"Multiply %v chars exactly %v times\\n\", count, repetitions)\n\n\t\t\t// find substring to process\n\t\t\trecursionStart := index + len(theMultiplier) + 2\n\t\t\trecursionString := str[recursionStart : recursionStart+count]\n\t\t\t//log.Printf(\"Now recurse substring %v\\n\", recursionString)\n\t\t\tlength += decompress(recursionString, recursionLevel+1) * repetitions\n\t\t\tindex += count + len(theMultiplier) + 2\n\t\t} else {\n\t\t\tlength++\n\t\t\tindex++\n\t\t}\n\t}\n\tcountd09Version2 = length\n\n\treturn length\n}", "func XorByte(buffer []byte, single byte) []byte {\n\toutput := make([]byte, len(buffer))\n\tfor idx := range buffer {\n\t\toutput[idx] = buffer[idx] ^ single\n\t}\n\treturn output\n}", "func DecodeBlob(b []byte, preAlloc ...int) (byte, [][]byte, error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil, fmt.Errorf(\"zero length blob not allowed\")\n\t}\n\tver := b[0]\n\tb = b[1:]\n\tpushes, err := ExtractPushes(b, preAlloc...)\n\treturn ver, pushes, err\n}", "func decodeBool8(b []byte) float64 {\n\tu := b[0]\n\tif u > 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (p *parser) VisitBytes(ctx *gen.BytesContext) any {\n\tb := []byte(p.unquote(ctx, ctx.GetTok().GetText()[1:], true))\n\treturn p.helper.newLiteralBytes(ctx, b)\n}", "func buildPrefixTree(byteFrequencies *dictionary.Dictionary) *huffmanTreeNode {\n\ttree := new(priorityqueue.PriorityQueue)\n\tkeys := byteFrequencies.Keys()\n\n\tfor i := 0; i < keys.Size(); i++ {\n\t\tbyt := keys.MustGet(i)\n\t\tfrequency, _ := byteFrequencies.Get(byt)\n\n\t\ttree.Enqueue(frequency.(int), &huffmanTreeNode{frequency: frequency.(int), value: byt.(byte)})\n\t}\n\n\tfor tree.Size() > 1 {\n\t\taPrio, a := tree.Dequeue()\n\t\tbPrio, b := tree.Dequeue()\n\n\t\tnewPrio := aPrio + bPrio\n\n\t\tnode := &huffmanTreeNode{frequency: newPrio, left: a.(*huffmanTreeNode), right: b.(*huffmanTreeNode)}\n\n\t\ttree.Enqueue(newPrio, node)\n\t}\n\n\t_, root := tree.Dequeue()\n\n\treturn root.(*huffmanTreeNode)\n}", "func (this *Codec) deserialize(data string) *TreeNode {\n\tstrs := strings.Split(data, this.sep)\n\tpos := 0\n\tvar buildTree func() *TreeNode\n\tbuildTree = func() *TreeNode {\n\t\tval := strs[pos]\n\t\tpos++\n\t\tif val == this.null {\n\t\t\treturn nil\n\t\t}\n\t\tnum, error := strconv.Atoi(val)\n\t\tif error != nil {\n\t\t\tpanic(error)\n\t\t}\n\t\tnode := &TreeNode{Val: num}\n\t\tnode.Left = buildTree()\n\t\tnode.Right = buildTree()\n\t\treturn node\n\t}\n\treturn buildTree()\n}", "func encodeToHuffmanCodes(uncompressed *vector.Vector, codes *dictionary.Dictionary) *vector.Vector {\n\tencodedHuffmanCodes := vector.New()\n\n\tfor i := 0; i < uncompressed.Size(); i++ {\n\t\tbyt := uncompressed.MustGet(i)\n\n\t\tiCode, _ := codes.Get(byt)\n\t\tcode := iCode.(*vector.Vector)\n\n\t\tfor j := 0; j < code.Size(); j++ {\n\t\t\tencodedHuffmanCodes.Append(code.MustGet(j))\n\t\t}\n\t}\n\n\treturn encodedHuffmanCodes\n}", "func (this *Codec) deserialize(data string) *TreeNode {\n\tstrList := strings.Split(data, \",\")\n\tindex := 0\n\tvar solve func() *TreeNode\n\tsolve = func() *TreeNode {\n\t\tif index >= len(strList) {\n\t\t\treturn nil\n\t\t}\n\t\tif strList[index] == \"$\" {\n\t\t\tindex++\n\t\t\treturn nil\n\t\t}\n\t\tval, _ := strconv.Atoi(strList[index])\n\t\troot := &TreeNode{\n\t\t\tVal: val,\n\t\t}\n\t\tindex++\n\t\troot.Left = solve()\n\t\troot.Right = solve()\n\t\treturn root\n\t}\n\treturn solve()\n}", "func (dd *dictDecoder) writeByte(c byte) {\n\tdd.hist[dd.wrPos] = c\n\tdd.wrPos++\n}", "func (b *BitStream) ReadByte() (byte, error) {\n\n\tif len(b.stream) == 0 {\n\t\treturn 0, io.EOF\n\t}\n\n\tif b.count == 0 {\n\t\tb.stream = b.stream[1:]\n\n\t\tif len(b.stream) == 0 {\n\t\t\treturn 0, io.EOF\n\t\t}\n\n\t\tb.count = 8\n\t}\n\n\tif b.count == 8 {\n\t\tb.count = 0\n\t\tb.bitsRead += 8\n\t\treturn b.stream[0], nil\n\t\t//b.stream = b.stream[1:]\n\t\t//return byt, nil\n\t}\n\n\tbyt := b.stream[0]\n\tb.stream = b.stream[1:]\n\n\tif len(b.stream) == 0 {\n\t\treturn 0, io.EOF\n\t}\n\n\tbyt |= b.stream[0] >> b.count\n\tb.stream[0] <<= (8 - b.count)\n\n\tb.bitsRead += 8\n\treturn byt, nil\n}", "func (head *Node) DecodeNext(r *bitio.Reader) (b byte, err error) {\n\tif head == nil {\n\t\treturn\n\t}\n\n\tvar u uint64\n\tnode := head\n\n\tfor node.left != nil && node.right != nil { // or node.value == 0\n\t\tu, err = r.ReadBits(1)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tif u == 0 {\n\t\t\tnode = node.left\n\t\t} else {\n\t\t\tnode = node.right\n\t\t}\n\t}\n\n\treturn node.value, err\n}", "func (this *Codec) deserialize(data string) *TreeNode {\n\tif data == \"\" {\n\t\treturn nil\n\t}\n\tans := strings.Split(data, \",\")\n\n\tvar i = new(int)\n\t*i = 0\n\treturn deserialize(&ans, i)\n}", "func byteToUint8(b byte) (n uint8) {\n\tn |= uint8(b)\n\treturn\n}", "func Byte(input []byte, startBitPos int) (result byte, resultPtr *byte, err error) {\n\tif Len(input)-startBitPos < 8 {\n\t\treturn 0, nil, errors.New(\"Input is less than 8 bits\")\n\t}\n\n\ttmpArr, _, err := SubBits(input, startBitPos, 8)\n\tresult = tmpArr[0]\n\n\treturn result, &result, err\n}", "func Interpret(data []byte, offset int) []byte {\n\tb:=make([]byte, len(data) * 2)\n\n\tfor i:=0; i<len(data); i++ {\n\t\tb[offset + i * 2] = hex_ascii[ (data[i] & 0XF0) >> 4]\n\t\tb[offset + i * 2 + 1] = hex_ascii[data[i] & 0x0F]\n\t}\n\treturn b\n}", "func (i *Insn) Byte() bool {\r\n\tswitch i.family {\r\n\tcase ItSingleOperand:\r\n\t\tswitch i.opcode {\r\n\t\tcase Op1Rrc:\t\r\n\t\t\tfallthrough\r\n\t\tcase Op1Rra:\r\n\t\t\tfallthrough\r\n\t\tcase Op1Push:\r\n\t\t\tif i.bw != 0 {\r\n\t\t\t\treturn true\r\n\t\t\t}\r\n\t\t}\r\n\tcase ItDoubleOperand:\r\n\t\tif i.bw != 0 {\r\n\t\t\treturn true\r\n\t\t}\r\n\t}\r\n\treturn false\r\n}", "func readULEB128(data []byte) (int, int) {\n\tlength := 1\n\tfor data[length-1]&0x80 > 0 {\n\t\tlength++\n\t}\n\n\tn := int(DecodeULeb128(data[:length+1]))\n\n\treturn n, length\n}", "func (flush *FuseFlushIn) ParseBinary(bcontent []byte) error {\n\n\tlength := len(bcontent)\n\n\tif length < 24 {\n\t\treturn ErrDataLen\n\t}\n\n\tcommon.ParseBinary(bcontent, flush)\n\n\treturn nil\n}", "func convertBitDepthsToSymbols(depth []byte, len uint, bits []uint16) {\n\tvar bl_count = [maxHuffmanBits]uint16{0}\n\tvar next_code [maxHuffmanBits]uint16\n\tvar i uint\n\t/* In Brotli, all bit depths are [1..15]\n\t 0 bit depth means that the symbol does not exist. */\n\n\tvar code int = 0\n\tfor i = 0; i < len; i++ {\n\t\tbl_count[depth[i]]++\n\t}\n\n\tbl_count[0] = 0\n\tnext_code[0] = 0\n\tfor i = 1; i < maxHuffmanBits; i++ {\n\t\tcode = (code + int(bl_count[i-1])) << 1\n\t\tnext_code[i] = uint16(code)\n\t}\n\n\tfor i = 0; i < len; i++ {\n\t\tif depth[i] != 0 {\n\t\t\tbits[i] = reverseBits(uint(depth[i]), next_code[depth[i]])\n\t\t\tnext_code[depth[i]]++\n\t\t}\n\t}\n}", "func main() {\r\n\ttest := \"abcdefghijklmnopqrstuvwxyz\"\r\n\r\n\tsymFreqs := make(map[rune]int)\r\n\t// read each symbol and record the frequencies\r\n\tfor _, c := range test {\r\n\t\tsymFreqs[c]++\r\n\t}\r\n\r\n\t// example tree\r\n\texampleTree := buildTree(symFreqs)\r\n\r\n\t// print out results\r\n\tfmt.Println(\"SYMBOL\\tWEIGHT\\tHUFFMAN CODE\")\r\n\tprintCodes(exampleTree, []byte{})\r\n}", "func NewEncodingTree(freq map[uint8]uint) *Node {\n\tvar head Node // Fictitious head\n\n\tfor i, v := range freq {\n\t\tnode := &Node{\n\t\t\tvalue: i,\n\t\t\tweight: v,\n\t\t}\n\t\thead.insert(node)\n\t}\n\n\tfor head.next != nil && head.next.next != nil {\n\t\tl := head.popFirst()\n\t\tr := head.popFirst()\n\n\t\tnode := join(l, r)\n\t\thead.insert(node)\n\t}\n\n\t// Fictitious head point to tree root\n\tif head.next != nil {\n\t\thead.next.prev = nil\n\t}\n\treturn head.next\n}", "func (forget *FuseForgetIn) ParseBinary(bcontent []byte) error {\n\terr := common.ParseBinary(bcontent, forget)\n\n\treturn err\n}", "func filterByte(mappedBit uint64) (retByte byte) {\n bitPosition := mappedBit % 8\n if bitPosition == 0 { // the leftmost bit is true\n retByte = 1 << 7\n } else {\n retByte = 1 << (uint(bitPosition) - 1)\n }\n return retByte\n}", "func CreateBinaryTree() {\n\tfmt.Fprintln(os.Stderr, \"CreateBinaryTree\")\n\tvar min1i, min2i, pos1, pos2 int\n\tvar point []int = make([]int, MAX_CODE_LENGTH)\n\tvar code []byte = make([]byte, MAX_CODE_LENGTH)\n\tvar count []int64 = make([]int64, vocab_size*2+1)\n\tvar binaryt []int = make([]int, vocab_size*2+1)\n\tvar parent_node []int = make([]int, vocab_size*2+1)\n\tfor a := 0; a < vocab_size; a++ {\n\t\tcount[a] = int64(vocab[a].cn)\n\t}\n\tfor a := vocab_size; a < vocab_size*2; a++ {\n\t\tcount[a] = 1e15\n\t}\n\tpos1 = vocab_size - 1\n\tpos2 = vocab_size\n\t// Following algorithm constructs the Huffman tree by adding one node at a time\n\tfor a := 0; a < vocab_size-1; a++ {\n\t\t// First, find two smallest nodes 'min1, min2'\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin1i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin1i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin1i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin2i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin2i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin2i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tcount[vocab_size+a] = count[min1i] + count[min2i]\n\t\tparent_node[min1i] = vocab_size + a\n\t\tparent_node[min2i] = vocab_size + a\n\t\tbinaryt[min2i] = 1\n\t}\n\t// Now assign binary code to each vocabulary character\n\tfor a := 0; a < vocab_size; a++ {\n\t\tb := a\n\t\ti := 0\n\t\tfor {\n\t\t\tcode[i] = byte(binaryt[b])\n\t\t\tpoint[i] = b\n\t\t\ti++\n\t\t\tb = parent_node[b]\n\t\t\tif b == vocab_size*2-2 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tvocab[a].codelen = byte(i)\n\t\tvocab[a].point[0] = vocab_size - 2\n\t\tfor b = 0; b < i; b++ {\n\t\t\tvocab[a].code[i-b-1] = code[b]\n\t\t\tvocab[a].point[i-b] = point[b] - vocab_size\n\t\t}\n\t}\n}", "func (this *Codec) deserialize(data string) *TreeNode {\n\tif len(data) <= 2 {\n\t\treturn nil\n\t}\n\tdata = data[1:len(data)-1]\n\tstrList := strings.Split(data, \",\")\n\tnodes := []*TreeNode{}\n\tfor _, str := range strList{\n\t\tval, _ := strconv.Atoi(str)\n\t\tnodes = append(nodes, &TreeNode{Val:val})\n\t}\n\ti, j := 0, 1\n\tfor j + 2 < len(nodes) {\n\t\tnodes[i].Left = nodes[j]\n\t\tnodes[i].Left = nodes[j+1]\n\t\ti, j = i + 1, j + 2\n\t}\n\treturn nodes[0]\n}", "func (bc *ByteCount) Scan(state fmt.ScanState, verb rune) error {\n\t// fmt.Printf(\"**scan[%c]**\\n\", verb)\n\tswitch verb {\n\tcase 'b', 'd', 'o', 'x', 'X':\n\t\ttFmt := \"%\"\n\t\tif wid, ok := state.Width(); ok {\n\t\t\ttFmt += strconv.FormatInt(int64(wid), 10)\n\t\t}\n\t\ttFmt += string(verb)\n\t\tptr := (*uint64)(bc)\n\t\tif _, err := fmt.Fscanf(state, tFmt, ptr); err != nil {\n\t\t\treturn fmt.Errorf(\"%%%c: no input: %w\", verb, err)\n\t\t}\n\n\tcase 's', 'S', 'u', 'U':\n\t\ttoken1Bytes, err := state.Token(true, nil)\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn fmt.Errorf(\"%%%c: %w\", verb, err)\n\t\tcase len(token1Bytes) < 1:\n\t\t\treturn fmt.Errorf(\"%%%c: no input\", verb)\n\t\t}\n\t\ttoken1Str := string(token1Bytes)\n\t\ttoken1 := byteCountScanTokenRe[0].FindStringSubmatch(token1Str)\n\t\tif token1 == nil {\n\t\t\treturn fmt.Errorf(\"%%%c: invalid expr: %s\", verb, token1Str)\n\t\t}\n\t\t// fmt.Printf(\"[SCAN] TOKEN1: %+v\\n\", token1)\n\n\t\tnumExpr := token1[1]\n\t\tisInt := 0 < len(token1[2]) && len(token1[3]) < 1\n\t\tunitExpr := token1[4]\n\n\t\tif len(numExpr) < 1 {\n\t\t\treturn fmt.Errorf(\"%%%c: invalid expr: %s\", verb, token1Str)\n\t\t}\n\n\t\tif unitExpr == \"\" { // no unit suffix within the first token\n\t\t\tswitch verb {\n\t\t\tcase 'u', 'U':\n\t\t\t\t// does not read the second token, assumed to be bytes\n\t\t\t\tunitExpr = \"b\"\n\t\t\tcase 's', 'S':\n\t\t\t\tsp, n, err := state.ReadRune()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"%%%c: no unit suffix: %w\", verb, err)\n\t\t\t\t}\n\t\t\t\tif n != 1 {\n\t\t\t\t\treturn fmt.Errorf(\"%%%c: no unit suffix\", verb)\n\t\t\t\t}\n\t\t\t\tif sp != ' ' {\n\t\t\t\t\treturn fmt.Errorf(\"%%%c: no space after digits: [%c]\", verb, sp)\n\t\t\t\t}\n\t\t\t\ttoken2Bytes, err := state.Token(false, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"%%%c: no unit suffix: %w\", verb, err)\n\t\t\t\t}\n\t\t\t\tif len(token2Bytes) < 1 {\n\t\t\t\t\treturn fmt.Errorf(\"%%%c: no unit suffix\", verb)\n\t\t\t\t}\n\t\t\t\ttoken2Str := string(token2Bytes)\n\t\t\t\ttoken2 := byteCountScanTokenRe[1].FindStringSubmatch(token2Str)\n\t\t\t\tif token2 == nil {\n\t\t\t\t\treturn fmt.Errorf(\"%%%c: invalid unit expr: %s\", verb, token2Str)\n\t\t\t\t}\n\t\t\t\t// fmt.Printf(\"[SCAN] TOKEN2: %+v\\n\", token2)\n\n\t\t\t\tunitExpr = token2[1]\n\t\t\t\tif unitExpr == \"\" {\n\t\t\t\t\treturn fmt.Errorf(\"%%%c: no unit suffix\", verb)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// fmt.Printf(\"[SCAN] LAST [%s] [%s]\\n\", numExpr, unitExpr)\n\n\t\tptr := (*uint64)(bc)\n\n\t\t// unit is byte\n\t\tif byteCountScanUnitRe[0].re.MatchString(unitExpr) {\n\t\t\tif !isInt {\n\t\t\t\treturn fmt.Errorf(\"%%%c: non-integer byte count: %s\", verb, numExpr)\n\t\t\t}\n\t\t\tnumVal, err := strconv.ParseUint(numExpr, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%%%c: invalid byte count: %s: %w\", verb, numExpr, err)\n\t\t\t}\n\t\t\t*ptr = numVal\n\t\t\treturn nil\n\t\t}\n\n\t\tif isInt { // integer\n\t\t\tnumVal, err := strconv.ParseUint(numExpr, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%%%c: invalid byte count: %s: %w\", verb, numExpr, err)\n\t\t\t}\n\t\t\tfor _, unit := range byteCountScanUnitRe {\n\t\t\t\tif unit.re.MatchString(unitExpr) {\n\t\t\t\t\tswitch verb {\n\t\t\t\t\tcase 's', 'u':\n\t\t\t\t\t\t*ptr = numVal * unit.bcs\n\t\t\t\t\tcase 'S', 'U':\n\t\t\t\t\t\t*ptr = numVal * unit.bcb\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"%%%c: unknown unit: %s\", verb, unitExpr)\n\t\t}\n\n\t\t// float\n\t\tnumVal, err := strconv.ParseFloat(numExpr, 64)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%%%c: invalid byte count: %s: %w\", verb, numExpr, err)\n\t\t}\n\t\tfor _, unit := range byteCountScanUnitRe {\n\t\t\tif unit.re.MatchString(unitExpr) {\n\t\t\t\tswitch verb {\n\t\t\t\tcase 's', 'u':\n\t\t\t\t\t*ptr = uint64(math.Round(numVal * float64(unit.bcs)))\n\t\t\t\tcase 'S', 'U':\n\t\t\t\t\t*ptr = uint64(math.Round(numVal * float64(unit.bcb)))\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"%%%c: unknown unit: %s\", verb, unitExpr)\n\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown verb for ByteCount: %%%c\", verb)\n\t}\n\treturn nil\n}", "func ByteDesc(list []byte, element byte) (int, bool) {\n\tleft := 0\n\tright := len(list) - 1\n\tfor left <= right {\n\t\tmiddle := (left + right) / 2\n\t\tvalue := list[middle]\n\t\tif element < value {\n\t\t\tleft = middle + 1\n\t\t} else if element > value {\n\t\t\tright = middle - 1\n\t\t} else {\n\t\t\treturn middle, true\n\t\t}\n\t}\n\treturn left, false\n}", "func FromByte(oneByte byte) []byte {\n\tbits := make([]byte, 8, 8)\n\tfor i := byte(7); i > 0; i-- {\n\t\tbit := (oneByte >> i) & 1\n\t\tbits[7-i] = bit\n\t}\n\tbits[7] = oneByte & 1\n\treturn bits\n}", "func byteEncoder(e *encodeState, v reflect.Value) error {\n\tval := v.Uint()\n\tsz := e.size\n\th := sz / 8.0\n\tfactor := .2\n\tblkH := h * (1 - factor)\n\tmargin := h * (factor / 2)\n\n\tfor y := sz - h; y > 0; y -= h {\n\t\tbit := val % 2\n\t\tif bit == 1 {\n\t\t\tr := e.Rect(margin, y-margin, sz-margin, blkH)\n\t\t\tr.Style.Set(\"stroke-width\", \"0\")\n\t\t\tr.Style.Set(\"fill\", \"black\")\n\t\t}\n\t\tval = val >> 1\n\t\tif val == 0 {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn nil\n}", "func Decode(src []byte) (dst [10]byte)", "func (e *encoder) emitHuff(h huffIndex, value int32) {\n\tx := theHuffmanLUT[h][value]\n\te.emit(x&(1<<24-1), x>>24)\n}", "func (c *Conf) InitFromBytes(content []byte) error {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tc.content = content\n\txmlDecoder := xml.NewDecoder(bytes.NewReader(c.content))\n\tvar nodeStack []*elem\n\tnodeStack = append(nodeStack, c.root)\n\tfor {\n\t\tcurrNode := nodeStack[len(nodeStack)-1]\n\t\ttoken, _ := xmlDecoder.Token()\n\t\tif token == nil {\n\t\t\tbreak\n\t\t}\n\t\tswitch t := token.(type) {\n\t\tcase xml.CharData:\n\t\t\tlineDecoder := bufio.NewScanner(bytes.NewReader(t))\n\t\t\tlineDecoder.Split(bufio.ScanLines)\n\t\t\tfor lineDecoder.Scan() {\n\t\t\t\tline := strings.Trim(lineDecoder.Text(), whiteSpaceChars)\n\t\t\t\tif (len(line) > 0 && line[0] == '#') || line == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// add Line data\n\t\t\t\tcurrNode.addLine(line)\n\t\t\t\tkv := strings.SplitN(line, \"=\", 2)\n\t\t\t\tk, v := strings.Trim(kv[0], whiteSpaceChars), \"\"\n\t\t\t\tif k == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif len(kv) == 2 {\n\t\t\t\t\tv = strings.Trim(kv[1], whiteSpaceChars)\n\t\t\t\t}\n\t\t\t\tleaf := newElem(Leaf, k)\n\t\t\t\tleaf.setValue(v)\n\t\t\t\tcurrNode.addChild(k, leaf)\n\t\t\t}\n\t\tcase xml.StartElement:\n\t\t\tnodeName := t.Name.Local\n\t\t\tnode, ok := currNode.findChild(nodeName)\n\t\t\tif !ok {\n\t\t\t\tnode = newElem(Node, nodeName)\n\t\t\t\tcurrNode.addChild(nodeName, node)\n\t\t\t}\n\t\t\tnodeStack = append(nodeStack, node)\n\t\tcase xml.EndElement:\n\t\t\tnodeName := t.Name.Local\n\t\t\tif currNode.name != nodeName {\n\t\t\t\treturn fmt.Errorf(\"xml end not match :%s\", nodeName)\n\t\t\t}\n\t\t\tnodeStack = nodeStack[:len(nodeStack)-1]\n\t\t}\n\t}\n\treturn nil\n}", "func decodeMUTF8(bytearr []byte) string {\n\tutflen := len(bytearr)\n\tchararr := make([]uint16, utflen)\n\n\tvar c, char2, char3 uint16\n\tcount := 0\n\tchararr_count := 0\n\n\tfor count < utflen {\n\t\tc = uint16(bytearr[count])\n\t\tif c > 127 {\n\t\t\tbreak\n\t\t}\n\t\tcount++\n\t\tchararr[chararr_count] = c\n\t\tchararr_count++\n\t}\n\n\tfor count < utflen {\n\t\tc = uint16(bytearr[count])\n\t\tswitch c >> 4 {\n\t\tcase 0, 1, 2, 3, 4, 5, 6, 7:\n\t\t\t/* 0xxxxxxx*/\n\t\t\tcount++\n\t\t\tchararr[chararr_count] = c\n\t\t\tchararr_count++\n\t\tcase 12, 13:\n\t\t\t/* 110x xxxx 10xx xxxx*/\n\t\t\tcount += 2\n\t\t\tif count > utflen {\n\t\t\t\tpanic(\"malformed input: partial character at end\")\n\t\t\t}\n\t\t\tchar2 = uint16(bytearr[count-1])\n\t\t\tif char2&0xC0 != 0x80 {\n\t\t\t\tpanic(fmt.Errorf(\"malformed input around byte %v\", count))\n\t\t\t}\n\t\t\tchararr[chararr_count] = c&0x1F<<6 | char2&0x3F\n\t\t\tchararr_count++\n\t\tcase 14:\n\t\t\t/* 1110 xxxx 10xx xxxx 10xx xxxx*/\n\t\t\tcount += 3\n\t\t\tif count > utflen {\n\t\t\t\tpanic(\"malformed input: partial character at end\")\n\t\t\t}\n\t\t\tchar2 = uint16(bytearr[count-2])\n\t\t\tchar3 = uint16(bytearr[count-1])\n\t\t\tif char2&0xC0 != 0x80 || char3&0xC0 != 0x80 {\n\t\t\t\tpanic(fmt.Errorf(\"malformed input around byte %v\", (count - 1)))\n\t\t\t}\n\t\t\tchararr[chararr_count] = c&0x0F<<12 | char2&0x3F<<6 | char3&0x3F<<0\n\t\t\tchararr_count++\n\t\tdefault:\n\t\t\t/* 10xx xxxx, 1111 xxxx */\n\t\t\tpanic(fmt.Errorf(\"malformed input around byte %v\", count))\n\t\t}\n\t}\n\t// The number of chars produced may be less than utflen\n\tchararr = chararr[0:chararr_count]\n\trunes := utf16.Decode(chararr)\n\treturn string(runes)\n}", "func (j *JPEG) readByteStuffedByte(r io.Reader) (byte, error) {\n\t// Take the fast path if d.bytes.buf contains at least two bytes.\n\t/*if d.bytes.i+2 <= d.bytes.j {\n\t x = d.bytes.buf[d.bytes.i]\n\t d.bytes.i++\n\t d.bytes.nUnreadable = 1\n\t if x != 0xff {\n\t return x, err\n\t }\n\t if d.bytes.buf[d.bytes.i] != 0x00 {\n\t return 0, errMissingFF00\n\t }\n\t d.bytes.i++\n\t d.bytes.nUnreadable = 2\n\t return 0xff, nil\n\t}*/\n\n\t//d.bytes.nUnreadable = 0\n\n\ttmp := make([]byte, 1, 1)\n\t_, err := r.Read(tmp)\n\tx := tmp[0]\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t//d.bytes.nUnreadable = 1\n\tif x != 0xff {\n\t\treturn x, nil\n\t}\n\n\t_, err = r.Read(tmp)\n\tx = tmp[0]\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t//d.bytes.nUnreadable = 2\n\tif x != 0x00 {\n\t\treturn 0, fmt.Errorf(\"missing 0xff00 sequence\")\n\t}\n\treturn 0xff, nil\n}", "func (p *Lexer) PeekByte() byte {\n\tc, err := p.Byte()\n\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\tp.UnreadByte()\n\treturn c\n}", "func (b Binary) Accept(interpreter *Interpreter) Object {\n\treturn interpreter.visitBinary(b)\n}", "func byte16FromByteSlice(src []byte) (blk bit128) {\n\t_ = src[15]\n\treturn bit128{binary.BigEndian.Uint64(src[0:8]), binary.BigEndian.Uint64(src[8:16])}\n}", "func parseByteMatch(k byteMatchType, s string) (*ByteMatch, error) {\n\tb := new(ByteMatch)\n\tb.Kind = k\n\n\tparts := strings.Split(s, \",\")\n\n\t// Num bytes is required for all byteMatchType keywords.\n\tif len(parts) < 1 {\n\t\treturn nil, fmt.Errorf(\"%s keyword has %d parts\", s, len(parts))\n\t}\n\n\tb.NumBytes = strings.TrimSpace(parts[0])\n\n\tif len(parts) < b.Kind.minLen() {\n\t\treturn nil, fmt.Errorf(\"invalid %s length: %d\", b.Kind, len(parts))\n\t}\n\n\tif k == bExtract || k == bJump {\n\t\t// Parse offset.\n\t\toffset, err := strconv.Atoi(strings.TrimSpace(parts[1]))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%s offset is not an int: %v; %s\", b.Kind, parts[1], err)\n\t\t}\n\t\tb.Offset = offset\n\t}\n\n\tif k == bExtract {\n\t\t// Parse variable name.\n\t\tname := parts[2]\n\t\tb.Variable = name\n\t}\n\n\tif k == bTest {\n\t\t// Parse operator.\n\t\tb.Operator = strings.TrimSpace(parts[1])\n\t\t// Parse value. Can use a variable.\n\t\tb.Value = strings.TrimSpace(parts[2])\n\t\t// Parse offset.\n\t\toffset, err := strconv.Atoi(strings.TrimSpace(parts[3]))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%s offset is not an int: %v; %s\", b.Kind, parts[1], err)\n\t\t}\n\t\tb.Offset = offset\n\t}\n\n\t// The rest of the options, for all types not b64decode\n\tfor i, l := b.Kind.minLen(), len(parts); i < l; i++ {\n\t\tparts[i] = strings.TrimSpace(parts[i])\n\t\tb.Options = append(b.Options, parts[i])\n\t}\n\n\treturn b, nil\n}", "func (ds *dagSession) decode(b blocks.Block) (format.Node, error) {\n\tnd, err := format.Decode(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trn, ok := nd.(Node)\n\tif !ok {\n\t\treturn nd, nil\n\t}\n\n\tds.pl.Lock()\n\tds.prnts[rn.Cid()] = rn.Copy().(Node) // it is better to make a copy here, since node can be altered by the caller.\n\tds.pl.Unlock()\n\n\treturn rn.Proto(), nil\n}", "func (j *HBPacket) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error {\n\tvar err error\n\tcurrentKey := ffjtHBPacketbase\n\t_ = currentKey\n\ttok := fflib.FFTok_init\n\twantedTok := fflib.FFTok_init\n\nmainparse:\n\tfor {\n\t\ttok = fs.Scan()\n\t\t//\tprintln(fmt.Sprintf(\"debug: tok: %v state: %v\", tok, state))\n\t\tif tok == fflib.FFTok_error {\n\t\t\tgoto tokerror\n\t\t}\n\n\t\tswitch state {\n\n\t\tcase fflib.FFParse_map_start:\n\t\t\tif tok != fflib.FFTok_left_bracket {\n\t\t\t\twantedTok = fflib.FFTok_left_bracket\n\t\t\t\tgoto wrongtokenerror\n\t\t\t}\n\t\t\tstate = fflib.FFParse_want_key\n\t\t\tcontinue\n\n\t\tcase fflib.FFParse_after_value:\n\t\t\tif tok == fflib.FFTok_comma {\n\t\t\t\tstate = fflib.FFParse_want_key\n\t\t\t} else if tok == fflib.FFTok_right_bracket {\n\t\t\t\tgoto done\n\t\t\t} else {\n\t\t\t\twantedTok = fflib.FFTok_comma\n\t\t\t\tgoto wrongtokenerror\n\t\t\t}\n\n\t\tcase fflib.FFParse_want_key:\n\t\t\t// json {} ended. goto exit. woo.\n\t\t\tif tok == fflib.FFTok_right_bracket {\n\t\t\t\tgoto done\n\t\t\t}\n\t\t\tif tok != fflib.FFTok_string {\n\t\t\t\twantedTok = fflib.FFTok_string\n\t\t\t\tgoto wrongtokenerror\n\t\t\t}\n\n\t\t\tkn := fs.Output.Bytes()\n\t\t\tif len(kn) <= 0 {\n\t\t\t\t// \"\" case. hrm.\n\t\t\t\tcurrentKey = ffjtHBPacketnosuchkey\n\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\tgoto mainparse\n\t\t\t} else {\n\t\t\t\tswitch kn[0] {\n\n\t\t\t\tcase 'P':\n\n\t\t\t\t\tif bytes.Equal(ffjKeyHBPacketPING, kn) {\n\t\t\t\t\t\tcurrentKey = ffjtHBPacketPING\n\t\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\t\tgoto mainparse\n\t\t\t\t\t}\n\n\t\t\t\tcase 'R':\n\n\t\t\t\t\tif bytes.Equal(ffjKeyHBPacketRPCMethod, kn) {\n\t\t\t\t\t\tcurrentKey = ffjtHBPacketRPCMethod\n\t\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\t\tgoto mainparse\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif fflib.SimpleLetterEqualFold(ffjKeyHBPacketPING, kn) {\n\t\t\t\t\tcurrentKey = ffjtHBPacketPING\n\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\n\t\t\t\tif fflib.SimpleLetterEqualFold(ffjKeyHBPacketRPCMethod, kn) {\n\t\t\t\t\tcurrentKey = ffjtHBPacketRPCMethod\n\t\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\n\t\t\t\tcurrentKey = ffjtHBPacketnosuchkey\n\t\t\t\tstate = fflib.FFParse_want_colon\n\t\t\t\tgoto mainparse\n\t\t\t}\n\n\t\tcase fflib.FFParse_want_colon:\n\t\t\tif tok != fflib.FFTok_colon {\n\t\t\t\twantedTok = fflib.FFTok_colon\n\t\t\t\tgoto wrongtokenerror\n\t\t\t}\n\t\t\tstate = fflib.FFParse_want_value\n\t\t\tcontinue\n\t\tcase fflib.FFParse_want_value:\n\n\t\t\tif tok == fflib.FFTok_left_brace || tok == fflib.FFTok_left_bracket || tok == fflib.FFTok_integer || tok == fflib.FFTok_double || tok == fflib.FFTok_string || tok == fflib.FFTok_bool || tok == fflib.FFTok_null {\n\t\t\t\tswitch currentKey {\n\n\t\t\t\tcase ffjtHBPacketRPCMethod:\n\t\t\t\t\tgoto handle_RPCMethod\n\n\t\t\t\tcase ffjtHBPacketPING:\n\t\t\t\t\tgoto handle_PING\n\n\t\t\t\tcase ffjtHBPacketnosuchkey:\n\t\t\t\t\terr = fs.SkipField(tok)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fs.WrapErr(err)\n\t\t\t\t\t}\n\t\t\t\t\tstate = fflib.FFParse_after_value\n\t\t\t\t\tgoto mainparse\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgoto wantedvalue\n\t\t\t}\n\t\t}\n\t}\n\nhandle_RPCMethod:\n\n\t/* handler: j.RPCMethod type=string kind=string quoted=false*/\n\n\t{\n\n\t\t{\n\t\t\tif tok != fflib.FFTok_string && tok != fflib.FFTok_null {\n\t\t\t\treturn fs.WrapErr(fmt.Errorf(\"cannot unmarshal %s into Go value for string\", tok))\n\t\t\t}\n\t\t}\n\n\t\tif tok == fflib.FFTok_null {\n\n\t\t} else {\n\n\t\t\toutBuf := fs.Output.Bytes()\n\n\t\t\tj.RPCMethod = string(string(outBuf))\n\n\t\t}\n\t}\n\n\tstate = fflib.FFParse_after_value\n\tgoto mainparse\n\nhandle_PING:\n\n\t/* handler: j.PING type=string kind=string quoted=false*/\n\n\t{\n\n\t\t{\n\t\t\tif tok != fflib.FFTok_string && tok != fflib.FFTok_null {\n\t\t\t\treturn fs.WrapErr(fmt.Errorf(\"cannot unmarshal %s into Go value for string\", tok))\n\t\t\t}\n\t\t}\n\n\t\tif tok == fflib.FFTok_null {\n\n\t\t} else {\n\n\t\t\toutBuf := fs.Output.Bytes()\n\n\t\t\tj.PING = string(string(outBuf))\n\n\t\t}\n\t}\n\n\tstate = fflib.FFParse_after_value\n\tgoto mainparse\n\nwantedvalue:\n\treturn fs.WrapErr(fmt.Errorf(\"wanted value token, but got token: %v\", tok))\nwrongtokenerror:\n\treturn fs.WrapErr(fmt.Errorf(\"ffjson: wanted token: %v, but got token: %v output=%s\", wantedTok, tok, fs.Output.String()))\ntokerror:\n\tif fs.BigError != nil {\n\t\treturn fs.WrapErr(fs.BigError)\n\t}\n\terr = fs.Error.ToError()\n\tif err != nil {\n\t\treturn fs.WrapErr(err)\n\t}\n\tpanic(\"ffjson-generated: unreachable, please report bug.\")\ndone:\n\n\treturn nil\n}", "func Encode(input string) (string, *tree.Node[string]) {\n\t// Create huffman tree and map\n\thTree := getHuffmanTree(input)\n\tprintTree(hTree)\n\thMap := getHuffmanEncodingMap(hTree)\n\tbuilder := strings.Builder{}\n\tfor i := 0; i < len(input); i++ {\n\t\tbuilder.WriteString(hMap[string(input[i])])\n\t}\n\treturn builder.String(), hTree\n}", "func (l *Lexer) blob() string {\n\treturn l.input[l.start:l.pos]\n}", "func AcknowledgeModeFromByte(a byte) AcknowledgeMode {\n\tswitch a {\n\tcase 0, 1, 2:\n\t\treturn AcknowledgeMode(a)\n\tcase 3, 4, 5:\n\t\treturn AckModeReserved\n\t}\n\n\tswitch {\n\tcase 6 <= a && a <= 9:\n\tcase 'A' <= a && a <= 'Z':\n\t\treturn AckModeManufacture\n\t}\n\n\treturn AckModeIllegalMode\n}", "func parseNextBinaryValue(ann []Symbol, r io.Reader) (Value, error) {\n\tswitch high, low, err := readNibblesHighAndLow(r); {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase low == 0xF:\n\t\treturn parseBinaryNull(high)\n\tcase high == binaryTypePadding:\n\t\treturn parseBinaryPadding(low, r)\n\tcase high == binaryTypeBool:\n\t\treturn parseBinaryBool(ann, low)\n\tcase high == binaryTypeInt || high == binaryTypeNegInt:\n\t\t// 2 = positive integer, 3 = negative integer.\n\t\treturn parseBinaryInt(ann, high == binaryTypeNegInt, low, r)\n\tcase high == binaryTypeFloat:\n\t\treturn parseBinaryFloat(ann, low, r)\n\tcase high == binaryTypeDecimal:\n\t\treturn parseBinaryDecimal(ann, low, r)\n\tcase high == binaryTypeTimestamp:\n\t\treturn parseBinaryTimestamp(ann, low, r)\n\tcase high == binaryTypeSymbol:\n\t\treturn parseBinarySymbol(ann, low, r)\n\tcase high == binaryTypeString:\n\t\treturn parseBinaryString(ann, low, r)\n\tcase high == binaryTypeBlob || high == binaryTypeClob:\n\t\treturn parseBinaryBytes(ann, high, low, r)\n\tcase high == binaryTypeList || high == binaryTypeSExp:\n\t\treturn parseBinaryList(ann, high, low, r)\n\tcase high == binaryTypeStruct:\n\t\treturn parseBinaryStruct(ann, low, r)\n\tcase high == binaryTypeAnnotation:\n\t\tif len(ann) != 0 {\n\t\t\treturn nil, errors.New(\"nesting annotations is not legal\")\n\t\t}\n\t\treturn parseBinaryAnnotation(low, r)\n\tdefault:\n\t\treturn nil, errors.Errorf(\"invalid header combination - high: %d low: %d\", high, low)\n\t}\n}", "func (b *BitStream) WriteByte(byt byte) error {\n\n\tif b.count == 0 {\n\t\tb.stream = append(b.stream, 0)\n\t\tb.count = 8\n\t}\n\n\ti := len(b.stream) - 1\n\n\t// fill up b.b with b.count bits from byt\n\tb.stream[i] |= byt >> (8 - b.count)\n\n\tb.stream = append(b.stream, 0)\n\ti++\n\tb.stream[i] = byt << b.count\n\tb.bitsWritten += 8\n\treturn nil\n}", "func (t *hashReader) ReadByte() (byte, error) {\n\tb := make([]byte, 1)\n\t_, err := t.Read(b)\n\treturn b[0], err\n}", "func DecodeTreeEntry(rd *bufio.Reader) (string, ipld.Node, error) {\n\tdata, err := rd.ReadString(' ')\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tdata = data[:len(data)-1]\n\n\tname, err := rd.ReadString(0)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tname = name[:len(name)-1]\n\n\tsha := make([]byte, 20)\n\t_, err = io.ReadFull(rd, sha)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\n\tte := _TreeEntry{\n\t\tmode: _String{data},\n\t\thash: _Link{cidlink.Link{Cid: shaToCid(sha)}},\n\t}\n\treturn name, &te, nil\n}", "func (this *Codec) deserialize(data string) *TreeNode {\n\ts := strings.Split(data, \",\")\n\tvar traverse func() *TreeNode\n\n\ttraverse = func() *TreeNode {\n\t\tval := s[0]\n\n\t\tif val == \"null\" {\n\t\t\ts = s[1:]\n\t\t\t// 这一步很关键\n\t\t\treturn nil\n\t\t}\n\n\t\tv, _ := strconv.Atoi(val)\n\t\ts = s[1:]\n\n\t\treturn &TreeNode{\n\t\t\tVal: v,\n\t\t\tLeft: traverse(),\n\t\t\tRight: traverse(),\n\t\t}\n\t}\n\n\treturn traverse()\n}", "func Decode(src []byte, mode Mode) (inst Inst, err error)", "func (release *FuseReleaseIn) ParseBinary(bcontent []byte) error {\n\n\tlength := len(bcontent)\n\n\tif length < 24 {\n\t\treturn ErrDataLen\n\t}\n\n\terr := common.ParseBinary(bcontent, release)\n\n\treturn err\n}", "func BPCharToByte(val *byte) sql.Scanner {\n\treturn charToByte{val: val}\n}", "func Decompress(b []byte) ([]byte, error) {\n\tdec := make([]byte, 0, len(b)) // estimate initial size\n\n\tfor len(b) > 0 {\n\t\tswitch b[0] {\n\t\tcase 254: // verbatim byte\n\t\t\tif len(b) < 2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tdec = append(dec, b[1])\n\t\t\tb = b[2:]\n\t\tcase 255: // verbatim string\n\t\t\tif len(b) < 2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tn := int(b[1])\n\t\t\tif len(b) < n+2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tdec = append(dec, b[2:n+2]...)\n\t\t\tb = b[n+2:]\n\t\tdefault: // look up encoded value\n\t\t\tdec = append(dec, codes[int(b[0])]...)\n\t\t\tb = b[1:]\n\t\t}\n\t}\n\n\treturn dec, nil\n}", "func (p *partition) readBit(prob uint8) bool {\n\tif p.nBits < 8 {\n\t\tif p.r >= len(p.buf) {\n\t\t\tp.unexpectedEOF = true\n\t\t\treturn false\n\t\t}\n\t\tp.bits |= uint32(p.buf[p.r]) << (8 - p.nBits)\n\t\tp.r++\n\t\tp.nBits += 8\n\t}\n\tsplit := (p.rangeM1*uint32(prob))>>8 + 1\n\tbit := p.bits >= split<<8\n\tif bit {\n\t\tp.rangeM1 -= split\n\t\tp.bits -= split << 8\n\t} else {\n\t\tp.rangeM1 = split - 1\n\t}\n\tif p.rangeM1 < 127 {\n\t\tshift := lutShift[p.rangeM1]\n\t\tp.rangeM1 = uint32(lutRangeM1[p.rangeM1])\n\t\tp.bits <<= shift\n\t\tp.nBits -= shift\n\t}\n\treturn bit\n}", "func (p *Packet) ReadByte() byte {\n\tif p.readIndex+1 > len(p.Payload) {\n\t\tlog.Warning.Println(\"Error parsing packet arguments: { opcode=\" + strconv.Itoa(int(p.Opcode)) + \"; offset=\" + strconv.Itoa(p.readIndex) + \" };\")\n\t\treturn byte(0)\n\t}\n\tdefer func() {\n\t\tp.readIndex++\n\t}()\n\treturn p.Payload[p.readIndex] & 0xFF\n}" ]
[ "0.5977924", "0.55451864", "0.5542703", "0.5483379", "0.52692354", "0.51715195", "0.5091173", "0.49814796", "0.4946427", "0.493463", "0.49185503", "0.4905912", "0.488269", "0.48778516", "0.4855809", "0.47979885", "0.47932762", "0.47918868", "0.4782398", "0.4781686", "0.47672722", "0.4746563", "0.47450212", "0.47417185", "0.47330287", "0.4705246", "0.467933", "0.46448395", "0.46337157", "0.4628936", "0.4617481", "0.46173504", "0.4610403", "0.4610345", "0.46073785", "0.46013796", "0.4600325", "0.45707157", "0.45706883", "0.4567618", "0.45672604", "0.45656928", "0.456404", "0.45482138", "0.45438206", "0.45340636", "0.45297524", "0.4527924", "0.45270413", "0.4515031", "0.45100266", "0.45028967", "0.4497646", "0.44908097", "0.44888112", "0.44884062", "0.4488037", "0.44870225", "0.44852966", "0.44809172", "0.44794187", "0.44731775", "0.44723964", "0.44669077", "0.4466686", "0.44654042", "0.44513175", "0.44502258", "0.4426088", "0.44236854", "0.44232607", "0.44181836", "0.44137186", "0.44110918", "0.44101933", "0.44081923", "0.44051424", "0.44049224", "0.43961573", "0.43959156", "0.43926737", "0.4386925", "0.43860552", "0.4383777", "0.4382383", "0.43822804", "0.4377656", "0.4376405", "0.43764028", "0.4367524", "0.43668476", "0.4365901", "0.4365742", "0.43646833", "0.43628034", "0.43425304", "0.4337366", "0.43359056", "0.43349385", "0.43334225" ]
0.602277
0
AsBitstreams encodes this Huffman tree in a bitstream
func (t Tree) AsBitstream() bitstream.BitStream { result := bitstream.BitStream{} t.asBitstream(&result, t.root) return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewEncodingTree(freq map[uint8]uint) *Node {\n\tvar head Node // Fictitious head\n\n\tfor i, v := range freq {\n\t\tnode := &Node{\n\t\t\tvalue: i,\n\t\t\tweight: v,\n\t\t}\n\t\thead.insert(node)\n\t}\n\n\tfor head.next != nil && head.next.next != nil {\n\t\tl := head.popFirst()\n\t\tr := head.popFirst()\n\n\t\tnode := join(l, r)\n\t\thead.insert(node)\n\t}\n\n\t// Fictitious head point to tree root\n\tif head.next != nil {\n\t\thead.next.prev = nil\n\t}\n\treturn head.next\n}", "func Encode(out *bytes.Buffer, byts []byte) (*EncodeInfo, error) {\n\tt := createTree(byts)\n\tconst codeSize = 32 // not optimize\n\tc := code{\n\t\tbits: make([]bool, 0, codeSize),\n\t}\n\te := newEncoder()\n\tif err := e.encode(t, c); err != nil {\n\t\treturn nil, err\n\t}\n\tsb, err := e.write(out, byts)\n\tei := &EncodeInfo{\n\t\tbytCodeMap: e.bytCodeMap,\n\t\tSize: sb,\n\t}\n\treturn ei, err\n}", "func Encode(input string) (string, *tree.Node[string]) {\n\t// Create huffman tree and map\n\thTree := getHuffmanTree(input)\n\tprintTree(hTree)\n\thMap := getHuffmanEncodingMap(hTree)\n\tbuilder := strings.Builder{}\n\tfor i := 0; i < len(input); i++ {\n\t\tbuilder.WriteString(hMap[string(input[i])])\n\t}\n\treturn builder.String(), hTree\n}", "func encodeTree(hmt *Tree, finalTree *string) {\n\tif hmt == nil {\n\t\treturn\n\t}\n\t\n\tif hmt.LeftNode == nil && hmt.RightNode == nil{\n\t\t*finalTree += \"1\" + string(hmt.Char)\n\t} else {\n\t\t*finalTree += \"0\"\n\t}\n\tencodeTree(hmt.LeftNode, finalTree)\n\tencodeTree(hmt.RightNode, finalTree) \n}", "func encodeToHuffmanCodes(uncompressed *vector.Vector, codes *dictionary.Dictionary) *vector.Vector {\n\tencodedHuffmanCodes := vector.New()\n\n\tfor i := 0; i < uncompressed.Size(); i++ {\n\t\tbyt := uncompressed.MustGet(i)\n\n\t\tiCode, _ := codes.Get(byt)\n\t\tcode := iCode.(*vector.Vector)\n\n\t\tfor j := 0; j < code.Size(); j++ {\n\t\t\tencodedHuffmanCodes.Append(code.MustGet(j))\n\t\t}\n\t}\n\n\treturn encodedHuffmanCodes\n}", "func compressPrefixTree(root *huffmanTreeNode, to *vector.Vector) {\n\tswitch isLeafNode(root) {\n\tcase true:\n\t\tto.Append(byte(1))\n\t\tto.Append(root.value)\n\tcase false:\n\t\tto.Append(byte(0))\n\t\tcompressPrefixTree(root.left, to)\n\t\tcompressPrefixTree(root.right, to)\n\t}\n}", "func (e EmptyNode) EncodeBinary(*io.BinWriter) {\n}", "func CreateBinaryTree() {\n\tfmt.Fprintln(os.Stderr, \"CreateBinaryTree\")\n\tvar min1i, min2i, pos1, pos2 int\n\tvar point []int = make([]int, MAX_CODE_LENGTH)\n\tvar code []byte = make([]byte, MAX_CODE_LENGTH)\n\tvar count []int64 = make([]int64, vocab_size*2+1)\n\tvar binaryt []int = make([]int, vocab_size*2+1)\n\tvar parent_node []int = make([]int, vocab_size*2+1)\n\tfor a := 0; a < vocab_size; a++ {\n\t\tcount[a] = int64(vocab[a].cn)\n\t}\n\tfor a := vocab_size; a < vocab_size*2; a++ {\n\t\tcount[a] = 1e15\n\t}\n\tpos1 = vocab_size - 1\n\tpos2 = vocab_size\n\t// Following algorithm constructs the Huffman tree by adding one node at a time\n\tfor a := 0; a < vocab_size-1; a++ {\n\t\t// First, find two smallest nodes 'min1, min2'\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin1i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin1i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin1i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tif pos1 >= 0 {\n\t\t\tif count[pos1] < count[pos2] {\n\t\t\t\tmin2i = pos1\n\t\t\t\tpos1--\n\t\t\t} else {\n\t\t\t\tmin2i = pos2\n\t\t\t\tpos2++\n\t\t\t}\n\t\t} else {\n\t\t\tmin2i = pos2\n\t\t\tpos2++\n\t\t}\n\t\tcount[vocab_size+a] = count[min1i] + count[min2i]\n\t\tparent_node[min1i] = vocab_size + a\n\t\tparent_node[min2i] = vocab_size + a\n\t\tbinaryt[min2i] = 1\n\t}\n\t// Now assign binary code to each vocabulary character\n\tfor a := 0; a < vocab_size; a++ {\n\t\tb := a\n\t\ti := 0\n\t\tfor {\n\t\t\tcode[i] = byte(binaryt[b])\n\t\t\tpoint[i] = b\n\t\t\ti++\n\t\t\tb = parent_node[b]\n\t\t\tif b == vocab_size*2-2 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tvocab[a].codelen = byte(i)\n\t\tvocab[a].point[0] = vocab_size - 2\n\t\tfor b = 0; b < i; b++ {\n\t\t\tvocab[a].code[i-b-1] = code[b]\n\t\t\tvocab[a].point[i-b] = point[b] - vocab_size\n\t\t}\n\t}\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tnodes := []*TreeNode{ root }\n\tstrList := []string{}\n\tfor i := 0; i < len(nodes); {\n\t\tcnt := len(nodes)\n\t\tfor ; i < cnt; i++ {\n\t\t\tnode := nodes[i]\n\t\t\tif node == nil {\n\t\t\t\tstrList = append(strList, \"null\")\n\t\t\t} else {\n\t\t\t\tstrList = append(strList, strconv.Itoa(node.Val))\n\t\t\t\tnodes = append(nodes, node.Left)\n\t\t\t\tnodes = append(nodes, node.Right)\n\t\t\t}\n\t\t}\n\t}\n\treturn \"[\" + strings.Join(strList, \"\") + \"]\"\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\n\tif root == nil {\n\t\treturn \"[null]\"\n\t}\n\n\tnodes := []*TreeNode{root}\n\tcode := \"[\" + strconv.Itoa(root.Val)\n\n\tfor len(nodes) > 0 {\n\t\tnewNodes := []*TreeNode{}\n\n\t\tfor i := range nodes {\n\n\t\t\tif nodes[i].Left != nil {\n\t\t\t\tnewNodes = append(newNodes, nodes[i].Left)\n\t\t\t\tcode = code + \",\" + strconv.Itoa(nodes[i].Left.Val)\n\t\t\t} else {\n\t\t\t\tcode = code + \",null\"\n\t\t\t}\n\n\t\t\tif nodes[i].Right != nil {\n\t\t\t\tnewNodes = append(newNodes, nodes[i].Right)\n\t\t\t\tcode = code + \",\" + strconv.Itoa(nodes[i].Right.Val)\n\t\t\t} else {\n\t\t\t\tcode = code + \",null\"\n\t\t\t}\n\n\t\t}\n\n\t\tnodes = newNodes\n\n\t}\n\tcode = code + \"]\"\n\treturn code\n}", "func NewHuffmanEncoder(inp io.ReadSeeker, wc io.Writer) *HuffmanEncoder {\n\the := new(HuffmanEncoder)\n\tfreq := make(map[byte]int)\n\n\tvar b [1]byte\n\t// using the reader, count the frequency of bytes\n\tfor {\n\t\t_, err := inp.Read(b[:])\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tpanic(err)\n\t\t}\n\n\t\t_, ok := freq[b[0]]\n\t\tif !ok {\n\t\t\tfreq[b[0]] = 0\n\t\t}\n\t\tfreq[b[0]]++\n\t}\n\t_, err := inp.Seek(0, io.SeekStart)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tpQ := make(PriorityQueue, len(freq))\n\ti := 0\n\tfor v, f := range freq {\n\t\tpQ[i] = NewHNode(v, f)\n\t\ti++\n\t}\n\n\theap.Init(&pQ)\n\n\tfor pQ.Len() > 1 {\n\t\tzero := pQ.Pop()\n\t\tl := zero.(Item)\n\t\tone := pQ.Pop()\n\t\tr := one.(Item)\n\t\tht := NewHTree(l, r)\n\t\theap.Push(&pQ, ht)\n\t}\n\n\thtree := pQ.Pop()\n\troot, ok := htree.(*HTree)\n\tif !ok {\n\t\tpanic(\"Huffman Tree\")\n\t}\n\the.root = root\n\the.dict = make(map[byte]Huffcode)\n\tfilldict(he.root, \"\", he.dict)\n\the.bw = bs.NewWriter(wc)\n\treturn he\n}", "func (this *Codec) serialize(root *TreeNode) string {\n if root == nil {\n return \"x\"\n }\n return strconv.Itoa(root.Val) + \",\" + this.serialize(root.Left)+ \",\" + this.serialize(root.Right)\n}", "func Encode(in, out *os.File) {\n\tcounts := count(in)\n\tp := makePQ(counts)\n\th := makeHuffman(p)\n\tm := make(map[byte]string)\n\tfillMap(h, m, \"\")\n\tfor k, v := range m {\n\t\tfmt.Printf(\"k: %c, v: %s\\n\", k, v)\n\t}\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tthis.s(root)\n\treturn \"[\" + strings.Join(this.data, \",\") + \"]\"\n}", "func buildCodes(root *huffmanTreeNode, code *vector.Vector, result *dictionary.Dictionary) {\n\tif root == nil {\n\t\treturn\n\t}\n\n\tif isLeafNode(root) {\n\t\tresult.Set(root.value, code)\n\t}\n\n\tbuildCodes(root.left, code.AppendToCopy(byte(0)), result)\n\tbuildCodes(root.right, code.AppendToCopy(byte(1)), result)\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tif root == nil {\n\t\treturn \"\"\n\t}\n\tvar res string\n\tp := root\n\tq := new(Queue)\n\tq.EnQueue(p)\n\n\tfor !q.IsEmpty() {\n\t\tnode := q.DeQueue()\n\t\tswitch t := node.(type) {\n\t\tcase nil:\n\t\t\tres += \" \"\n\t\tcase *TreeNode:\n\t\t\tres += strconv.Itoa(t.Val)\n\t\t\tq.EnQueue(t.Left)\n\t\t\tq.EnQueue(t.Right)\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t}\n\tfmt.Print(res)\n\treturn res\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tif root == nil {\n\t\treturn \"\"\n\t}\n\tans := make([]string, 0, 10)\n\tserialize(root, &ans)\n\n\treturn strings.Join(ans, \",\")\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tif root == nil {\n\t\treturn \"\"\n\t}\n\n\tres := make([]string, 0)\n\tqueue := make([]*TreeNode, 0)\n\tqueue = append(queue, root)\n\tfor len(queue) > 0 {\n\t\tl := len(queue)\n\t\tfor i := 0; i < l; i++ {\n\t\t\tnode := queue[0]\n\t\t\tqueue = queue[1:]\n\t\t\tif node != nil {\n\t\t\t\tres = append(res, strconv.Itoa(node.Val))\n\t\t\t\tqueue = append(queue, node.Left, node.Right)\n\t\t\t} else {\n\t\t\t\tres = append(res, \"#\")\n\t\t\t}\n\n\t\t}\n\t}\n\treturn strings.Join(res, \",\")\n}", "func (this *Codec) serialize(root *TreeNode) string {\n var s string \n res:=helpSerialize(root,s)\n fmt.Println(res)\n return res\n}", "func (enc *HuffmanEncoder) ShowHuffTree() {\n\ttraverse(enc.root, \"\")\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\ttmp := []string{}\n\ts(root, &tmp)\n\tthis.SerializeStr = strings.Join(tmp, \",\")\n\treturn this.SerializeStr\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\n\tif root == nil {\n\t\treturn \"\"\n\t}\n\n\tqueue := []*TreeNode{root}\n\tc := []string{strconv.Itoa(root.Val)}\n\n\tfor len(queue) > 0 {\n\t\tl := len(queue)\n\t\tfor i := 0; i < l; i++ {\n\t\t\tif queue[i].Left != nil {\n\t\t\t\tqueue = append(queue, queue[i].Left)\n\t\t\t}\n\t\t\tif queue[i].Right != nil {\n\t\t\t\tqueue = append(queue, queue[i].Right)\n\t\t\t}\n\t\t\tadd(&c, queue[i].Left)\n\t\t\tadd(&c, queue[i].Right)\n\t\t}\n\t\tqueue = queue[l:]\n\t}\n\n\tres := strings.Join(c, \",\")\n\treturn res\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tif root == nil {\n\t\treturn \"[]\"\n\t}\n\n\telements := []string{}\n\tqueue := []*TreeNode{}\n\tqueue = append(queue, root)\n\n\tfor len(queue) > 0 {\n\t\tnode := queue[0]\n\t\tqueue = queue[1:]\n\t\tif node.Val == NULL_VAL {\n\t\t\telements = append(elements, NULL_STR)\n\t\t\tcontinue\n\t\t}\n\n\t\tif node.Left != nil {\n\t\t\tqueue = append(queue, node.Left)\n\t\t} else {\n\t\t\tqueue = append(queue, &TreeNode{\n\t\t\t\tVal: NULL_VAL,\n\t\t\t})\n\t\t}\n\n\t\tif node.Right != nil {\n\t\t\tqueue = append(queue, node.Right)\n\t\t} else {\n\t\t\tqueue = append(queue, &TreeNode{\n\t\t\t\tVal: NULL_VAL,\n\t\t\t})\n\t\t}\n\n\t\telements = append(elements, strconv.Itoa(node.Val))\n\t}\n\n\treturn \"[\" + strings.Join(elements, \",\") + \"]\"\n}", "func (t *transposedChunkWriter) Encode() ([]byte, error) {\n\tif err := t.Close(); err != nil {\n\t\treturn nil, fmt.Errorf(\"closing transposedChunkWriter: %v\", err)\n\t}\n\n\t// TODO(schroederc): split buffers into multiple buckets\n\tdata, err := newCompressor(t.opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbufferIndices := make(map[nodeID]int)\n\tvar bufferIdx int\n\tvar bufferSizes []int\n\tfor _, bufs := range t.data {\n\t\tfor _, buf := range bufs {\n\t\t\tbufferIdx++\n\t\t\tbufferIndices[buf.id] = bufferIdx\n\t\t\tbufferSizes = append(bufferSizes, buf.writer.Len())\n\t\t\tif _, err := io.Copy(data, buf.writer); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"compressing buffer: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\tif t.nonProtoLengths.Len() > 0 {\n\t\tbufferSizes = append(bufferSizes, t.nonProtoLengths.Len())\n\t\tif _, err := io.Copy(data, &t.nonProtoLengths); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"compressing non_proto_length: %v\", err)\n\t\t}\n\t}\n\tif err := data.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tstates, ts, init, err := t.buildStateMachine(bufferIndices)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\tbuf.WriteByte(byte(t.opts.compressionType()))\n\n\t// Encode header\n\thdr, err := newCompressor(t.opts)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if err := t.encodeHeader(hdr, states, init, data.Len(), bufferSizes); err != nil {\n\t\treturn nil, err\n\t} else if err := hdr.Close(); err != nil {\n\t\treturn nil, err\n\t} else if _, err := writeUvarint(buf, uint64(hdr.Len())); err != nil {\n\t\treturn nil, fmt.Errorf(\"writing header_length: %v\", err)\n\t} else if _, err := hdr.WriteTo(buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Encode data bucket\n\tif _, err := data.WriteTo(buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Encode transitions\n\ttransitions, err := newCompressor(t.opts)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if _, err := transitions.Write(ts); err != nil {\n\t\treturn nil, err\n\t} else if err := transitions.Close(); err != nil {\n\t\treturn nil, err\n\t} else if _, err := transitions.WriteTo(buf); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tif root == nil {\n\t\treturn \"\"\n\t}\n\tvar result []string\n\tqueue := []*TreeNode{root}\n\tfor len(queue) > 0 {\n\t\troot = queue[0]\n\t\tqueue = queue[1:]\n\t\tif root == nil {\n\t\t\tresult = append(result, \"\")\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, strconv.Itoa(root.Val))\n\t\tqueue = append(queue, root.Left, root.Right)\n\t}\n\treturn strings.Join(result, \",\")\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tvar res string\n\n\tvar dfs func(node *TreeNode)\n\tdfs = func(node *TreeNode) {\n\t\tif node == nil {\n\t\t\tres += \"null,\"\n\t\t\treturn\n\t\t}\n\n\t\tres += fmt.Sprintf(\"%+v\", node.Val) + \",\"\n\t\tdfs(node.Left)\n\t\tdfs(node.Right)\n\t}\n\n\tdfs(root)\n\n\treturn res\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tif root == nil {\n\t\treturn \"\"\n\t}\n\tmaps := make(map[int64]int)\n\n\tmaps[1] = root.Val\n\tinnerSerialize(root.Right, &maps, 3)\n\tinnerSerialize(root.Left, &maps, 2)\n\tfmt.Println(maps)\n\n\treturn stringfy(&maps)\n}", "func convertBitDepthsToSymbols(depth []byte, len uint, bits []uint16) {\n\tvar bl_count = [maxHuffmanBits]uint16{0}\n\tvar next_code [maxHuffmanBits]uint16\n\tvar i uint\n\t/* In Brotli, all bit depths are [1..15]\n\t 0 bit depth means that the symbol does not exist. */\n\n\tvar code int = 0\n\tfor i = 0; i < len; i++ {\n\t\tbl_count[depth[i]]++\n\t}\n\n\tbl_count[0] = 0\n\tnext_code[0] = 0\n\tfor i = 1; i < maxHuffmanBits; i++ {\n\t\tcode = (code + int(bl_count[i-1])) << 1\n\t\tnext_code[i] = uint16(code)\n\t}\n\n\tfor i = 0; i < len; i++ {\n\t\tif depth[i] != 0 {\n\t\t\tbits[i] = reverseBits(uint(depth[i]), next_code[depth[i]])\n\t\t\tnext_code[depth[i]]++\n\t\t}\n\t}\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tstrs := make([]string, 0)\n\tvar preorder func(*TreeNode)\n\tpreorder = func(node *TreeNode) {\n\t\tif node == nil {\n\t\t\tstrs = append(strs, this.null)\n\t\t\treturn\n\t\t}\n\n\t\tstrs = append(strs, strconv.Itoa(node.Val))\n\t\tpreorder(node.Left)\n\t\tpreorder(node.Right)\n\t}\n\tpreorder(root)\n\treturn strings.Join(strs, this.sep)\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tnodeValues := []int{}\n\t// preoder 노드 탐색\n\t_to_string(root, &nodeValues)\n\n\t// 노드 값을 공백으로 구분한 스트링으로 리턴\n\tr := \"\"\n\tfor i := 0; i < len(nodeValues); i++ {\n\t\tr += fmt.Sprintf(\"%d \", nodeValues[i])\n\t}\n\treturn strings.TrimSpace(r)\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\ts := \"\"\n\n\tif root == nil {\n\t\treturn s\n\t}\n\n\ts = s + strconv.Itoa(root.Val)\n\n\tif root.Left != nil {\n\t\ts = s + \",\" + this.serialize(root.Left)\n\t} else {\n\t\ts = s + \",\" + \"null\"\n\t}\n\n\tif root.Right != nil {\n\t\ts = s + \",\" + this.serialize(root.Right)\n\t} else {\n\t\ts = s + \",\" + \"null\"\n\t}\n\n\treturn s\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tif root == nil {\n\t\treturn \"nil\"\n\t}\n\treturn strconv.Itoa(root.Val) + \",\" + this.serialize(root.Left) + \",\" + this.serialize(root.Right)\n}", "func (this *Codec) serialize1(root *TreeNode) string {\n\n\tif root == nil {\n\t\treturn \"\"\n\t}\n\n\tqueue := []*TreeNode{root}\n\tc := []string{strconv.Itoa(root.Val)}\n\n\tfor len(queue) > 0 {\n\t\tl := len(queue)\n\t\tfor i := 0; i < l; i++ {\n\t\t\tif queue[i].Left != nil {\n\t\t\t\tqueue = append(queue, queue[i].Left)\n\t\t\t}\n\t\t\tif queue[i].Right != nil {\n\t\t\t\tqueue = append(queue, queue[i].Right)\n\t\t\t}\n\t\t\tadd(&c, queue[i].Left)\n\t\t\tadd(&c, queue[i].Right)\n\t\t}\n\t\tqueue = queue[l:]\n\t}\n\n\tres := strings.Join(c, \",\")\n\treturn res\n}", "func encodeStream(r io.Reader, buffer bool) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tif !buffer {\n\t\tw := NewWriter(&buf)\n\t\t_, err := io.Copy(w, r)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = w.Close()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn buf.Bytes(), nil\n\t}\n\n\tw := NewWriter(&buf)\n\t_, err := io.Copy(w, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = w.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tstrList := make([]string, 0)\n\tvar solve func(root *TreeNode)\n\tsolve = func(root *TreeNode) {\n\t\tif root == nil {\n\t\t\tstrList = append(strList, \"$\")\n\t\t\treturn\n\t\t}\n\t\tstrList = append(strList, strconv.Itoa(root.Val))\n\t\tsolve(root.Left)\n\t\tsolve(root.Right)\n\t}\n\tsolve(root)\n\tfmt.Println(strings.Join(strList, \",\"))\n\treturn strings.Join(strList, \",\")\n}", "func main() {\n\troot := TreeNode{\n\t\tVal: 1,\n\t\tLeft: &TreeNode{\n\t\t\tVal: 2,\n\t\t\tLeft: nil,\n\t\t\tRight: nil,\n\t\t},\n\t\tRight: &TreeNode{\n\t\t\tVal: 3,\n\t\t\tLeft: &TreeNode{\n\t\t\t\tVal: 4,\n\t\t\t\tRight: nil,\n\t\t\t\tLeft: nil,\n\t\t\t},\n\t\t\tRight: &TreeNode{\n\t\t\t\tVal: 5,\n\t\t\t\tRight: nil,\n\t\t\t\tLeft: nil,\n\t\t\t},\n\t\t},\n\t}\n\tobj := Constructor()\n\tdata := obj.serialize(&root)\n\tfmt.Println(data)\n}", "func (head *Node) WriteHeader(w *bitio.Writer, freq map[uint8]uint) (err error) {\n\tvar nEncoded uint32\n\tfor _, v := range freq {\n\t\tnEncoded += uint32(v)\n\t}\n\n\t// Write total number of encoded symbols\n\tw.TryWriteBitsUnsafe(uint64(nEncoded), 32)\n\n\t// Write total number of symbols in graph\n\tw.TryWriteBitsUnsafe(uint64(len(freq)), 8)\n\n\t// Write encoding tree information\n\tif err = head.writeHeader(w); err != nil {\n\t\treturn err\n\t}\n\tw.TryWriteBitsUnsafe(0, 1)\n\treturn w.TryError\n}", "func (d *DFA) GobEncode() ([]byte, error) {\n\tbuffer := new(bytes.Buffer)\n\tencoder := gob.NewEncoder(buffer)\n\tif err := encoder.Encode(d.initial); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not GOB encode initial state\")\n\t}\n\tif err := encoder.Encode(d.table); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not GOB encode sparse table\")\n\t}\n\treturn buffer.Bytes(), nil\n}", "func compressHuffmanCodes(codes *vector.Vector) (compressedCodes *vector.Vector, lastByteInBits int) {\n\tcurrentCode := vector.New(0, 8)\n\tencodedCode := byte(0)\n\ttotalBits := 0\n\n\tcompressedCodes = vector.New()\n\n\tfor i := 0; i < codes.Size(); i++ {\n\t\tcurrentCode.Append(codes.MustGet(i))\n\n\t\tif currentCode.Size() != 8 && i != codes.Size()-1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor j := 0; j < currentCode.Size(); j++ {\n\t\t\ttotalBits++\n\n\t\t\tencodedCode <<= 1\n\n\t\t\tif currentCode.MustGet(j) != byte(0) {\n\t\t\t\tencodedCode |= 1\n\t\t\t}\n\t\t}\n\n\t\tcompressedCodes.Append(encodedCode)\n\t\tcurrentCode = vector.New(0, 8)\n\t\tencodedCode = byte(0)\n\t}\n\n\tlastByteInBits = totalBits % 8\n\n\tif lastByteInBits == 0 {\n\t\tlastByteInBits = 8\n\t}\n\n\treturn compressedCodes, lastByteInBits\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\treturn this.rserialize(root, \"\")\n}", "func buildPrefixTree(byteFrequencies *dictionary.Dictionary) *huffmanTreeNode {\n\ttree := new(priorityqueue.PriorityQueue)\n\tkeys := byteFrequencies.Keys()\n\n\tfor i := 0; i < keys.Size(); i++ {\n\t\tbyt := keys.MustGet(i)\n\t\tfrequency, _ := byteFrequencies.Get(byt)\n\n\t\ttree.Enqueue(frequency.(int), &huffmanTreeNode{frequency: frequency.(int), value: byt.(byte)})\n\t}\n\n\tfor tree.Size() > 1 {\n\t\taPrio, a := tree.Dequeue()\n\t\tbPrio, b := tree.Dequeue()\n\n\t\tnewPrio := aPrio + bPrio\n\n\t\tnode := &huffmanTreeNode{frequency: newPrio, left: a.(*huffmanTreeNode), right: b.(*huffmanTreeNode)}\n\n\t\ttree.Enqueue(newPrio, node)\n\t}\n\n\t_, root := tree.Dequeue()\n\n\treturn root.(*huffmanTreeNode)\n}", "func (c Int64Codec) EncodeChildren(n *Int64Node, vals []int64) []int64 {\n\tfor _, n2 := range n.Children {\n\t\tvals = append(vals, n2.Value)\n\t\tif len(n2.Children) > 0 {\n\t\t\tvals = append(vals, c.Desc)\n\t\t\tvals = c.EncodeChildren(n2, vals)\n\t\t\tvals = append(vals, c.Asc)\n\t\t}\n\t}\n\treturn vals\n}", "func Encode(node ipld.Node, w io.Writer) error {\n\t// 1KiB can be allocated on the stack, and covers most small nodes\n\t// without having to grow the buffer and cause allocations.\n\tenc := make([]byte, 0, 1024)\n\n\tenc, err := AppendEncode(enc, node)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = w.Write(enc)\n\treturn err\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\treturn dfsSerial(root, \"\")\n}", "func (c *Codec) serialize(root *TreeNode) string {\n\tvar q []*TreeNode\n\tq = append(q, root)\n\tvar out []string\n\tfor len(q) != 0 {\n\t\tfor k := len(q); k > 0; k-- {\n\t\t\tcurr := q[0]\n\t\t\tif curr != nil {\n\t\t\t\tout = append(out, strconv.Itoa(curr.Val))\n\t\t\t\tq = append(q, curr.Left, curr.Right)\n\t\t\t} else {\n\t\t\t\tout = append(out, \"null\")\n\t\t\t}\n\t\t\tq = q[1:]\n\t\t}\n\t}\n\treturn \"[\" + strings.TrimRight(strings.Join(out, \",\"), \",null\") + \"]\"\n}", "func encodeNodeWithType(n Node, w *io.BinWriter) {\n\tw.WriteB(byte(n.Type()))\n\tn.EncodeBinary(w)\n}", "func (b *BitOp) WithChildren(children ...sql.Expression) (sql.Expression, error) {\n\tif len(children) != 2 {\n\t\treturn nil, sql.ErrInvalidChildrenNumber.New(b, len(children), 2)\n\t}\n\treturn NewBitOp(children[0], children[1], b.Op), nil\n}", "func (t *BPTree) ToBinary(n *Node) (result []byte, err error) {\n\tvar i int\n\tvar keys [order - 1]int64\n\n\tfor i = 0; i < n.KeysNum; i++ {\n\t\tif t.enabledKeyPosMap {\n\t\t\tif len(t.keyPosMap) == 0 {\n\t\t\t\treturn nil, errors.New(\"not set keyPosMap\")\n\t\t\t}\n\t\t\tkeys[i] = t.keyPosMap[string(n.Keys[i])]\n\t\t} else {\n\t\t\tkey, _ := strconv2.StrToInt64(string(n.Keys[i]))\n\n\t\t\tkeys[i] = key\n\t\t}\n\t}\n\n\tvar pointers [order]int64\n\n\tif !n.isLeaf {\n\t\tfor i = 0; i < n.KeysNum+1; i++ {\n\t\t\tpointers[i] = n.pointers[i].(*Node).Address\n\t\t}\n\t} else {\n\t\tfor i = 0; i < n.KeysNum; i++ {\n\t\t\tif n.pointers[i].(*Record).H != nil {\n\t\t\t\tdataPos := n.pointers[i].(*Record).H.dataPos\n\t\t\t\tpointers[i] = int64(dataPos)\n\t\t\t} else {\n\t\t\t\tpointers[i] = 0\n\t\t\t}\n\t\t}\n\t}\n\n\tvar nextAddress int64\n\tnextAddress = DefaultInvalidAddress\n\n\tif n.Next != nil {\n\t\tnextAddress = n.Next.Address\n\t}\n\n\tvar isLeaf uint16\n\tisLeaf = 0\n\n\tif n.isLeaf {\n\t\tisLeaf = 1\n\t}\n\n\tbinNode := BinaryNode{\n\t\tKeys: keys,\n\t\tPointers: pointers,\n\t\tIsLeaf: isLeaf,\n\t\tAddress: n.Address,\n\t\tNextAddress: nextAddress,\n\t\tKeysNum: uint16(n.KeysNum),\n\t}\n\n\tbuf := new(bytes.Buffer)\n\n\terr = binary.Write(buf, binary.LittleEndian, binNode)\n\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (f *Fragment) Encode(w io.Writer) error {\n\ttraf := f.Moof.Traf\n\terr := traf.OptimizeTfhdTrun()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, b := range f.Children {\n\t\terr := b.Encode(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (pe *Encoder) Init(codes PrefixCodes) {\n\t// Handle special case trees.\n\tif len(codes) <= 1 {\n\t\tswitch {\n\t\tcase len(codes) == 0: // Empty tree (should error if used later)\n\t\t\t*pe = Encoder{chunks: pe.chunks[:0], NumSyms: 0}\n\t\tcase len(codes) == 1 && codes[0].Len == 0: // Single code tree (bit-length of zero)\n\t\t\tpe.chunks = append(pe.chunks[:0], codes[0].Val<<countBits|0)\n\t\t\t*pe = Encoder{chunks: pe.chunks[:1], NumSyms: 1}\n\t\tdefault:\n\t\t\tpanic(\"invalid codes\")\n\t\t}\n\t\treturn\n\t}\n\tif internal.Debug && !sort.IsSorted(prefixCodesBySymbol(codes)) {\n\t\tpanic(\"input codes is not sorted\")\n\t}\n\tif internal.Debug && !(codes.checkLengths() && codes.checkPrefixes()) {\n\t\tpanic(\"detected incomplete or overlapping codes\")\n\t}\n\n\t// Enough chunks to contain all the symbols.\n\tnumChunks := 1\n\tfor n := len(codes) - 1; n > 0; n >>= 1 {\n\t\tnumChunks <<= 1\n\t}\n\tpe.NumSyms = uint32(len(codes))\n\nretry:\n\t// Allocate and reset chunks.\n\tpe.chunks = allocUint32s(pe.chunks, numChunks)\n\tpe.chunkMask = uint32(numChunks - 1)\n\tfor i := range pe.chunks {\n\t\tpe.chunks[i] = 0 // Logic below relies on zero value as uninitialized\n\t}\n\n\t// Insert each symbol, checking that there are no conflicts.\n\tfor _, c := range codes {\n\t\tif pe.chunks[c.Sym&pe.chunkMask] > 0 {\n\t\t\t// Collision found our \"hash\" table, so grow and try again.\n\t\t\tnumChunks <<= 1\n\t\t\tgoto retry\n\t\t}\n\t\tpe.chunks[c.Sym&pe.chunkMask] = c.Val<<countBits | c.Len\n\t}\n}", "func makeHuffman(p priq.PriQ) *node {\n\trr, ok := p.Remove()\n\tif !ok {\n\t\tpanic(\"not enough elements in the priority queue to make a huffman tree\")\n\t}\t\n\tr := rr.(*node)\n\tll, ok := p.Remove()\n\tif !ok {\n\t\tpanic(\"not enough elements in the priority queue to make a huffman tree\")\n\t}\n\tl := ll.(*node)\t\n\tfor !p.Empty() {\n\t\tparent := new(node)\n\t\tparent.count = l.count + r.count\n\t\tparent.left = l\n\t\tparent.right = r\n\t\tp.Add(parent)\n\n\t\trr, ok = p.Remove()\n\t\tr = rr.(*node)\n\t\tll, ok = p.Remove()\n\t\tl = ll.(*node)\n\t}\n\troot := new(node)\n\troot.count = l.count + r.count\n\troot.left = l\n\troot.right = r\n\treturn root\n}", "func (node *Node) Pack() []byte {\n\tbfr := new(bytes.Buffer)\n\t// Write CATID\n\tbinary.Write(bfr, BIGEND, LBTYPE_CATID)\n\tbinary.Write(bfr, BIGEND, node.Id())\n\t// Write Catalog string key\n\tbinary.Write(bfr, BIGEND, LBTYPE_CATKEY)\n\tksz := AsLBUINT(len(node.Name()))\n\tbinary.Write(bfr, BIGEND, ksz)\n\tbfr.Write([]byte(node.Name()))\n\t// Write field map\n\tif node.HasFields() > 0 {\n\t\tbinary.Write(bfr, BIGEND, LBTYPE_MAP)\n\t\tbyts := node.FieldMap.ToBytes(node.debug)\n\t\tbinary.Write(bfr, BIGEND, AsLBUINT(len(byts)))\n\t\tbfr.Write(byts)\n\t} else {\n\t\tbinary.Write(bfr, BIGEND, LBTYPE_NIL)\n\t}\n\t// Write parents CATID set\n\tif node.HasParents() > 0 {\n\t\tbinary.Write(bfr, BIGEND, LBTYPE_CATID_SET)\n\t\tbyts := node.parents.ToBytes(node.debug)\n\t\tbinary.Write(bfr, BIGEND, AsLBUINT(len(byts)))\n\t\tbfr.Write(byts)\n\t} else {\n\t\tbinary.Write(bfr, BIGEND, LBTYPE_NIL)\n\t}\n\treturn bfr.Bytes()\n}", "func encode(n ipld.Node) (ipld.Node, ipld.Link) {\n\tlb := cidlink.LinkBuilder{cid.Prefix{\n\t\tVersion: 1,\n\t\tCodec: 0x0129,\n\t\tMhType: 0x17,\n\t\tMhLength: 4,\n\t}}\n\tlnk, err := lb.Build(context.Background(), ipld.LinkContext{}, n,\n\t\tfunc(ipld.LinkContext) (io.Writer, ipld.StoreCommitter, error) {\n\t\t\tbuf := bytes.Buffer{}\n\t\t\treturn &buf, func(lnk ipld.Link) error {\n\t\t\t\tstorage[lnk] = buf.Bytes()\n\t\t\t\treturn nil\n\t\t\t}, nil\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn n, lnk\n}", "func (bs *BitStream) Bits() []byte {\n\treturn bs.bitBuffer.Bytes()\n}", "func Encode(st interface{}, options ...EncDecOption) ([]byte, error) {\n\tbuf, err := EncodeToBits(st, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (a *AudioSampleEntryBox) Encode(w io.Writer) error {\n\terr := EncodeHeader(a, w)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuf := makebuf(a)\n\tsw := NewSliceWriter(buf)\n\tsw.WriteZeroBytes(6)\n\tsw.WriteUint16(a.DataReferenceIndex)\n\tsw.WriteZeroBytes(8) // pre_defined and reserved\n\tsw.WriteUint16(a.ChannelCount)\n\tsw.WriteUint16(a.SampleSize)\n\tsw.WriteZeroBytes(4) // Pre-defined and reserved\n\tsw.WriteUint32(makeFixed32Uint(a.SampleRate)) // nrAudioSampleBytesBeforeChildren bytes this far\n\n\t_, err = w.Write(buf[:sw.pos]) // Only write written bytes\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Next output child boxes in order\n\tfor _, child := range a.Children {\n\t\terr = child.Encode(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}", "func BuildJpegHuffmanTable(count_in, symbols []int, lut []HuffmanTableEntry) int {\n\tvar (\n\t\tcode HuffmanTableEntry // current table entry\n\t\ttable []HuffmanTableEntry // next available space in table\n\t\tlength int // current code length\n\t\tidx int // symbol index\n\t\tkey int // prefix code\n\t\treps int // number of replicate key values in current table\n\t\tlow int // low bits for current root entry\n\t\ttable_bits int // key length of current table\n\t\ttable_size int // size of current table\n\t\ttotal_size int // sum of root table size and 2nd level table sizes\n\t)\n\n\t// Make a local copy of the input bit length histogram.\n\tvar count [kJpegHuffmanMaxBitLength + 1]int\n\ttotal_count := 0\n\tfor length = 1; length <= kJpegHuffmanMaxBitLength; length++ {\n\t\tcount[length] = count_in[length]\n\t\ttotal_count += count[length]\n\t}\n\n\ttable = lut\n\t// table_delta used in go version, to work around pointer arithmetic\n\ttable_delta := 0\n\ttable_bits = kJpegHuffmanRootTableBits\n\ttable_size = 1 << uint(table_bits)\n\ttotal_size = table_size\n\n\t// Special case code with only one value.\n\tif total_count == 1 {\n\t\tcode.bits = 0\n\t\tcode.value = uint16(symbols[0])\n\t\tfor key = 0; key < total_size; key++ {\n\t\t\ttable[key] = code\n\t\t}\n\t\treturn total_size\n\t}\n\n\t// Fill in root table.\n\tkey = 0\n\tidx = 0\n\tfor length = 1; length <= kJpegHuffmanRootTableBits; length++ {\n\t\tfor ; count[length] > 0; count[length]-- {\n\t\t\tcode.bits = uint8(length)\n\t\t\tcode.value = uint16(symbols[idx])\n\t\t\tidx++\n\t\t\treps = 1 << uint(kJpegHuffmanRootTableBits-length)\n\t\t\tfor ; reps > 0; reps-- {\n\t\t\t\ttable[key] = code\n\t\t\t\tkey++\n\t\t\t}\n\t\t}\n\t}\n\n\t// Fill in 2nd level tables and add pointers to root table.\n\ttable = table[table_size:]\n\ttable_delta += table_size\n\ttable_size = 0\n\tlow = 0\n\tfor length = kJpegHuffmanRootTableBits + 1; length <= kJpegHuffmanMaxBitLength; length++ {\n\t\tfor ; count[length] > 0; count[length]-- {\n\t\t\t// Start a new sub-table if the previous one is full.\n\t\t\tif low >= table_size {\n\t\t\t\ttable = table[table_size:]\n\t\t\t\ttable_delta += table_size\n\t\t\t\ttable_bits = NextTableBitSize(count[:], length)\n\t\t\t\ttable_size = 1 << uint(table_bits)\n\t\t\t\ttotal_size += table_size\n\t\t\t\tlow = 0\n\t\t\t\tlut[key].bits = uint8(table_bits + kJpegHuffmanRootTableBits)\n\t\t\t\tlut[key].value = uint16(table_delta - key)\n\t\t\t\tkey++\n\t\t\t}\n\t\t\tcode.bits = uint8(length - kJpegHuffmanRootTableBits)\n\t\t\tcode.value = uint16(symbols[idx])\n\t\t\tidx++\n\t\t\treps = 1 << uint(table_bits-int(code.bits))\n\t\t\tfor ; reps > 0; reps-- {\n\t\t\t\ttable[low] = code\n\t\t\t\tlow++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn total_size\n}", "func (n *Node) ToBinary() (result []byte, err error) {\n\tbinNode := binaryNode{\n\t\tPointers: n.Pointers,\n\t\tData: n.Data,\n\t}\n\tbuf := new(bytes.Buffer)\n\n\terr = binary.Write(buf, binary.LittleEndian, binNode)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func encode(size int, input []byte, position int, numberOfByte int, controlBitsQuantity int) []byte {\n\tencoded := make([]byte, int(size/8))\n\t//Data bits accommodate process\n\tfor i := controlBitsQuantity - 1; i > 0; i-- {\n\t\tsl := expInt(i) - 1\n\t\til := expInt(i-1) - 1\n\t\tfor j := sl - 1; j > il; j-- {\n\t\t\tdataBit := takeBit(input[numberOfByte], position, 7-int(j%8))\n\t\t\tx := int(j / 8)\n\t\t\tencoded[x] = encoded[x] | dataBit\n\t\t\tposition++\n\t\t\tif position > 7 {\n\t\t\t\tnumberOfByte--\n\t\t\t\tposition = 0\n\t\t\t}\n\t\t}\n\t}\n\t//Control bits calculus process\n\tfor i := 0; i < controlBitsQuantity-1; i++ {\n\t\tparity := byte(0)\n\t\tfor j := expInt(i) - 1; j < size; j += expInt(i + 1) {\n\t\t\tfor k := 0; k < expInt(i); k++ {\n\t\t\t\tparity ^= takeBit(encoded[int((j+k)/8)], 7-((j+k)%8), 0)\n\t\t\t}\n\t\t}\n\t\tx := int(int(expInt(i)-1) / 8)\n\t\tencoded[x] = encoded[x] | takeBit(parity, 0, 7-(expInt(i)-1)%8)\n\t}\n\treturn encoded\n}", "func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error {\n\tif len(b.sequences) == 0 {\n\t\treturn b.encodeLits(b.literals, rawAllLits)\n\t}\n\t// We want some difference to at least account for the headers.\n\tsaved := b.size - len(b.literals) - (b.size >> 5)\n\tif saved < 16 {\n\t\tif org == nil {\n\t\t\treturn errIncompressible\n\t\t}\n\t\tb.popOffsets()\n\t\treturn b.encodeLits(org, rawAllLits)\n\t}\n\n\tvar bh blockHeader\n\tvar lh literalsHeader\n\tbh.setLast(b.last)\n\tbh.setType(blockTypeCompressed)\n\t// Store offset of the block header. Needed when we know the size.\n\tbhOffset := len(b.output)\n\tb.output = bh.appendTo(b.output)\n\n\tvar (\n\t\tout []byte\n\t\treUsed, single bool\n\t\terr error\n\t)\n\tif b.dictLitEnc != nil {\n\t\tb.litEnc.TransferCTable(b.dictLitEnc)\n\t\tb.litEnc.Reuse = huff0.ReusePolicyAllow\n\t\tb.dictLitEnc = nil\n\t}\n\tif len(b.literals) >= 1024 && !raw {\n\t\t// Use 4 Streams.\n\t\tout, reUsed, err = huff0.Compress4X(b.literals, b.litEnc)\n\t} else if len(b.literals) > 32 && !raw {\n\t\t// Use 1 stream\n\t\tsingle = true\n\t\tout, reUsed, err = huff0.Compress1X(b.literals, b.litEnc)\n\t} else {\n\t\terr = huff0.ErrIncompressible\n\t}\n\n\tswitch err {\n\tcase huff0.ErrIncompressible:\n\t\tlh.setType(literalsBlockRaw)\n\t\tlh.setSize(len(b.literals))\n\t\tb.output = lh.appendTo(b.output)\n\t\tb.output = append(b.output, b.literals...)\n\t\tif debugEncoder {\n\t\t\tprintln(\"Adding literals RAW, length\", len(b.literals))\n\t\t}\n\tcase huff0.ErrUseRLE:\n\t\tlh.setType(literalsBlockRLE)\n\t\tlh.setSize(len(b.literals))\n\t\tb.output = lh.appendTo(b.output)\n\t\tb.output = append(b.output, b.literals[0])\n\t\tif debugEncoder {\n\t\t\tprintln(\"Adding literals RLE\")\n\t\t}\n\tcase nil:\n\t\t// Compressed litLen...\n\t\tif reUsed {\n\t\t\tif debugEncoder {\n\t\t\t\tprintln(\"reused tree\")\n\t\t\t}\n\t\t\tlh.setType(literalsBlockTreeless)\n\t\t} else {\n\t\t\tif debugEncoder {\n\t\t\t\tprintln(\"new tree, size:\", len(b.litEnc.OutTable))\n\t\t\t}\n\t\t\tlh.setType(literalsBlockCompressed)\n\t\t\tif debugEncoder {\n\t\t\t\t_, _, err := huff0.ReadTable(out, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlh.setSizes(len(out), len(b.literals), single)\n\t\tif debugEncoder {\n\t\t\tprintf(\"Compressed %d literals to %d bytes\", len(b.literals), len(out))\n\t\t\tprintln(\"Adding literal header:\", lh)\n\t\t}\n\t\tb.output = lh.appendTo(b.output)\n\t\tb.output = append(b.output, out...)\n\t\tb.litEnc.Reuse = huff0.ReusePolicyAllow\n\t\tif debugEncoder {\n\t\t\tprintln(\"Adding literals compressed\")\n\t\t}\n\tdefault:\n\t\tif debugEncoder {\n\t\t\tprintln(\"Adding literals ERROR:\", err)\n\t\t}\n\t\treturn err\n\t}\n\t// Sequence compression\n\n\t// Write the number of sequences\n\tswitch {\n\tcase len(b.sequences) < 128:\n\t\tb.output = append(b.output, uint8(len(b.sequences)))\n\tcase len(b.sequences) < 0x7f00: // TODO: this could be wrong\n\t\tn := len(b.sequences)\n\t\tb.output = append(b.output, 128+uint8(n>>8), uint8(n))\n\tdefault:\n\t\tn := len(b.sequences) - 0x7f00\n\t\tb.output = append(b.output, 255, uint8(n), uint8(n>>8))\n\t}\n\tif debugEncoder {\n\t\tprintln(\"Encoding\", len(b.sequences), \"sequences\")\n\t}\n\tb.genCodes()\n\tllEnc := b.coders.llEnc\n\tofEnc := b.coders.ofEnc\n\tmlEnc := b.coders.mlEnc\n\terr = llEnc.normalizeCount(len(b.sequences))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ofEnc.normalizeCount(len(b.sequences))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = mlEnc.normalizeCount(len(b.sequences))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Choose the best compression mode for each type.\n\t// Will evaluate the new vs predefined and previous.\n\tchooseComp := func(cur, prev, preDef *fseEncoder) (*fseEncoder, seqCompMode) {\n\t\t// See if predefined/previous is better\n\t\thist := cur.count[:cur.symbolLen]\n\t\tnSize := cur.approxSize(hist) + cur.maxHeaderSize()\n\t\tpredefSize := preDef.approxSize(hist)\n\t\tprevSize := prev.approxSize(hist)\n\n\t\t// Add a small penalty for new encoders.\n\t\t// Don't bother with extremely small (<2 byte gains).\n\t\tnSize = nSize + (nSize+2*8*16)>>4\n\t\tswitch {\n\t\tcase predefSize <= prevSize && predefSize <= nSize || forcePreDef:\n\t\t\tif debugEncoder {\n\t\t\t\tprintln(\"Using predefined\", predefSize>>3, \"<=\", nSize>>3)\n\t\t\t}\n\t\t\treturn preDef, compModePredefined\n\t\tcase prevSize <= nSize:\n\t\t\tif debugEncoder {\n\t\t\t\tprintln(\"Using previous\", prevSize>>3, \"<=\", nSize>>3)\n\t\t\t}\n\t\t\treturn prev, compModeRepeat\n\t\tdefault:\n\t\t\tif debugEncoder {\n\t\t\t\tprintln(\"Using new, predef\", predefSize>>3, \". previous:\", prevSize>>3, \">\", nSize>>3, \"header max:\", cur.maxHeaderSize()>>3, \"bytes\")\n\t\t\t\tprintln(\"tl:\", cur.actualTableLog, \"symbolLen:\", cur.symbolLen, \"norm:\", cur.norm[:cur.symbolLen], \"hist\", cur.count[:cur.symbolLen])\n\t\t\t}\n\t\t\treturn cur, compModeFSE\n\t\t}\n\t}\n\n\t// Write compression mode\n\tvar mode uint8\n\tif llEnc.useRLE {\n\t\tmode |= uint8(compModeRLE) << 6\n\t\tllEnc.setRLE(b.sequences[0].llCode)\n\t\tif debugEncoder {\n\t\t\tprintln(\"llEnc.useRLE\")\n\t\t}\n\t} else {\n\t\tvar m seqCompMode\n\t\tllEnc, m = chooseComp(llEnc, b.coders.llPrev, &fsePredefEnc[tableLiteralLengths])\n\t\tmode |= uint8(m) << 6\n\t}\n\tif ofEnc.useRLE {\n\t\tmode |= uint8(compModeRLE) << 4\n\t\tofEnc.setRLE(b.sequences[0].ofCode)\n\t\tif debugEncoder {\n\t\t\tprintln(\"ofEnc.useRLE\")\n\t\t}\n\t} else {\n\t\tvar m seqCompMode\n\t\tofEnc, m = chooseComp(ofEnc, b.coders.ofPrev, &fsePredefEnc[tableOffsets])\n\t\tmode |= uint8(m) << 4\n\t}\n\n\tif mlEnc.useRLE {\n\t\tmode |= uint8(compModeRLE) << 2\n\t\tmlEnc.setRLE(b.sequences[0].mlCode)\n\t\tif debugEncoder {\n\t\t\tprintln(\"mlEnc.useRLE, code: \", b.sequences[0].mlCode, \"value\", b.sequences[0].matchLen)\n\t\t}\n\t} else {\n\t\tvar m seqCompMode\n\t\tmlEnc, m = chooseComp(mlEnc, b.coders.mlPrev, &fsePredefEnc[tableMatchLengths])\n\t\tmode |= uint8(m) << 2\n\t}\n\tb.output = append(b.output, mode)\n\tif debugEncoder {\n\t\tprintf(\"Compression modes: 0b%b\", mode)\n\t}\n\tb.output, err = llEnc.writeCount(b.output)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstart := len(b.output)\n\tb.output, err = ofEnc.writeCount(b.output)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif false {\n\t\tprintln(\"block:\", b.output[start:], \"tablelog\", ofEnc.actualTableLog, \"maxcount:\", ofEnc.maxCount)\n\t\tfmt.Printf(\"selected TableLog: %d, Symbol length: %d\\n\", ofEnc.actualTableLog, ofEnc.symbolLen)\n\t\tfor i, v := range ofEnc.norm[:ofEnc.symbolLen] {\n\t\t\tfmt.Printf(\"%3d: %5d -> %4d \\n\", i, ofEnc.count[i], v)\n\t\t}\n\t}\n\tb.output, err = mlEnc.writeCount(b.output)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Maybe in block?\n\twr := &b.wr\n\twr.reset(b.output)\n\n\tvar ll, of, ml cState\n\n\t// Current sequence\n\tseq := len(b.sequences) - 1\n\ts := b.sequences[seq]\n\tllEnc.setBits(llBitsTable[:])\n\tmlEnc.setBits(mlBitsTable[:])\n\tofEnc.setBits(nil)\n\n\tllTT, ofTT, mlTT := llEnc.ct.symbolTT[:256], ofEnc.ct.symbolTT[:256], mlEnc.ct.symbolTT[:256]\n\n\t// We have 3 bounds checks here (and in the loop).\n\t// Since we are iterating backwards it is kinda hard to avoid.\n\tllB, ofB, mlB := llTT[s.llCode], ofTT[s.ofCode], mlTT[s.mlCode]\n\tll.init(wr, &llEnc.ct, llB)\n\tof.init(wr, &ofEnc.ct, ofB)\n\twr.flush32()\n\tml.init(wr, &mlEnc.ct, mlB)\n\n\t// Each of these lookups also generates a bounds check.\n\twr.addBits32NC(s.litLen, llB.outBits)\n\twr.addBits32NC(s.matchLen, mlB.outBits)\n\twr.flush32()\n\twr.addBits32NC(s.offset, ofB.outBits)\n\tif debugSequences {\n\t\tprintln(\"Encoded seq\", seq, s, \"codes:\", s.llCode, s.mlCode, s.ofCode, \"states:\", ll.state, ml.state, of.state, \"bits:\", llB, mlB, ofB)\n\t}\n\tseq--\n\t// Store sequences in reverse...\n\tfor seq >= 0 {\n\t\ts = b.sequences[seq]\n\n\t\tofB := ofTT[s.ofCode]\n\t\twr.flush32() // tablelog max is below 8 for each, so it will fill max 24 bits.\n\t\t//of.encode(ofB)\n\t\tnbBitsOut := (uint32(of.state) + ofB.deltaNbBits) >> 16\n\t\tdstState := int32(of.state>>(nbBitsOut&15)) + int32(ofB.deltaFindState)\n\t\twr.addBits16NC(of.state, uint8(nbBitsOut))\n\t\tof.state = of.stateTable[dstState]\n\n\t\t// Accumulate extra bits.\n\t\toutBits := ofB.outBits & 31\n\t\textraBits := uint64(s.offset & bitMask32[outBits])\n\t\textraBitsN := outBits\n\n\t\tmlB := mlTT[s.mlCode]\n\t\t//ml.encode(mlB)\n\t\tnbBitsOut = (uint32(ml.state) + mlB.deltaNbBits) >> 16\n\t\tdstState = int32(ml.state>>(nbBitsOut&15)) + int32(mlB.deltaFindState)\n\t\twr.addBits16NC(ml.state, uint8(nbBitsOut))\n\t\tml.state = ml.stateTable[dstState]\n\n\t\toutBits = mlB.outBits & 31\n\t\textraBits = extraBits<<outBits | uint64(s.matchLen&bitMask32[outBits])\n\t\textraBitsN += outBits\n\n\t\tllB := llTT[s.llCode]\n\t\t//ll.encode(llB)\n\t\tnbBitsOut = (uint32(ll.state) + llB.deltaNbBits) >> 16\n\t\tdstState = int32(ll.state>>(nbBitsOut&15)) + int32(llB.deltaFindState)\n\t\twr.addBits16NC(ll.state, uint8(nbBitsOut))\n\t\tll.state = ll.stateTable[dstState]\n\n\t\toutBits = llB.outBits & 31\n\t\textraBits = extraBits<<outBits | uint64(s.litLen&bitMask32[outBits])\n\t\textraBitsN += outBits\n\n\t\twr.flush32()\n\t\twr.addBits64NC(extraBits, extraBitsN)\n\n\t\tif debugSequences {\n\t\t\tprintln(\"Encoded seq\", seq, s)\n\t\t}\n\n\t\tseq--\n\t}\n\tml.flush(mlEnc.actualTableLog)\n\tof.flush(ofEnc.actualTableLog)\n\tll.flush(llEnc.actualTableLog)\n\terr = wr.close()\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.output = wr.out\n\n\tif len(b.output)-3-bhOffset >= b.size {\n\t\t// Maybe even add a bigger margin.\n\t\tb.litEnc.Reuse = huff0.ReusePolicyNone\n\t\treturn errIncompressible\n\t}\n\n\t// Size is output minus block header.\n\tbh.setSize(uint32(len(b.output)-bhOffset) - 3)\n\tif debugEncoder {\n\t\tprintln(\"Rewriting block header\", bh)\n\t}\n\t_ = bh.appendTo(b.output[bhOffset:bhOffset])\n\tb.coders.setPrev(llEnc, mlEnc, ofEnc)\n\treturn nil\n}", "func WriteTree(writer io.Writer, hierarchy *Hierarchy, includeEmpty bool) {\n\ttree := assembleTree(hierarchy)\n\tkeys := make([]string, len(tree))\n\ti := 0\n\tfor k := range tree {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\tsort.Strings(keys)\n\tfor _, key := range keys {\n\t\tb := tree[key]\n\t\twriteBranch(writer, b, \"\", hierarchy, includeEmpty)\n\t}\n}", "func (c *Codec) serialize(root *TreeNode) string {\n\treturn rserialize(root, \"\")\n}", "func (ths *TreeHashStack) Serialize() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\n\tif err := gob.NewEncoder(buf).Encode(ths); nil != err {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func encodeTransactionOutputs(obj *transactionOutputs) ([]byte, error) {\n\tn := encodeSizeTransactionOutputs(obj)\n\tbuf := make([]byte, n)\n\n\tif err := encodeTransactionOutputsToBuffer(buf, obj); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf, nil\n}", "func (d *decoder) createTree() *node {\n\tif val, _ := readBit(d.r); val {\n\t\treturn &node{readByte(d.r), -1, false, nil, nil}\n\t} else if d.numChars != d.numCharsDecoded {\n\t\tleft := d.createTree()\n\t\tright := d.createTree()\n\t\treturn &node{0, -1, true, left, right}\n\t}\n\n\treturn nil\n}", "func main() {\n\tt11 := &TreeNode{Val:7}\n\tt21 := &TreeNode{Val:3}\n\tt22 := &TreeNode{Val:15}\n\t// t31 := &TreeNode{Val:1}\n\t// t32 := &TreeNode{Val:4}\n\tt33 := &TreeNode{Val:9}\n\tt34 := &TreeNode{Val:20}\n\tt11.Left = t21\n\tt11.Right = t22\n\t// t21.Left = t31\n\t// t21.Right = t32\n\tt22.Left = t33\n\tt22.Right = t34\n\n\tb1 := Constructor(t11)\n\n\tfmt.Println(b1.Data)\n\tfmt.Println(b1.Next())\n\tfmt.Println(b1.Next())\n\tfmt.Println(b1.HasNext())\n\tfmt.Println(b1.Next())\n\tfmt.Println(b1.HasNext())\n\tfmt.Println(b1.Next())\n\tfmt.Println(b1.HasNext())\n\tfmt.Println(b1.Next())\n\tfmt.Println(b1.HasNext())\n}", "func (t *BinaryNode) AsciiBuilder() string {\n\tvar proot *AsciiNode\n\tvar xmin int\n\tif t == nil {\n\t\treturn AsciiBuilder.String()\n\t}\n\n\tproot = BuildAsciiTree(t)\n\tFillEdgeLen(proot)\n\n\tfor i := 0; i < proot.Height; i++ {\n\t\tLprofile[i] = math.MaxInt32\n\t}\n\tComuputeLprofile(proot, 0, 0)\n\txmin = 0\n\tfor i := 0; i < proot.Height; i++ {\n\t\txmin = Min(xmin, Lprofile[i])\n\t}\n\n\tif proot.Height > MaxHeight {\n\t\tfmt.Printf(\"The tree is too fucking high than %d! how high do you want to be?\\n\",\n\t\t\tMaxHeight)\n\t}\n\tfor i := 0; i < proot.Height; i++ {\n\t\tPrintNext = 0\n\t\tPrintLevel(proot, -xmin, i)\n\t\tfmt.Fprintf(&AsciiBuilder, \"%s\", \"\\n\")\n\t}\n\ts := AsciiBuilder.String()\n\tAsciiBuilder.Reset()\n\treturn s\n}", "func Encode(blob []byte) []byte {\n\tleadZeros, size := 0, len(blob)\n\tfor leadZeros < size && blob[leadZeros] == 0 {\n\t\tleadZeros++\n\t}\n\n\t// nolint: gomnd\n\tcapacity := (size-leadZeros)*138/100 + 1 // log256 / log58\n\toutputSize := capacity - 1\n\n\toutput := make([]byte, capacity)\n\tfor _, b := range blob[leadZeros:] {\n\t\tidx := capacity - 1\n\t\tfor carry := int(b); idx > outputSize || carry != 0; idx-- {\n\t\t\tcarry += int(output[idx]) << 8 // nolint: gomnd\n\t\t\toutput[idx] = byte(carry % alphabetSize)\n\t\t\tcarry /= alphabetSize\n\t\t}\n\t\toutputSize = idx\n\t}\n\n\tencodeTable := []byte(Alphabet)\n\tres := make([]byte, leadZeros+(capacity-1-outputSize))\n\tfor i := 0; i < leadZeros; i++ {\n\t\tres[i] = alphabetIdx0\n\t}\n\n\tfor i, n := range output[outputSize+1:] {\n\t\tres[leadZeros+i] = encodeTable[n]\n\t}\n\n\treturn res\n}", "func (bs BitStream) Bytes() []byte {\n\tresult := make([]byte, 0)\n\ti := 0\n\tfor ; i+byteSize <= len(bs.bits); i += byteSize {\n\t\tslice := bs.bits[i : i+byteSize]\n\t\tresult = append(result, NewFromBits(slice).Byte())\n\t}\n\n\trest := bs.bits[i:]\n\tif len(rest) != 0 {\n\t\t// pad\n\t\tfor len(rest) < byteSize { // pad the byte\n\t\t\trest = append(rest, Bit(false))\n\t\t}\n\t\tresult = append(result, NewFromBits(rest).Byte())\n\t}\n\n\treturn result\n}", "func Compress(uncompressed *vector.Vector) *vector.Vector {\n\tbyteFrequencies := createFrequencyTable(uncompressed)\n\tprefixTree := buildPrefixTree(byteFrequencies)\n\n\tcodes := dictionary.New()\n\tbuildCodes(prefixTree, vector.New(), codes)\n\n\tcompressedPrefixTree := vector.New()\n\tcompressPrefixTree(prefixTree, compressedPrefixTree)\n\n\tencodedBytes := encodeToHuffmanCodes(uncompressed, codes)\n\n\tcompressedCodes, lastByteInBits := compressHuffmanCodes(encodedBytes)\n\n\t// Reserve space for the last byte size, prefix tree and huffman codes\n\tcompressed := vector.New(0, 1+uint(compressedPrefixTree.Size()+compressedCodes.Size()))\n\tcompressed.Append(byte(lastByteInBits))\n\n\tfor i := 0; i < compressedPrefixTree.Size(); i++ {\n\t\tcompressed.Append(compressedPrefixTree.MustGet(i))\n\t}\n\n\tfor i := 0; i < compressedCodes.Size(); i++ {\n\t\tcompressed.Append(compressedCodes.MustGet(i))\n\t}\n\n\treturn compressed\n}", "func NewEncoder() Encoder {\n return &encoder{}\n}", "func uleb128enc(bout []byte, value int) int {\n\t/* To encode:\n\tGrab the lowest 7 bits of your value and store them in a byte,\n\tthis is what you're going to output.\n\tShift the value 7 bits to the right, getting rid of those 7 bits you just grabbed.\n\tIf the value is non-zero (ie. after you shifted away 7 bits from it),\n\tset the high bit of the byte you're going to output before you output it.\n\tOutput the byte\n\tIf the value is non-zero (ie. same check that resulted in setting the high bit),\n\tgo back and repeat the steps from the start*/\n\tif len(bout) < 10 {\n\t\tpanic(\"Need to give a buffer of at least 10\")\n\t}\n\tcount := 0\n\tfor first, i := true, 0; first || value > 0; i++ {\n\t\tfirst = false\n\t\tlower7bits := byte(value & 0x7f)\n\t\tvalue >>= 7\n\t\tif value > 0 {\n\t\t\tlower7bits |= 128\n\t\t}\n\t\tbout[i] = lower7bits\n\t\tcount++\n\n\t}\n\treturn count\n}", "func (this *Codec) serializeV2(root *TreeNode) string {\n\n\tqueue :=[]*TreeNode{}\n\tqueue=append(queue,root)\n\tres :=[]string{}\n\tfor len(queue)>0 {\n\t\tnode :=queue[0] // 出队列\n\t\tqueue=queue[1:]\n\t\tif node!=nil { // 节点不为空,\n\t\t\tres =append(res,strconv.Itoa(node.Val)) //将根节点加入结果集中\n\t\t\tqueue=append(queue,node.Left) //左子节点入队\n\t\t\tqueue=append(queue,node.Right) //右子节点入队\n\t\t}else {\n\t\t\tres=append(res,\"null\") //如果是nil节点 用null代替\n\t\t}\n\t}\n\treturn strings.Join(res,\",\")\n}", "func (p *GameTree) writeTree(w *bufio.Writer, n TreeNodeIdx, needs bool, nMov int, nMovPerLine int) (err error) {\n\tdefer u(tr(\"writeTree\"))\n\tif needs == true {\n\t\tif nMov > 0 {\n\t\t\terr = w.WriteByte('\\n')\n\t\t\tnMov = 0\n\t\t}\n\t\terr = w.WriteByte('(')\n\t}\n\tif err == nil {\n\t\tif nMov == nMovPerLine {\n\t\t\terr = w.WriteByte('\\n')\n\t\t\tnMov = 0\n\t\t}\n\t\terr = w.WriteByte(';')\n\t\t// write the node\n\t\ttyp := p.treeNodes[n].TNodType\n\t\tswitch typ {\n\t\tcase GameInfoNode:\n\t\t\t// fmt.Println(\"writing GameInfoNode\\n\")\n\t\t\terr = p.writeProperties(w, n, true)\n\t\tcase InteriorNode:\n\t\t\t// fmt.Println(\"writing InteriorNode\\n\")\n\t\t\terr = p.writeProperties(w, n, false)\n\t\tcase BlackMoveNode:\n\t\t\t_, err = w.WriteString(\"B[\")\n\t\t\t_, err = w.Write(SGFCoords(ah.NodeLoc(p.treeNodes[n].propListOrNodeLoc), p.IsFF4()))\n\t\t\terr = w.WriteByte(']')\n\t\t\tnMov += 1\n\t\tcase WhiteMoveNode:\n\t\t\t_, err = w.WriteString(\"W[\")\n\t\t\t_, err = w.Write(SGFCoords(ah.NodeLoc(p.treeNodes[n].propListOrNodeLoc), p.IsFF4()))\n\t\t\terr = w.WriteByte(']')\n\t\t\tnMov += 1\n\t\tdefault:\n\t\t\tfmt.Println(\"*** unsupported TreeNodeType in writeTree\")\n\t\t\terr = errors.New(\"writeTree: unsupported TreeNodeType\" + strconv.FormatInt(int64(typ), 10))\n\t\t\treturn err\n\t\t}\n\t\tif err == nil {\n\t\t\t// write the children\n\t\t\tlastCh := p.treeNodes[n].Children\n\t\t\tif lastCh != nilTreeNodeIdx && err == nil {\n\t\t\t\tch := p.treeNodes[lastCh].NextSib\n\t\t\t\tchNeeds := (lastCh != ch)\n\t\t\t\terr = p.writeTree(w, ch, chNeeds, nMov, nMovPerLine)\n\t\t\t\tfor ch != lastCh && err == nil {\n\t\t\t\t\tch = p.treeNodes[ch].NextSib\n\t\t\t\t\t//\t\t\t\t\tnMov += 1\n\t\t\t\t\terr = p.writeTree(w, ch, chNeeds, nMov, nMovPerLine)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (err == nil) && (needs == true) {\n\t\t\t\terr = w.WriteByte(')')\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func (b *BitSet) WriteTo(ctx context.Context, w io.Writer) error {\n\tvar err error\n\n\t// Write length of the data to follow.\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb.prune()\n\n\tlb := len(b.set)\n\tlb *= 2 * binary.Size(uint64(0))\n\terr = binary.Write(w, binary.BigEndian, uint32(lb))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor key, value := range b.set {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\t{\n\t\t\t\treturn nil\n\t\t\t}\n\t\tdefault:\n\t\t\terr = binary.Write(w, binary.BigEndian, key)\n\t\t\tif err != nil {\n\t\t\t\t//return int64(binary.Size(uint32(0))), err\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = binary.Write(w, binary.BigEndian, value)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (enc *Encoding) EncodeBits(dst, src []byte, bits int) int {\n\tif bits < 0 {\n\t\treturn 0\n\t}\n\treturn enc.encode(dst, src, bits)\n}", "func (decTree *Tree) WriteTree(filename string) {\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\tfmt.Println(\"Error opening output file: \", filename)\n\t\treturn\n\t}\n\n\tcurrNode := decTree\n\tvar treeStack []*Tree\n\n\ttreeLen := 1\n\tfor treeLen != 0 {\n\t\tfile.WriteString(nodeToStr(currNode.Details))\n\n\t\tif currNode.Details.Leaf == false {\n\t\t\ttreeStack = append(treeStack, currNode.Right)\n\t\t\tcurrNode = currNode.Left\n\t\t\ttreeLen++\n\t\t} else {\n\t\t\t//get the length of the tree and set curr to the last element in the list\n\t\t\ttreeLen--\n\n\t\t\tif treeLen > 0 {\n\t\t\t\tcurrNode, treeStack = treeStack[treeLen-1], treeStack[:treeLen-1]\n\t\t\t}\n\t\t}\n\t}\n\n\tfile.Close()\n}", "func RatGobEncode(x *big.Rat,) ([]byte, error)", "func (b *Block) Encode() error {\n\tif len(b.subelements) == 0 {\n\t\t// Take no action, but is not an error\n\t\treturn nil\n\t}\n\n\tb.value = []byte{}\n\tfor _, elem := range b.subelements {\n\t\telemWire, err := elem.Wire()\n\t\tif err != nil {\n\t\t\tb.value = []byte{}\n\t\t\treturn err\n\t\t}\n\t\tb.value = append(b.value, elemWire...)\n\t}\n\n\tb.subelements = []*Block{}\n\treturn nil\n}", "func (e *encoder) emit(bits, nBits uint32) {\n\tnBits += e.nBits\n\tbits <<= 32 - nBits\n\tbits |= e.bits\n\tfor nBits >= 8 {\n\t\tb := uint8(bits >> 24)\n\t\te.writeByte(b)\n\t\tif b == 0xff {\n\t\t\te.writeByte(0x00)\n\t\t}\n\t\tbits <<= 8\n\t\tnBits -= 8\n\t}\n\te.bits, e.nBits = bits, nBits\n}", "func (enc *HuffmanEncoder) Flush() error {\n\treturn enc.bw.Flush(bs.Zero)\n}", "func (flg FrameFlag) ToCodec() FrameFlag {\n\treturn flg | CodecFlag\n}", "func decodeTree(r *bitio.Reader, nTree byte) (root *Node, err error) {\n\tvar head Node\n\tvar nodes byte\n\tvar leaves byte\n\tvar u uint64\n\n\tfor nodes < nTree {\n\t\tu, err = r.ReadBits(1)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif u == 1 {\n\t\t\tleaves++\n\t\t\tsymbol, err := r.ReadBits(8)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnode := &Node{value: byte(symbol)}\n\t\t\thead.pushBack(node)\n\t\t}\n\n\t\tif u == 0 {\n\t\t\tnodes++\n\t\t\tif nodes == nTree {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tr := head.popLast()\n\t\t\tl := head.popLast()\n\t\t\tnode := join(l, r)\n\t\t\thead.pushBack(node)\n\t\t}\n\t}\n\n\tif nodes != leaves {\n\t\terr = errors.New(\"nodes != leaves\")\n\t}\n\n\treturn head.next, err\n}", "func Encode(r *Root) *wiretype.Object {\n\treturn &wiretype.Object{\n\t\tValue: &wiretype.Object_Root{\n\t\t\tRoot: &wiretype.Root{\n\t\t\t\tFileKey: []byte(r.FileKey),\n\t\t\t\tDescription: r.Description,\n\t\t\t\tIndexKey: []byte(r.IndexKey),\n\t\t\t},\n\t\t},\n\t}\n}", "func encoder() {\n\n\tdefer func() {\n\t\tclose(OutputChan)\n\t\tWaitGroup.Done()\n\t}()\n\n\tfor {\n\t\tpcm, ok := <-EncodeChan\n\t\tif !ok {\n\t\t\t// if chan closed, exit\n\t\t\treturn\n\t\t}\n\n\t\t// try encoding pcm frame with Opus\n\t\topus, err := OpusEncoder.Encode(pcm, AudioFrameSize, MaxBytes)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Encoding Error:\", err)\n\t\t\treturn\n\t\t}\n\n\t\t// write opus data to OutputChan\n\t\tOutputChan <- opus\n\t}\n}", "func exprStream(node *node32) <-chan *node32 {\n\tout := make(chan *node32)\n\tgo func() {\n\t\tfor ; node != nil; node = node.next {\n\t\t\tswitch node.pegRule {\n\t\t\tcase ruleSPACE:\n\t\t\tcase ruleBOOLLITER:\n\t\t\t\tout <- node.up\n\t\t\tcase ruleEXPR:\n\t\t\t\tfor inode := range exprStream(node.up) {\n\t\t\t\t\tout <- inode\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tout <- node\n\t\t\t}\n\t\t}\n\t\tclose(out)\n\t}()\n\treturn out\n}", "func MulticodeEncode(g Graph) []byte {\n\tn := g.N()\n\tif n > 255 {\n\t\tpanic(\"Graph too large for Multicode\")\n\t} else if n == 0 {\n\t\treturn []byte{0}\n\t}\n\ts := make([]byte, g.M()+n)\n\ts[0] = byte(n)\n\tindex := 1\n\tfor i := 0; i < n-1; i++ {\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\tif g.IsEdge(i, j) {\n\t\t\t\ts[index] = byte(j + 1)\n\t\t\t\tindex++\n\t\t\t}\n\t\t}\n\t\ts[index] = 0\n\t\tindex++\n\t}\n\treturn s\n}", "func (n *Node) Encoded(force bool) ([]byte, error) {\n\tsort.Stable(LinkSlice(n.Links)) // keep links sorted\n\tif n.encoded == nil || force {\n\t\tvar err error\n\t\tn.encoded, err = n.Marshal()\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tn.cached = u.Hash(n.encoded)\n\t}\n\n\treturn n.encoded, nil\n}", "func main() {\n\torbits := tree{}\n\n\tif len(os.Args) < 2 {\n\t\tlog.Fatalf(\"Missing parameter, provide file name!\")\n\t\treturn\n\t}\n\n\t// raw reading of the file\n\tdata, err := ioutil.ReadFile(os.Args[1])\n\tif err != nil {\n\t\tlog.Fatalf(\"Can't read file: %v\\n\", os.Args[1])\n\t\tpanic(err)\n\t}\n\n\t// take the read file and convert it from strings to ints\n\tfor _, line := range bytes.Split(data, []byte(\"\\n\")) {\n\t\tplanets := strings.Split(strings.TrimSpace(string(line)), \")\")\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Could not extract planets from line. %v\\n\", err)\n\t\t}\n\n\t\torbits[planets[0]] = append(orbits[planets[0]], planets[1])\n\t}\n\n\tspew.Dump(\"Result:\")\n\t//\tspew.Dump(orbits)\n\n\t//\tfmt.Printf(\"nodes:%d\\n\", orbits.height(\"COM\"))\n\t//\tfmt.Printf(\"count:%d\\n\", orbits.count(\"COM\", 0))\n\tfmt.Printf(\"p:%v\\n\", orbits.parent(\"B\"))\n\tfmt.Printf(\"p:%v\\n\", orbits.parent(\"COM\"))\n\tfmt.Printf(\"q:%v\\n\", orbits.ancestry(\"YOU\"))\n\tfmt.Printf(\"q:%v\\n\", orbits.ancestry(\"SAN\"))\n\tfmt.Printf(\"q:%v\\n\", orbits.transfers(\"YOU\", \"SAN\"))\n\n}", "func Build(iterate func(func(string, interface{})), valueFor func(string) interface{}, iteratesSorted bool) ByteMap {\n\tkeysLen := 0\n\tvaluesLen := 0\n\n\trecordKey := func(key string, value interface{}) {\n\t\tvalLen := encodedLength(value)\n\t\tkeysLen += len(key) + SizeKeyLen + SizeValueType\n\t\tif valLen > 0 {\n\t\t\tkeysLen += SizeValueOffset\n\t\t}\n\t\tvaluesLen += valLen\n\t}\n\n\tvar finalIterate func(func(string, interface{}))\n\n\tif iteratesSorted {\n\t\titerate(func(key string, value interface{}) {\n\t\t\trecordKey(key, value)\n\t\t})\n\t\tfinalIterate = iterate\n\t} else {\n\t\tsortedKeys := make([]string, 0, 10)\n\t\titerate(func(key string, value interface{}) {\n\t\t\tsortedKeys = append(sortedKeys, key)\n\t\t\trecordKey(key, value)\n\t\t})\n\t\tsort.Strings(sortedKeys)\n\n\t\tfinalIterate = func(cb func(string, interface{})) {\n\t\t\tfor _, key := range sortedKeys {\n\t\t\t\tcb(key, valueFor(key))\n\t\t\t}\n\t\t}\n\t}\n\n\tstartOfValues := keysLen\n\tbm := make(ByteMap, startOfValues+valuesLen)\n\tkeyOffset := 0\n\tvalueOffset := startOfValues\n\tfinalIterate(func(key string, value interface{}) {\n\t\tkeyLen := len(key)\n\t\tenc.PutUint16(bm[keyOffset:], uint16(keyLen))\n\t\tcopy(bm[keyOffset+SizeKeyLen:], key)\n\t\tkeyOffset += SizeKeyLen + keyLen\n\t\tt, n := encodeValue(bm[valueOffset:], value)\n\t\tbm[keyOffset] = t\n\t\tkeyOffset += SizeValueType\n\t\tif t != TypeNil {\n\t\t\tenc.PutUint32(bm[keyOffset:], uint32(valueOffset))\n\t\t\tkeyOffset += SizeValueOffset\n\t\t\tvalueOffset += n\n\t\t}\n\t})\n\n\treturn bm\n}", "func (f Frame) Encode(w io.Writer, timestamp time.Time, compress bool) error {\n\tf.CorrectTimestamps(timestamp)\n\tf.Length = f.correctLength()\n\tf.Count = uint16(len(f.Blocks))\n\tf.Reserved1 = 1\n\n\tvar compressedBlockData []byte\n\tif compress {\n\t\tvar err error\n\t\tcompressedBlockData, err = f.compressBlocks()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tf.Compression = 1\n\t\tf.Length = uint32(40 + len(compressedBlockData))\n\t} else {\n\t\tf.Compression = 0\n\t}\n\n\tbuf := make([]byte, 40)\n\tcopy(buf[0:16], f.Preamble[:])\n\ttime := uint64(f.Time.UnixNano() / 1000000)\n\tbinary.LittleEndian.PutUint64(buf[16:24], time)\n\tbinary.LittleEndian.PutUint32(buf[24:28], f.Length)\n\tbinary.LittleEndian.PutUint16(buf[28:30], f.ConnectionType)\n\tbinary.LittleEndian.PutUint16(buf[30:32], f.Count)\n\tbuf[32] = f.Reserved1\n\tbuf[33] = f.Compression\n\tbinary.LittleEndian.PutUint16(buf[34:36], f.Reserved2)\n\tbinary.LittleEndian.PutUint32(buf[36:40], f.DecompressedLength)\n\n\t_, err := w.Write(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif compress {\n\t\t_, err := w.Write(compressedBlockData)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tfor _, b := range f.Blocks {\n\t\t\terr := b.Encode(w)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\treturn nil\n}", "func ToBits(bs []byte) []bool {\n\tbits := make([]bool, len(bs)*8)\n\tfor i := 0; i < len(bits); i++ {\n\t\tbits[i] = (bs[i/8]<<uint(i%8))&(1<<7) > 0\n\t}\n\treturn bits\n}", "func ToBytes(bits []bool) []byte {\n\tbs := make([]byte, (len(bits)+7)/8)\n\tfor i := 0; i < len(bits); i++ {\n\t\tif bits[i] {\n\t\t\tbs[i/8] |= (1 << 7) >> uint(i%8)\n\t\t}\n\t}\n\treturn bs\n}", "func main() {\n\troot := &TreeNode{\n\t\tVal: 2,\n\t\tLeft: &TreeNode{\n\t\t\tVal: 1,\n\t\t},\n\t\tRight: &TreeNode{\n\t\t\tVal: 3,\n\t\t},\n\t}\n\tprintTreeNodeByDFS(root)\n\tfmt.Println()\n\n\tser := Constructor()\n\ttreeString := ser.serialize(root)\n\tfmt.Println(treeString)\n\tans := ser.deserialize(treeString)\n\t// printTreeNodeByBFS(ans)\n\tprintTreeNodeByDFS(ans)\n\tfmt.Println()\n}", "func toEncoded(keys []*datastore.Key) (full []string, roots stringset.Set) {\n\troots = stringset.New(len(keys))\n\tfull = make([]string, len(keys))\n\tfor i, k := range keys {\n\t\troots.Add(string(datastore.Serialize.ToBytes(k.Root())))\n\t\tfull[i] = string(datastore.Serialize.ToBytes(k))\n\t}\n\treturn\n}", "func Encode(packet packets.NdnPacket, byteStream io.Writer) error {\n\tt := Tlv{}\n\tswitch packet.PacketType() {\n\tcase INTEREST:\n\t\tt, _ = encodeInterest(packet.(packets.Interest))\n\tcase DATA:\n\t\tt, _ = encodeData(packet.(packets.Data))\n\tdefault:\n\t\treturn errors.New(\"Encode: -- unknown packet type --\")\n\t}\n\n\t//write the tlv as bytes\n\terr := TlvToBytes(t, byteStream)\n\treturn err\n}", "func (n *node) encodeValue(offset uint32, size uint32) {\n\tencodedValue := uint64(size)\n\tencodedValue += uint64(offset) << 32\n\tatomic.StoreUint64(&n.encodedValue, encodedValue)\n}", "func binaryEncode(dst, src []byte) {\n\td := uint(0)\n\t_, _ = src[0], dst[7]\n\tfor i := 7; i >= 0; i-- {\n\t\tif src[0]&(1<<d) == 0 {\n\t\t\tdst[i] = '0'\n\t\t} else {\n\t\t\tdst[i] = '1'\n\t\t}\n\t\td++\n\t}\n}", "func (t Tree) Interpret(bs *bitstream.BitStream) byte {\n\treturn t.walk(t.root, bs)\n}", "func (mp *MerkleProof) ToBytes() ([]byte, error) {\r\n\tindex := bt.VarInt(mp.Index)\r\n\r\n\ttxOrID, err := hex.DecodeString(mp.TxOrID)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\ttxOrID = bt.ReverseBytes(txOrID)\r\n\r\n\ttarget, err := hex.DecodeString(mp.Target)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\ttarget = bt.ReverseBytes(target)\r\n\r\n\tnodeCount := len(mp.Nodes)\r\n\r\n\tnodes := []byte{}\r\n\r\n\tfor _, n := range mp.Nodes {\r\n\t\tif n == \"*\" {\r\n\t\t\tnodes = append(nodes, []byte{1}...)\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\tnodes = append(nodes, []byte{0}...)\r\n\t\tnb, err := hex.DecodeString(n)\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\t\tnodes = append(nodes, bt.ReverseBytes(nb)...)\r\n\r\n\t}\r\n\r\n\tvar flags uint8\r\n\r\n\tvar txLength []byte\r\n\tif len(mp.TxOrID) > 64 { // tx bytes instead of txid\r\n\t\t// set bit at index 0\r\n\t\tflags |= (1 << 0)\r\n\r\n\t\ttxLength = bt.VarInt(uint64(len(txOrID)))\r\n\t}\r\n\r\n\tif mp.TargetType == \"header\" {\r\n\t\t// set bit at index 1\r\n\t\tflags |= (1 << 1)\r\n\t} else if mp.TargetType == \"merkleRoot\" {\r\n\t\t// set bit at index 2\r\n\t\tflags |= (1 << 2)\r\n\t}\r\n\r\n\t// ignore proofType and compositeType for this version\r\n\r\n\tbytes := []byte{}\r\n\tbytes = append(bytes, flags)\r\n\tbytes = append(bytes, index...)\r\n\tbytes = append(bytes, txLength...)\r\n\tbytes = append(bytes, txOrID...)\r\n\tbytes = append(bytes, target...)\r\n\tbytes = append(bytes, byte(nodeCount))\r\n\tbytes = append(bytes, nodes...)\r\n\r\n\treturn bytes, nil\r\n}" ]
[ "0.5976212", "0.588826", "0.57714266", "0.56684834", "0.5471367", "0.5359475", "0.53010243", "0.52597386", "0.52532464", "0.5214008", "0.52020335", "0.5191336", "0.5183353", "0.51561105", "0.51269877", "0.51163054", "0.5077814", "0.5068617", "0.50552714", "0.5026026", "0.49952075", "0.49755093", "0.4950272", "0.4947061", "0.49440256", "0.4942683", "0.49236396", "0.49215308", "0.49030536", "0.4896708", "0.48689228", "0.48538688", "0.4845682", "0.48452756", "0.48421586", "0.48262382", "0.48240975", "0.48071498", "0.48029566", "0.47929904", "0.47797376", "0.47676125", "0.4746899", "0.47431242", "0.47310725", "0.47110128", "0.47108", "0.4701854", "0.46719247", "0.46596536", "0.4656221", "0.4622193", "0.4577035", "0.45678088", "0.45651653", "0.45601222", "0.455789", "0.4549957", "0.4539616", "0.45303515", "0.45200565", "0.44957307", "0.44925857", "0.44461408", "0.44329944", "0.44121504", "0.44113478", "0.44104216", "0.4408534", "0.4399156", "0.43981904", "0.43894818", "0.43874544", "0.438242", "0.43636003", "0.4356293", "0.435628", "0.43548116", "0.43536046", "0.43508103", "0.43497807", "0.43495238", "0.43347794", "0.43317312", "0.43258905", "0.43159577", "0.43152708", "0.43110076", "0.43010774", "0.4293923", "0.42933777", "0.42896345", "0.4283403", "0.42746603", "0.42711675", "0.4267761", "0.42662787", "0.42623717", "0.42597544", "0.42531937" ]
0.69163007
0
AllTypes returns all of the value types.
func AllTypes() []Type { return []Type{TypeInt, TypeUInt, TypeFloat, TypeBool, TypeString} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TypeValues() []Type {\n\treturn _TypeValues\n}", "func (pkg *Package) ValuesOfType(typeName string) ([]string, map[string]bool, error) {\n\tvar values, inspectErrs []string\n\ttmplsToExclude := map[string]bool{}\n\n\tfor _, file := range pkg.files {\n\t\tast.Inspect(file, func(node ast.Node) bool {\n\t\t\tswitch decl := node.(type) {\n\t\t\tcase *ast.GenDecl:\n\t\t\t\tswitch decl.Tok {\n\t\t\t\tcase token.CONST:\n\t\t\t\t\tvs, err := pkg.constOfTypeIn(typeName, decl)\n\t\t\t\t\tvalues = append(values, vs...)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tinspectErrs = append(inspectErrs, err.Error())\n\t\t\t\t\t}\n\n\t\t\t\tcase token.VAR:\n\t\t\t\t\tvs := pkg.varOfTypeIn(typeName, decl)\n\t\t\t\t\tfor k, v := range vs {\n\t\t\t\t\t\ttmplsToExclude[k] = v\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\tcase *ast.FuncDecl:\n\t\t\t\tvs := pkg.methodsOfTypeIn(typeName, decl)\n\t\t\t\tfor k, v := range vs {\n\t\t\t\t\ttmplsToExclude[k] = v\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\treturn false\n\t\t})\n\t}\n\n\tif len(inspectErrs) > 0 {\n\t\treturn nil, nil, fmt.Errorf(\"inspecting code:\\n\\t%v\", strings.Join(inspectErrs, \"\\n\\t\"))\n\t}\n\tif len(values) == 0 {\n\t\treturn nil, nil, fmt.Errorf(\"no values defined for type %s\", typeName)\n\t}\n\n\treturn values, tmplsToExclude, nil\n}", "func Type_Values() []string {\n\treturn []string{\n\t\tTypeRelationship,\n\t\tTypeString,\n\t\tTypeLong,\n\t\tTypeBoolean,\n\t\tTypeInteger,\n\t\tTypeDouble,\n\t\tTypeList,\n\t\tTypeMap,\n\t}\n}", "func (Type) Values() []Type {\n\treturn []Type{\n\t\t\"PullRequest\",\n\t\t\"RepositoryAnalysis\",\n\t}\n}", "func SimpleType_Values() []SimpleType {\n\treturn []SimpleType{\n\t\tSimpleTypeBool,\n\t\tSimpleTypeByte,\n\t\tSimpleTypeInt8,\n\t\tSimpleTypeInt16,\n\t\tSimpleTypeInt32,\n\t\tSimpleTypeInt64,\n\t\tSimpleTypeFloat64,\n\t\tSimpleTypeString,\n\t\tSimpleTypeStructEmpty,\n\t}\n}", "func DataTypeValues() []DataType {\n\treturn _DataTypeValues\n}", "func (FeatureType) Values() []FeatureType {\n\treturn []FeatureType{\n\t\t\"Integral\",\n\t\t\"Fractional\",\n\t\t\"String\",\n\t}\n}", "func TestTypes(t *testing.T) {\n\tprimitiveTypes()\n\tconstTypes()\n\ttypeStruct()\n}", "func Type_Values() []string {\n\treturn []string{\n\t\tTypeDash,\n\t\tTypeHls,\n\t}\n}", "func (MembershipType) Values() []MembershipType {\n\treturn []MembershipType{\n\t\t\"static\",\n\t\t\"igmp\",\n\t}\n}", "func (o FleetMetricAggregationTypeOutput) Values() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v FleetMetricAggregationType) []string { return v.Values }).(pulumi.StringArrayOutput)\n}", "func (o FleetMetricAggregationTypePtrOutput) Values() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *FleetMetricAggregationType) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Values\n\t}).(pulumi.StringArrayOutput)\n}", "func Type_Values() []string {\n\treturn []string{\n\t\tTypeConversation,\n\t\tTypeDictation,\n\t}\n}", "func (ModelInfrastructureType) Values() []ModelInfrastructureType {\n\treturn []ModelInfrastructureType{\n\t\t\"RealTimeInference\",\n\t}\n}", "func FeatureType_Values() []string {\n\treturn []string{\n\t\tFeatureTypeIntegral,\n\t\tFeatureTypeFractional,\n\t\tFeatureTypeString,\n\t}\n}", "func (ProjectionType) Values() []ProjectionType {\n\treturn []ProjectionType{\n\t\t\"ALL\",\n\t\t\"KEYS_ONLY\",\n\t\t\"INCLUDE\",\n\t}\n}", "func (MemberType) Values() []MemberType {\n\treturn []MemberType{\n\t\t\"User\",\n\t\t\"Bot\",\n\t\t\"Webhook\",\n\t}\n}", "func (PrincipalType) Values() []PrincipalType {\n\treturn []PrincipalType{\n\t\t\"All\",\n\t\t\"Service\",\n\t\t\"OrganizationUnit\",\n\t\t\"Account\",\n\t\t\"User\",\n\t\t\"Role\",\n\t}\n}", "func (AssemblyType) Values() []AssemblyType {\n\treturn []AssemblyType{\n\t\t\"None\",\n\t\t\"Line\",\n\t}\n}", "func (bi *BinaryInfo) Types() ([]string, error) {\n\ttypes := make([]string, 0, len(bi.types))\n\tfor k := range bi.types {\n\t\ttypes = append(types, k)\n\t}\n\treturn types, nil\n}", "func AllTypes() []interface{} {\n\treturn []interface{}{AuthenticationProvider{}, User{}, UserAuthPoint{}}\n}", "func ModelInfrastructureType_Values() []string {\n\treturn []string{\n\t\tModelInfrastructureTypeRealTimeInference,\n\t}\n}", "func (EncodingType) Values() []EncodingType {\n\treturn []EncodingType{\n\t\t\"binary\",\n\t\t\"json\",\n\t}\n}", "func (Type) Values() []Type {\n\treturn []Type{\n\t\t\"DASH\",\n\t\t\"HLS\",\n\t}\n}", "func (o GetInstanceTypesResultOutput) Types() GetInstanceTypesTypeArrayOutput {\n\treturn o.ApplyT(func(v GetInstanceTypesResult) []GetInstanceTypesType { return v.Types }).(GetInstanceTypesTypeArrayOutput)\n}", "func (ModelPackageType) Values() []ModelPackageType {\n\treturn []ModelPackageType{\n\t\t\"Versioned\",\n\t\t\"Unversioned\",\n\t\t\"Both\",\n\t}\n}", "func (TemplateParameterDataType) Values() []TemplateParameterDataType {\n\treturn []TemplateParameterDataType{\n\t\t\"NUMBER\",\n\t\t\"STRING\",\n\t}\n}", "func (VariableType) Values() []VariableType {\n\treturn []VariableType{\n\t\t\"INCIDENT_RECORD_ARN\",\n\t\t\"INVOLVED_RESOURCES\",\n\t}\n}", "func (HypervisorType) Values() []HypervisorType {\n\treturn []HypervisorType{\n\t\t\"ovm\",\n\t\t\"xen\",\n\t}\n}", "func (NodeDataType) Values() []NodeDataType {\n\treturn []NodeDataType{\n\t\t\"INT8\",\n\t\t\"UINT8\",\n\t\t\"INT16\",\n\t\t\"UINT16\",\n\t\t\"INT32\",\n\t\t\"UINT32\",\n\t\t\"INT64\",\n\t\t\"UINT64\",\n\t\t\"BOOLEAN\",\n\t\t\"FLOAT\",\n\t\t\"DOUBLE\",\n\t\t\"STRING\",\n\t\t\"UNIX_TIMESTAMP\",\n\t\t\"INT8_ARRAY\",\n\t\t\"UINT8_ARRAY\",\n\t\t\"INT16_ARRAY\",\n\t\t\"UINT16_ARRAY\",\n\t\t\"INT32_ARRAY\",\n\t\t\"UINT32_ARRAY\",\n\t\t\"INT64_ARRAY\",\n\t\t\"UINT64_ARRAY\",\n\t\t\"BOOLEAN_ARRAY\",\n\t\t\"FLOAT_ARRAY\",\n\t\t\"DOUBLE_ARRAY\",\n\t\t\"STRING_ARRAY\",\n\t\t\"UNIX_TIMESTAMP_ARRAY\",\n\t\t\"UNKNOWN\",\n\t}\n}", "func SchemaValueType_Values() []string {\n\treturn []string{\n\t\tSchemaValueTypeLong,\n\t\tSchemaValueTypeInt,\n\t\tSchemaValueTypeString,\n\t\tSchemaValueTypeFloat,\n\t\tSchemaValueTypeDouble,\n\t\tSchemaValueTypeBoolean,\n\t}\n}", "func (AnalysisType) Values() []AnalysisType {\n\treturn []AnalysisType{\n\t\t\"Security\",\n\t\t\"CodeQuality\",\n\t}\n}", "func (VirtualizationType) Values() []VirtualizationType {\n\treturn []VirtualizationType{\n\t\t\"hvm\",\n\t\t\"paravirtual\",\n\t}\n}", "func PossibleTypeValues() []Type {\n\treturn []Type{CUSTOMNAME, FIXED, PREFIXBASED, USERDEFINED, VIRTUALMACHINENAME}\n}", "func (v Version) Types() []Type {\n\tif !v.Valid() {\n\t\treturn nil\n\t}\n\treturn versions[v].types\n}", "func SchemaAttributeType_Values() []string {\n\treturn []string{\n\t\tSchemaAttributeTypeName,\n\t\tSchemaAttributeTypeNameFirst,\n\t\tSchemaAttributeTypeNameMiddle,\n\t\tSchemaAttributeTypeNameLast,\n\t\tSchemaAttributeTypeAddress,\n\t\tSchemaAttributeTypeAddressStreet1,\n\t\tSchemaAttributeTypeAddressStreet2,\n\t\tSchemaAttributeTypeAddressStreet3,\n\t\tSchemaAttributeTypeAddressCity,\n\t\tSchemaAttributeTypeAddressState,\n\t\tSchemaAttributeTypeAddressCountry,\n\t\tSchemaAttributeTypeAddressPostalcode,\n\t\tSchemaAttributeTypePhone,\n\t\tSchemaAttributeTypePhoneNumber,\n\t\tSchemaAttributeTypePhoneCountrycode,\n\t\tSchemaAttributeTypeEmailAddress,\n\t\tSchemaAttributeTypeUniqueId,\n\t\tSchemaAttributeTypeDate,\n\t\tSchemaAttributeTypeString,\n\t}\n}", "func (MonitoringType) Values() []MonitoringType {\n\treturn []MonitoringType{\n\t\t\"DataQuality\",\n\t\t\"ModelQuality\",\n\t\t\"ModelBias\",\n\t\t\"ModelExplainability\",\n\t}\n}", "func (DiscoveryType) Values() []DiscoveryType {\n\treturn []DiscoveryType{\n\t\t\"RESOURCE_GROUP_BASED\",\n\t\t\"ACCOUNT_BASED\",\n\t}\n}", "func (ClarifyFeatureType) Values() []ClarifyFeatureType {\n\treturn []ClarifyFeatureType{\n\t\t\"numerical\",\n\t\t\"categorical\",\n\t\t\"text\",\n\t}\n}", "func (FleetType) Values() []FleetType {\n\treturn []FleetType{\n\t\t\"request\",\n\t\t\"maintain\",\n\t\t\"instant\",\n\t}\n}", "func AllTypeInfo() *types.Info {\n\treturn &types.Info{\n\t\tTypes: make(map[ast.Expr]types.TypeAndValue),\n\t\tDefs: make(map[*ast.Ident]types.Object),\n\t\tUses: make(map[*ast.Ident]types.Object),\n\t\tImplicits: make(map[ast.Node]types.Object),\n\t\tSelections: make(map[*ast.SelectorExpr]*types.Selection),\n\t\tScopes: make(map[ast.Node]*types.Scope),\n\t}\n}", "func (LocalStorageType) Values() []LocalStorageType {\n\treturn []LocalStorageType{\n\t\t\"hdd\",\n\t\t\"ssd\",\n\t}\n}", "func (RestController *RestController) GetDataTypes(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tdataTypes := RestController.databaseController.ListDataTypes()\n\tjsonBytes, err := json.Marshal(*dataTypes)\n\tif err == nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(200)\n\t\tfmt.Fprintf(w, \"%s\", jsonBytes)\n\t} else {\n\t\tmsg := fmt.Sprintf(\"An error occurred during marshaling of list of data types: %s\\n\", err)\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tw.WriteHeader(500)\n\t\tfmt.Fprintf(w, \"%s\", msg)\n\t\tconfiguration.Error.Printf(msg)\n\t}\n}", "func (MarketType) Values() []MarketType {\n\treturn []MarketType{\n\t\t\"spot\",\n\t}\n}", "func (FileSystemType) Values() []FileSystemType {\n\treturn []FileSystemType{\n\t\t\"EFS\",\n\t\t\"FSxLustre\",\n\t}\n}", "func printTypes(vals []interface{}) string {\n\ts := \"[\"\n\tfor ix, val := range vals {\n\t\tif ix > 0 {\n\t\t\ts += \", \"\n\t\t}\n\t\ts += reflect.TypeOf(val).String()\n\t}\n\treturn s + \"]\"\n}", "func IndexType_Values() []string {\n\treturn []string{\n\t\tIndexTypeLocal,\n\t\tIndexTypeAggregator,\n\t}\n}", "func (TestType) Values() []TestType {\n\treturn []TestType{\n\t\t\"BUILTIN_FUZZ\",\n\t\t\"BUILTIN_EXPLORER\",\n\t\t\"WEB_PERFORMANCE_PROFILE\",\n\t\t\"APPIUM_JAVA_JUNIT\",\n\t\t\"APPIUM_JAVA_TESTNG\",\n\t\t\"APPIUM_PYTHON\",\n\t\t\"APPIUM_NODE\",\n\t\t\"APPIUM_RUBY\",\n\t\t\"APPIUM_WEB_JAVA_JUNIT\",\n\t\t\"APPIUM_WEB_JAVA_TESTNG\",\n\t\t\"APPIUM_WEB_PYTHON\",\n\t\t\"APPIUM_WEB_NODE\",\n\t\t\"APPIUM_WEB_RUBY\",\n\t\t\"CALABASH\",\n\t\t\"INSTRUMENTATION\",\n\t\t\"UIAUTOMATION\",\n\t\t\"UIAUTOMATOR\",\n\t\t\"XCTEST\",\n\t\t\"XCTEST_UI\",\n\t\t\"REMOTE_ACCESS_RECORD\",\n\t\t\"REMOTE_ACCESS_REPLAY\",\n\t}\n}", "func KindValues() []Kind {\n\treturn _KindValues\n}", "func (CEType) Values() []CEType {\n\treturn []CEType{\n\t\t\"MANAGED\",\n\t\t\"UNMANAGED\",\n\t}\n}", "func Valueize(values ...reflect.Value) []reflect.Value {\n\treturn values\n}", "func (TrustProviderType) Values() []TrustProviderType {\n\treturn []TrustProviderType{\n\t\t\"user\",\n\t\t\"device\",\n\t}\n}", "func PossibleTypeValues() []Type {\n\treturn []Type{TypeBuiltIn, TypeCustom, TypeNotSpecified, TypeStatic}\n}", "func (DeviceSubsetType) Values() []DeviceSubsetType {\n\treturn []DeviceSubsetType{\n\t\t\"PERCENTAGE\",\n\t\t\"SELECTION\",\n\t\t\"NAMECONTAINS\",\n\t}\n}", "func DataTypes() {\n\tvar a int = 8\n\tvar b int8 = 20\n\n\tfmt.Println(\" the Values are \", a, b)\n\n}", "func (TranscribeMedicalContentIdentificationType) Values() []TranscribeMedicalContentIdentificationType {\n\treturn []TranscribeMedicalContentIdentificationType{\n\t\t\"PHI\",\n\t}\n}", "func (s *Structx) Values() []interface{} {\n\tvar result []interface{}\n\n\tfs := s.Fields()\n\tfor _, v := range fs {\n\t\tif !v.IsExport() {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, v.Value())\n\t}\n\n\treturn result\n}", "func (l Leftovers) Types() {\n\tl.logger.NoConfirm()\n\n\tfor _, r := range l.resources {\n\t\tl.logger.Println(r.Type())\n\t}\n}", "func (StatisticType) Values() []StatisticType {\n\treturn []StatisticType{\n\t\t\"p50\",\n\t}\n}", "func (o SchemaPackageOutput) Types() Hl7TypesConfigArrayOutput {\n\treturn o.ApplyT(func(v SchemaPackage) []Hl7TypesConfig { return v.Types }).(Hl7TypesConfigArrayOutput)\n}", "func Type_Values() []string {\n\treturn []string{\n\t\tTypeImportAssetsFromS3,\n\t\tTypeImportAssetFromSignedUrl,\n\t\tTypeExportAssetsToS3,\n\t\tTypeExportAssetToSignedUrl,\n\t\tTypeExportRevisionsToS3,\n\t\tTypeImportAssetsFromRedshiftDataShares,\n\t\tTypeImportAssetFromApiGatewayApi,\n\t\tTypeCreateS3DataAccessFromS3Bucket,\n\t\tTypeImportAssetsFromLakeFormationTagPolicy,\n\t}\n}", "func (DomainType) Values() []DomainType {\n\treturn []DomainType{\n\t\t\"vpc\",\n\t\t\"standard\",\n\t}\n}", "func MeasureValueType_Values() []string {\n\treturn []string{\n\t\tMeasureValueTypeDouble,\n\t\tMeasureValueTypeBigint,\n\t\tMeasureValueTypeVarchar,\n\t\tMeasureValueTypeBoolean,\n\t\tMeasureValueTypeTimestamp,\n\t\tMeasureValueTypeMulti,\n\t}\n}", "func (RootDeviceType) Values() []RootDeviceType {\n\treturn []RootDeviceType{\n\t\t\"ebs\",\n\t\t\"instance-store\",\n\t}\n}", "func (f Fields) ValuesForFieldOfType(fieldName, typ string) []string {\n\tvar res []string\n\tfor _, field := range f {\n\t\tif field.Var == fieldName && field.Type == typ && len(field.Values) > 0 {\n\t\t\tres = append(res, field.Values...)\n\t\t}\n\t}\n\treturn res\n}", "func (SnowballType) Values() []SnowballType {\n\treturn []SnowballType{\n\t\t\"STANDARD\",\n\t\t\"EDGE\",\n\t\t\"EDGE_C\",\n\t\t\"EDGE_CG\",\n\t\t\"EDGE_S\",\n\t\t\"SNC1_HDD\",\n\t\t\"SNC1_SSD\",\n\t\t\"V3_5C\",\n\t\t\"V3_5S\",\n\t\t\"RACK_5U_C\",\n\t}\n}", "func (o GetDomainNameEndpointConfigurationOutput) Types() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetDomainNameEndpointConfiguration) []string { return v.Types }).(pulumi.StringArrayOutput)\n}", "func (e *Extractor) Values() (out []interface{}, err error) {\n\n\tif err := e.isValidStruct(); err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := reflect.ValueOf(e.StructAddr).Elem()\n\tfields := e.fields(s)\n\n\tfor _, field := range fields {\n\t\tout = append(out, field.value.Interface())\n\n\t}\n\n\treturn\n}", "func (ParameterType) Values() []ParameterType {\n\treturn []ParameterType{\n\t\t\"Integer\",\n\t\t\"Continuous\",\n\t\t\"Categorical\",\n\t\t\"FreeText\",\n\t}\n}", "func (m *MapConvert) Values(prefix string, values map[string]*jason.Value) []DataType {\n\tvar results []DataType\n\tinput := make(map[string]jason.Value, len(values))\n\tfor k, v := range values {\n\t\tinput[k] = *v\n\t}\n\n\tfor name, value := range input {\n\t\tvar result DataType\n\t\tif _, ok := m.MemoryTypes[strings.ToLower(name)]; ok {\n\t\t\tresult, ok = m.getMemoryTypes(prefix, name, &value)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbyteTypeCount.Add(1)\n\t\t} else if obj, err := value.Object(); err == nil {\n\t\t\t// we are dealing with nested objects\n\t\t\tresults = append(results, m.Values(prefix+name+\".\", obj.Map())...)\n\t\t\tnestedTypeCount.Add(1)\n\t\t\tcontinue\n\t\t} else if s, err := value.String(); err == nil {\n\t\t\tstringTypeCount.Add(1)\n\t\t\tresult = NewStringType(prefix+name, s)\n\t\t} else if f, err := value.Float64(); err == nil {\n\t\t\tfloatTypeCount.Add(1)\n\t\t\tresult = NewFloatType(prefix+name, f)\n\t\t} else if arr, err := value.Array(); err == nil {\n\t\t\t// we are dealing with an array object\n\t\t\tresult = m.arrayValue(prefix, name, arr)\n\t\t} else {\n\t\t\tdataTypeErrs.Add(1)\n\t\t\tcontinue\n\t\t}\n\t\tdataTypeObjs.Add(1)\n\t\tif result != nil { // TEST: write tests (7)\n\t\t\tresults = append(results, result)\n\t\t}\n\t}\n\treturn results\n}", "func (l Leftovers) Types() {\n\tfor _, r := range l.resources {\n\t\tl.logger.Println(r.Type())\n\t}\n}", "func (me TClassListType) Values() (list []xsdt.String) {\n\tsvals := xsdt.ListValues(string(me))\n\tlist = make([]xsdt.String, len(svals))\n\tfor i, s := range svals {\n\t\tlist[i].Set(s)\n\t}\n\treturn\n}", "func MatchFieldType_Values() []string {\n\treturn []string{\n\t\tMatchFieldTypeUri,\n\t\tMatchFieldTypeQueryString,\n\t\tMatchFieldTypeHeader,\n\t\tMatchFieldTypeMethod,\n\t\tMatchFieldTypeBody,\n\t\tMatchFieldTypeSingleQueryArg,\n\t\tMatchFieldTypeAllQueryArgs,\n\t}\n}", "func (this *ObjectValues) Type() value.Type { return value.ARRAY }", "func (this *ObjectValues) Type() value.Type { return value.ARRAY }", "func PossibleTypeValues() []Type {\n\treturn []Type{TypeSQLConnectionInfo, TypeUnknown}\n}", "func EventTypeValues() []EventType {\n\treturn _EventTypeValues\n}", "func (UserType) Values() []UserType {\n\treturn []UserType{\n\t\t\"PrivateUser\",\n\t\t\"SharedDevice\",\n\t}\n}", "func (ContainerProviderType) Values() []ContainerProviderType {\n\treturn []ContainerProviderType{\n\t\t\"EKS\",\n\t}\n}", "func (TranscribeContentIdentificationType) Values() []TranscribeContentIdentificationType {\n\treturn []TranscribeContentIdentificationType{\n\t\t\"PII\",\n\t}\n}", "func (InferenceExperimentType) Values() []InferenceExperimentType {\n\treturn []InferenceExperimentType{\n\t\t\"ShadowMode\",\n\t}\n}", "func ModelPackageType_Values() []string {\n\treturn []string{\n\t\tModelPackageTypeVersioned,\n\t\tModelPackageTypeUnversioned,\n\t\tModelPackageTypeBoth,\n\t}\n}", "func (ConnectivityType) Values() []ConnectivityType {\n\treturn []ConnectivityType{\n\t\t\"private\",\n\t\t\"public\",\n\t}\n}", "func ServerType_Values() []string {\n\treturn []string{\n\t\tServerTypeVirtualMachine,\n\t}\n}", "func (AppType) Values() []AppType {\n\treturn []AppType{\n\t\t\"JupyterServer\",\n\t\t\"KernelGateway\",\n\t\t\"TensorBoard\",\n\t\t\"RStudioServerPro\",\n\t\t\"RSessionGateway\",\n\t}\n}", "func (MonitoringProblemType) Values() []MonitoringProblemType {\n\treturn []MonitoringProblemType{\n\t\t\"BinaryClassification\",\n\t\t\"MulticlassClassification\",\n\t\t\"Regression\",\n\t}\n}", "func Types(err error) []string {\n\treturn deepAppendTypes(nil, err)\n}", "func testTypes() (ts []testType) {\n\tts = []testType{\n\t\t{\"test.Ints\", TestIntsStruct{8, 16, 32, 64}},\n\t\t{\"test.NamedInts\", TestNamedIntsStruct{8, 16, 32, 64}},\n\t\t{\"test.Uints\", TestUintsStruct{8, 16, 32, 64}},\n\t\t{\"test.NamedUints\", TestNamedUintsStruct{8, 16, 32, 64}},\n\t\t{\"test.String\", TestStringStruct{\"string\"}},\n\t\t{\"test.NamedString\", TestNamedStringStruct{\"named string\"}},\n\t\t{\"test.Floats\", TestFloatsStruct{32.0, 64.0}},\n\t\t{\"test.NamedFloats\", TestNamedFloatsStruct{32.0, 64.0}},\n\t\t{\"test.Empty\", TestEmptyStruct{}},\n\t\t{\"test.Arrays\", TestArraysStruct{\n\t\t\t[0]int8{},\n\t\t\t[1]int16{16},\n\t\t\t[2]string{\"string\", \"string\"},\n\t\t\t[3]TestEmptyStruct{},\n\t\t\t[4]TestStringStruct{{\"string\"}, {\"string\"}, {\"string\"}, {\"string\"}},\n\t\t\tTestNamedArray{10, 11, 12, 13, 14},\n\t\t}},\n\t\t{\"test.Slices\", TestSliceStruct{\n\t\t\t[]int8{8},\n\t\t\tTestNamedSlice{32},\n\t\t\t[]string{\"string\", \"string\"},\n\t\t\t[]TestEmptyStruct{},\n\t\t\t[]TestStringStruct{{\"string\"}, {\"string\"}, {\"string\"}, {\"string\"}},\n\t\t}},\n\t\t{\"test.User\", TestUser{\"Alice\", 15, []byte(\"hey-ho!\")}},\n\t\t{\"test.Group\", TestGroup{Name: \"the CXO\"}},\n\t\t{\"test.Man\", TestMan{\"kostyarin\", \"logrusorgru\"}},\n\t}\n\n\treturn\n}", "func (PhoneNumberType) Values() []PhoneNumberType {\n\treturn []PhoneNumberType{\n\t\t\"Local\",\n\t\t\"TollFree\",\n\t}\n}", "func (OrchestrationType) Values() []OrchestrationType {\n\treturn []OrchestrationType{\n\t\t\"ECS\",\n\t\t\"EKS\",\n\t}\n}", "func (me TcoordinatesType) Values() (list []xsdt.String) {\r\n\tsvals := xsdt.ListValues(string(me))\r\n\tlist = make([]xsdt.String, len(svals))\r\n\tfor i, s := range svals {\r\n\t\tlist[i].Set(s)\r\n\t}\r\n\treturn\r\n}", "func PossibleTypeValues() []Type {\n\treturn []Type{TypeBuildStepProperties, TypeDocker}\n}", "func PossibleTypeValues() []Type {\n\treturn []Type{MicrosoftKustoclustersattachedDatabaseConfigurations, MicrosoftKustoclustersdatabases}\n}", "func (UsageClassType) Values() []UsageClassType {\n\treturn []UsageClassType{\n\t\t\"spot\",\n\t\t\"on-demand\",\n\t}\n}", "func nativeToTypeList(valueList []interface{}) []LogValueType {\n\tt := TypeByteData\n\ttypeList := make([]LogValueType, len(valueList))\n\tfor _, val := range valueList {\n\t\tswitch val.(type) {\n\t\tcase uint8:\n\t\t\tt = TypeUint8\n\t\tcase int8:\n\t\t\tt = TypeInt8\n\t\tcase uint32:\n\t\t\tt = TypeUint32\n\t\tcase int32:\n\t\t\tt = TypeInt32\n\t\tcase uint64:\n\t\t\tt = TypeUint64\n\t\tcase int64:\n\t\t\tt = TypeInt64\n\t\tcase bool:\n\t\t\tt = TypeBoolean\n\t\tcase string:\n\t\t\tt = TypeString\n\t\tcase float32:\n\t\t\tt = TypeFloat32\n\t\tcase float64:\n\t\t\tt = TypeFloat64\n\t\t}\n\t\ttypeList = append(typeList, t)\n\t}\n\treturn typeList\n}", "func (AllowsMultipleInstanceTypes) Values() []AllowsMultipleInstanceTypes {\n\treturn []AllowsMultipleInstanceTypes{\n\t\t\"on\",\n\t\t\"off\",\n\t}\n}", "func (AthenaResultCompressionType) Values() []AthenaResultCompressionType {\n\treturn []AthenaResultCompressionType{\n\t\t\"GZIP\",\n\t\t\"SNAPPY\",\n\t\t\"ZLIB\",\n\t}\n}", "func (OsType) Values() []OsType {\n\treturn []OsType{\n\t\t\"WINDOWS\",\n\t\t\"LINUX\",\n\t}\n}", "func TaskTypeValues() []TaskType {\n\treturn _TaskTypeValues\n}", "func PossibleTypeValues() []Type {\n\treturn []Type{TypeIntegrationRuntime, TypeManaged, TypeSelfHosted}\n}" ]
[ "0.70301", "0.66016096", "0.65565395", "0.6466942", "0.63187724", "0.6198198", "0.59649175", "0.59599745", "0.5952964", "0.59205806", "0.59042585", "0.58914685", "0.5890263", "0.588717", "0.5848367", "0.5835866", "0.58317244", "0.58302057", "0.5822015", "0.5800212", "0.57824224", "0.5713104", "0.57076156", "0.569992", "0.56899005", "0.5674597", "0.5672697", "0.5666518", "0.56622666", "0.56570053", "0.56518745", "0.56482863", "0.56285083", "0.56246865", "0.56235", "0.5621874", "0.5614864", "0.56094974", "0.5603414", "0.56009287", "0.5590717", "0.55816734", "0.5573579", "0.5571089", "0.5569674", "0.55604184", "0.55604035", "0.5560191", "0.5560158", "0.55584216", "0.55564207", "0.55553323", "0.5555026", "0.55480504", "0.55452645", "0.55443674", "0.55379426", "0.55317134", "0.55203575", "0.55095464", "0.55062157", "0.5501324", "0.54982734", "0.5488222", "0.5487297", "0.5484839", "0.54773813", "0.54591644", "0.54514515", "0.54505885", "0.54497474", "0.5443695", "0.544368", "0.5443476", "0.5443476", "0.5441841", "0.54301673", "0.5423634", "0.54231083", "0.5417656", "0.5416308", "0.5414854", "0.5414632", "0.541169", "0.54113036", "0.5401683", "0.5400965", "0.5400123", "0.5397975", "0.5397281", "0.5395282", "0.53902304", "0.5389947", "0.5366233", "0.5363175", "0.536176", "0.5361397", "0.5356229", "0.53499985", "0.5347643" ]
0.6932683
1
Valid returns if the current type is one of AllTypes
func (t Type) Valid() bool { for _, typ := range AllTypes() { if t == typ { return true } } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t Type) IsValid() bool {\n\tfor _, knownType := range allKnownTypes {\n\t\tif t == knownType {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (t Type) Valid() bool {\n\treturn EvNone < t && t < EvCount\n}", "func (i ImageType) Valid() bool {\n\tswitch string(i) {\n\tcase \"\", \"local\", \"all\":\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (i StorageType) Valid() bool {\n\treturn i > storageTypeUnknown && i < storageTypeSentinel\n}", "func (v ToplistWidgetDefinitionType) IsValid() bool {\n\tfor _, existing := range allowedToplistWidgetDefinitionTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (t Type) Valid() bool {\r\n\treturn t >= CONNECT && t <= DISCONNECT\r\n}", "func (v ReportType) IsValid() bool {\n\tfor _, existing := range allowedReportTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v TableWidgetDefinitionType) IsValid() bool {\n\tfor _, existing := range allowedTableWidgetDefinitionTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (TypesObject) Is(typ string) bool { return boolResult }", "func (v ChangeWidgetDefinitionType) IsValid() bool {\n\tfor _, existing := range allowedChangeWidgetDefinitionTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func ValidType(t Type) bool {\n\treturn StandardType(t) || CustomType(t)\n}", "func (typ Type) HasAll(t Type) bool { return typ&t == t }", "func (i UsersBatchType) Valid() bool {\n\treturn i > UsersBatchTypeUnknown && i < usersBatchTypeSentinel\n}", "func (v LogsUserAgentParserType) IsValid() bool {\n\tfor _, existing := range allowedLogsUserAgentParserTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v TeamPermissionSettingType) IsValid() bool {\n\tfor _, existing := range allowedTeamPermissionSettingTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v SyntheticsTestRequestBodyType) IsValid() bool {\n\tfor _, existing := range allowedSyntheticsTestRequestBodyTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v RestrictionPolicyType) IsValid() bool {\n\tfor _, existing := range allowedRestrictionPolicyTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v IDNumberType) IsValid() bool {\n\tfor _, existing := range allowedIDNumberTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (t Type) Is(ty Type) bool {\n\treturn t&ty != 0\n}", "func (v UserTeamUserType) IsValid() bool {\n\tfor _, existing := range allowedUserTeamUserTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (t Type) IsValid() bool {\n\treturn valid_start < t && t < valid_end\n}", "func (v LogsArithmeticProcessorType) IsValid() bool {\n\tfor _, existing := range allowedLogsArithmeticProcessorTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v LogsArithmeticProcessorType) IsValid() bool {\n\tfor _, existing := range allowedLogsArithmeticProcessorTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v UserStatedIncomeSourcePayType) IsValid() bool {\n\tfor _, existing := range allowedUserStatedIncomeSourcePayTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v SyntheticsBasicAuthOauthROPType) IsValid() bool {\n\tfor _, existing := range allowedSyntheticsBasicAuthOauthROPTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (me Tokens) IsAnyOneOf(any ...string) bool {\n\treturn len(me) == 1 && me[0].IsAnyOneOf(any...)\n}", "func (v LogsMessageRemapperType) IsValid() bool {\n\tfor _, existing := range allowedLogsMessageRemapperTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v ActivityTypeEnum) IsValid() bool {\n\tfor _, existing := range allowedActivityTypeEnumEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (t QuotaType) IsValid() bool {\n\treturn t == HardQuota || t == FIFOQuota\n}", "func (v FormulaTypeEnum) IsValid() bool {\n\tfor _, existing := range AllowedFormulaTypeEnumEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (c TransformIOType) IsValid() bool {\n\tswitch c {\n\tcase TransformIOTypeString, TransformIOTypeBool, TransformIOTypeInt, TransformIOTypeInt64, TransformIOTypeFloat64, TransformIOTypeObject, TransformIOTypeArray:\n\t\treturn true\n\t}\n\treturn false\n}", "func (v LogsComputeType) IsValid() bool {\n\tfor _, existing := range allowedLogsComputeTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func typeIsValid(typ types.Type) bool {\n\t// Check named types separately, because we don't want\n\t// to call Underlying() on them to avoid problems with recursive types.\n\tif _, ok := typ.(*types.Named); ok {\n\t\treturn true\n\t}\n\n\tswitch typ := typ.Underlying().(type) {\n\tcase *types.Basic:\n\t\treturn typ.Kind() != types.Invalid\n\tcase *types.Array:\n\t\treturn typeIsValid(typ.Elem())\n\tcase *types.Slice:\n\t\treturn typeIsValid(typ.Elem())\n\tcase *types.Pointer:\n\t\treturn typeIsValid(typ.Elem())\n\tcase *types.Map:\n\t\treturn typeIsValid(typ.Key()) && typeIsValid(typ.Elem())\n\tcase *types.Chan:\n\t\treturn typeIsValid(typ.Elem())\n\tcase *types.Signature:\n\t\treturn typeIsValid(typ.Params()) && typeIsValid(typ.Results())\n\tcase *types.Tuple:\n\t\tfor i := 0; i < typ.Len(); i++ {\n\t\t\tif !typeIsValid(typ.At(i).Type()) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\tcase *types.Struct, *types.Interface:\n\t\t// Don't bother checking structs, interfaces for validity.\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (v InvestmentTransactionSubtype) IsValid() bool {\n\tfor _, existing := range allowedInvestmentTransactionSubtypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v V1GenomicRegionGenomicRegionType) IsValid() bool {\n\tfor _, existing := range AllowedV1GenomicRegionGenomicRegionTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v WidgetDisplayType) IsValid() bool {\n\tfor _, existing := range allowedWidgetDisplayTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (r ValidationErrors) Any() bool {\n\treturn len(r.Errors) > 0\n}", "func (v TransactionTypeFilter) IsValid() bool {\n\tfor _, existing := range allowedTransactionTypeFilterEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v IncidentAttachmentType) IsValid() bool {\n\tfor _, existing := range allowedIncidentAttachmentTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (kind Kind) IsValid() bool {\n\treturn kind&Invalid == 0\n}", "func (_BaseLibrary *BaseLibraryCaller) ValidType(opts *bind.CallOpts, content_type common.Address) (bool, error) {\n\tvar out []interface{}\n\terr := _BaseLibrary.contract.Call(opts, &out, \"validType\", content_type)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (v TipoEntidade) IsValid() bool {\n\tfor _, existing := range allowedTipoEntidadeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v TransferBalanceType) IsValid() bool {\n\tfor _, existing := range allowedTransferBalanceTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func Is(name string) bool {\n\treturn contains(name, All)\n}", "func (right Access) IsOneOf(rights ...Access) bool {\n\tif len(rights) == 0 {\n\t\treturn false\n\t}\n\tfor _, r := range rights {\n\t\tif right == r {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (s State) IsOneOf(targets ...State) bool {\n\tfor _, target := range targets {\n\t\tif s == target {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (d Definition) IsValid(args ...interface{}) bool {\n\tif d.Inputs == nil {\n\t\treturn true\n\t}\n\tif len(args) != len(d.Inputs) {\n\t\treturn false\n\t}\n\tfor i, a := range args {\n\t\tswitch x := d.Inputs[i].(type) {\n\t\tcase reflect.Type:\n\t\t\txv := reflect.ValueOf(x)\n\t\t\tav := reflect.ValueOf(a)\n\t\t\tif !xv.IsNil() {\n\t\t\t\tif !av.IsValid() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif ak := reflect.TypeOf(a).Kind(); (ak == reflect.Chan || ak == reflect.Func || ak == reflect.Map || ak == reflect.Ptr || ak == reflect.Slice) && av.IsNil() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif !av.Type().AssignableTo(x) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\tcase reflect.Kind:\n\t\t\txv := reflect.ValueOf(x)\n\t\t\tav := reflect.ValueOf(a)\n\t\t\tif xv.IsValid() || !xv.IsNil() {\n\t\t\t\tif !av.IsValid() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif xv.IsValid() && av.Type().Kind() != x {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func (v DeliveryOverrideType) IsValid() bool {\n\tfor _, existing := range AllowedDeliveryOverrideTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v value) Is(t Type) bool {\n\treturn v.typ.Name() == t.Name()\n}", "func allInstance(guard dgo.RecursionGuard, t dgo.Type, vs []dgo.Value) bool {\n\tif t == DefaultAnyType {\n\t\treturn true\n\t}\n\tfor i := range vs {\n\t\tif !Instance(guard, t, vs[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (t UploadType) IsValid() error {\n\tswitch t {\n\tcase UploadTypeAttachment:\n\t\treturn nil\n\tcase UploadTypeImport:\n\t\treturn nil\n\tdefault:\n\t}\n\treturn fmt.Errorf(\"invalid UploadType %s\", t)\n}", "func IsOneOf(s string, all ...string) bool {\n\tfor _, a := range all {\n\t\tif s == a {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) ValidType(opts *bind.CallOpts, content_type common.Address) (bool, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"validType\", content_type)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func allBoolean(typ Type) bool { return allBasic(typ, IsBoolean) }", "func (s *UnionSchema) Validate(v reflect.Value) bool {\n\tv = dereference(v)\n\tfor i := range s.Types {\n\t\tif t := s.Types[i]; t.Validate(v) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (v MetricBulkConfigureTagsType) IsValid() bool {\n\tfor _, existing := range allowedMetricBulkConfigureTagsTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (typ Type) HasAny(t Type) bool { return typ&t != 0 }", "func (v ListTeamsInclude) IsValid() bool {\n\tfor _, existing := range allowedListTeamsIncludeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func IsValidResourceType(resourceType string, allResourceTypes []string) bool {\n\treturn collections.ListContainsElement(allResourceTypes, resourceType)\n}", "func (c PullRequestMergeType) IsValid() bool {\n\treturn c == MergeMerge || c == MergeRebase || c == MergeSquash\n}", "func Valid(name string) bool {\n\tswitch name {\n\tcase Bitmark, Testing, Local:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (i GinBindType) Valid() bool {\n\tfor _, v := range _GinBindTypeValues {\n\t\tif i == v {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (t *TypeGuard) IsSatisfiedBy(n TypeNode) bool {\n\tg, ok := n.(*TypeGuard)\n\tif ok {\n\t\tfor _, i := range t.Types {\n\t\t\tif i == nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor _, j := range g.Types {\n\t\t\t\tif j == nil {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif i.IsSatisfiedBy(j) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor _, i := range t.Types {\n\t\tif i.IsSatisfiedBy(n) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (_BaseContentSpace *BaseContentSpaceCaller) ValidType(opts *bind.CallOpts, content_type common.Address) (bool, error) {\n\tvar out []interface{}\n\terr := _BaseContentSpace.contract.Call(opts, &out, \"validType\", content_type)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (v MetricTagConfigurationMetricTypes) IsValid() bool {\n\tfor _, existing := range allowedMetricTagConfigurationMetricTypesEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v UtilizadorEstados) IsValid() bool {\n\tfor _, existing := range allowedUtilizadorEstadosEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (p *parser) accept(valids []fieldType) bool {\n\tnext := p.next()\n\tfor _, valid := range valids {\n\t\tif next.typ == valid {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v CteraLicense) IsValid() bool {\n\tfor _, existing := range allowedCteraLicenseEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v FunnelSource) IsValid() bool {\n\tfor _, existing := range allowedFunnelSourceEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v DowntimeResourceType) IsValid() bool {\n\tfor _, existing := range allowedDowntimeResourceTypeEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (this MessageType) Valid() bool {\n\treturn this > RESERVED && this < RESERVED2\n}", "func (me TshapeEnumType) IsRectangle() bool { return me == \"rectangle\" }", "func (o *WorkflowCliCommandAllOf) HasType() bool {\n\tif o != nil && o.Type != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (et EventType) Valid() bool {\n\tswitch et {\n\tcase Reopened, Closed, Renamed, Labeled, Unlabeled, CommentDeleted:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (v ViewType) IsOk() bool {\n\tpaw.Logger.Debug(\"checking ViewType...\" + paw.Caller(1))\n\tif _, ok := ViewTypeNames[v]; ok {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func (r Role) Valid() bool {\n\tswitch r {\n\tcase RoleUser:\n\t\tbreak\n\tcase RoleAdmin:\n\t\tbreak\n\tcase RoleSuper:\n\t\tbreak\n\tcase RoleSystem:\n\t\tbreak\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}", "func (_Container *ContainerCaller) ValidType(opts *bind.CallOpts, content_type common.Address) (bool, error) {\n\tvar out []interface{}\n\terr := _Container.contract.Call(opts, &out, \"validType\", content_type)\n\n\tif err != nil {\n\t\treturn *new(bool), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(bool)).(*bool)\n\n\treturn out0, err\n\n}", "func (e *TypeError) Is() bool {\n\treturn e.Obj != nil\n}", "func (ct ContentType) IsValid() error {\n\tswitch ct {\n\tcase Collection, Credential, DIDDocument, Metadata, Connection:\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"invalid content type '%s', supported types are %s\", ct,\n\t\t[]ContentType{Collection, Credential, DIDDocument, Metadata, Connection})\n}", "func (s Set) Is(t Type) bool {\n\treturn s.equals(t, false)\n}", "func (*NamedType) isType() {}", "func (t *HashType) IsValid() bool {\n\t_, valid := validHashes[*t]\n\treturn valid\n}", "func (collection *Collection) Valid() bool {\n\t// Collection must contain at least one GameTree\n\tif len(collection.GameTrees) == 0 {\n\t\treturn false\n\t}\n\n\t// Check GameTrees\n\tfor _, gameTree := range collection.GameTrees {\n\t\tif !validGameTree(gameTree) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (e Enum) IsValid() bool {\n\t_, ok := lookupEnum(e)\n\treturn ok\n}", "func (v ListStreamSource) IsValid() bool {\n\tfor _, existing := range allowedListStreamSourceEnumValues {\n\t\tif existing == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (f Format) Valid() bool {\n\tfor _, valid := range Formats {\n\t\tif valid == f {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (htype HType) Is(other IHType) bool {\n\tht, ok := other.(HType)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn ht.checkValue%htype.checkValue == 0\n}", "func (ExprType) OfKind(kind string) bool { return boolResult }", "func (a *Asset) Valid() bool {\n\tif !filepath.IsAbs(a.path) {\n\t\treturn false\n\t}\n\n\tfor _, at := range AssetTypes() {\n\t\tif at == a.kind {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func IsStorageItemTypeValid(mtype string) bool {\n\tswitch mtype {\n\tcase\n\t\tFuzzer,\n\t\tTarget,\n\t\tCorpus:\n\t\treturn true\n\t}\n\treturn false\n}", "func (g *genExpansion) Filter(c *generator.Context, t *types.Type) bool {\r\n\treturn len(g.types) == 0 || t == g.types[0]\r\n}", "func (f Format) Valid() bool {\n\tswitch f {\n\tcase None:\n\t\tbreak\n\tcase Custom:\n\t\tbreak\n\tcase Zstd:\n\t\tbreak\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}", "func (err ErrAggregate) Is(target error) bool {\n\tfor _, err := range err.errs {\n\t\tif errors.Is(err, target) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (e Event) Is(t EventType) bool {\n\treturn EventType(e.Type) == t\n}", "func (ct ContentType) IsValid() error {\n\tswitch ct {\n\tcase Collection, Credential, DIDResolutionResponse, Metadata, Connection, Key:\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"invalid content type '%s', supported types are %s\", ct,\n\t\t[]ContentType{Collection, Credential, DIDResolutionResponse, Metadata, Connection, Key})\n}", "func (p PaymentType) Validate() bool {\n\tswitch p {\n\tcase CashPaymentType:\n\t\treturn true\n\tcase CheckPaymentType:\n\t\treturn true\n\tcase CreditCardPaymentType:\n\t\treturn true\n\tcase DebitCardPaymentType:\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (ExprType) Is(typ string) bool { return boolResult }", "func (e *multiErr) Is(target error) bool {\n\tfor _, err := range e.errs {\n\t\tif errors.Is(err, target) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (q *Query) isValidTableSelected() (valid bool) {\n\tfor _, value := range queryTypes {\n\n\t\tif value == q.QueryType.String() {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (o *NotificationAccountSubscriptionAllOf) GetTypeOk() (*string, bool) {\n\tif o == nil || o.Type == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Type, true\n}" ]
[ "0.6825694", "0.6371591", "0.62264395", "0.6162184", "0.61585903", "0.61412436", "0.6111977", "0.61091393", "0.6106575", "0.6102013", "0.60669553", "0.6064694", "0.60605884", "0.604936", "0.59423536", "0.59300756", "0.59161454", "0.5910387", "0.5899794", "0.5895834", "0.587668", "0.5869308", "0.5869308", "0.585995", "0.5823086", "0.58185583", "0.5773181", "0.5761973", "0.57592076", "0.57454544", "0.57345086", "0.56990147", "0.5687565", "0.56853104", "0.5661541", "0.56604475", "0.56431985", "0.5643159", "0.5632099", "0.56214565", "0.56139416", "0.5612605", "0.56092966", "0.5605811", "0.55934346", "0.5588458", "0.5587821", "0.5573971", "0.55721474", "0.55620503", "0.5535132", "0.55290115", "0.5528663", "0.55244595", "0.55235946", "0.55213654", "0.55098414", "0.547385", "0.5468564", "0.54674834", "0.5466553", "0.54592407", "0.5458412", "0.54540557", "0.5453583", "0.5452345", "0.54493207", "0.5448125", "0.5442723", "0.5425381", "0.54224646", "0.5422184", "0.5416534", "0.5414525", "0.5396255", "0.53911287", "0.53804535", "0.5378847", "0.5377388", "0.5370415", "0.53636724", "0.5338129", "0.53299797", "0.53256536", "0.5324626", "0.5317454", "0.5290264", "0.5284494", "0.5280644", "0.52797765", "0.5278732", "0.527759", "0.52679956", "0.5267661", "0.52630323", "0.52607435", "0.5258337", "0.52573746", "0.52525973", "0.5251639" ]
0.7091641
0
Equal checks equivalence between resource maps
func (r Resources) Equal(o Resources) bool { Log.Vomit.Printf("Comparing resources: %+ v ?= %+ v", r, o) if len(r) != len(o) { Log.Vomit.Println("Lengths differ") return false } if r.Ports() != o.Ports() { Log.Vomit.Println("Ports differ") return false } if math.Abs(r.Cpus()-o.Cpus()) > 0.001 { Log.Vomit.Println("Cpus differ") return false } if math.Abs(r.Memory()-o.Memory()) > 0.001 { Log.Vomit.Println("Memory differ") return false } return true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ResourcesEqual(a, b map[string]envoy.Resource) bool {\n\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\n\tfor name, resource := range a {\n\t\tif !proto.Equal(resource, b[name]) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func equalMap(a, b map[string]int) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor key, val := range a {\n\t\tif val != b[key] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func TestHashMapEqual(t *T) {\n\t// Degenerate case\n\thm1, hm2 := NewHashMap(), NewHashMap()\n\tassert.Equal(t, true, hm1.Equal(hm2))\n\tassert.Equal(t, true, hm2.Equal(hm1))\n\n\t// False with different sizes\n\thm1, _ = hm1.Set(\"one\", 1)\n\tassert.Equal(t, false, hm1.Equal(hm2))\n\tassert.Equal(t, false, hm2.Equal(hm1))\n\n\t// False with same sizes\n\thm2, _ = hm2.Set(\"two\", 2)\n\tassert.Equal(t, false, hm1.Equal(hm2))\n\tassert.Equal(t, false, hm2.Equal(hm1))\n\n\t// Now true\n\thm1, _ = hm1.Set(\"two\", 2)\n\thm2, _ = hm2.Set(\"one\", 1)\n\tassert.Equal(t, true, hm1.Equal(hm2))\n\tassert.Equal(t, true, hm2.Equal(hm1))\n\n\t// False with embedded HashMap\n\thm1, _ = hm1.Set(NewHashMap().Set(\"three\", 3))\n\tassert.Equal(t, false, hm1.Equal(hm2))\n\tassert.Equal(t, false, hm2.Equal(hm1))\n\n\t// True with embedded set\n\thm2, _ = hm2.Set(NewHashMap().Set(\"three\", 3))\n\tassert.Equal(t, true, hm1.Equal(hm2))\n\tassert.Equal(t, true, hm2.Equal(hm1))\n\n\t// False with same key, different value\n\thm1, _ = hm1.Set(\"four\", 4)\n\thm2, _ = hm2.Set(\"four\", 5)\n\tassert.Equal(t, false, hm1.Equal(hm2))\n\tassert.Equal(t, false, hm2.Equal(hm1))\n}", "func checkTargetMapContainsSourceMap(source, target map[string]interface{}) bool {\n\tfor key, sourceValue := range source {\n\t\ttargetValue, exist := target[key]\n\t\tif !exist && !reflect.DeepEqual(sourceValue, targetValue) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func checkMap(expected, actual map[string]string) bool {\n\tif actual != nil {\n\t\tfor k, v := range expected {\n\t\t\tif actual[k] != v {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\tif expected != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func routerCAConfigMapsEqual(a, b *corev1.ConfigMap) bool {\n\tif a.Data[\"ca-bundle.crt\"] != b.Data[\"ca-bundle.crt\"] {\n\t\treturn false\n\t}\n\treturn true\n}", "func EqualMapInt32StrP(map1, map2 map[int32]string) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func StringMapsEqual(a map[string]string, b map[string]string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor k := range a {\n\t\tif a[k] != b[k] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func checkSmaps(t *testing.T, proxyURL string) {\n\tvar (\n\t\tsmap1 = tutils.GetClusterMap(t, proxyURL)\n\t\tprimary = smap1.Primary // primary according to the `proxyURL`(*)\n\t)\n\tfor _, psi := range smap1.Pmap {\n\t\tsmap2 := tutils.GetClusterMap(t, psi.URL(cmn.NetworkPublic))\n\t\tuuid, sameOrigin, sameVersion, eq := smap1.Compare(smap2)\n\t\tif eq {\n\t\t\tcontinue\n\t\t}\n\t\terr := fmt.Errorf(\"(%s %s, primary=%s) != (%s %s, primary=%s): (uuid=%s, same-orig=%t, same-ver=%t)\",\n\t\t\tproxyURL, smap1, primary, psi.URL(cmn.NetworkPublic), smap2, smap2.Primary, uuid, sameOrigin, sameVersion)\n\t\tt.Error(err)\n\t}\n}", "func same(sMap, cMap map[rune]int) bool {\n\tfor sr, sCount := range sMap {\n\t\tif cCount, ok := cMap[sr]; !ok {\n\t\t\treturn false\n\t\t} else if cCount != sCount {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func EqualMapUint32StrP(map1, map2 map[uint32]string) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt32Uint8P(map1, map2 map[int32]uint8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (m *Map) Equal(other *Map) bool {\n\tif m != nil && other != nil {\n\t\treturn m.URI == other.URI && m.Byterange.Equal(other.Byterange)\n\t}\n\n\treturn m == other\n}", "func compareMaps(t *testing.T, a, b map[string]string) {\n\tif len(a) != len(b) {\n\t\tt.Error(\"Maps different sizes\", a, b)\n\t}\n\tfor ka, va := range a {\n\t\tif vb, ok := b[ka]; !ok || va != vb {\n\t\t\tt.Error(\"Difference in key\", ka, va, b[ka])\n\t\t}\n\t}\n\tfor kb, vb := range b {\n\t\tif va, ok := a[kb]; !ok || vb != va {\n\t\t\tt.Error(\"Difference in key\", kb, vb, a[kb])\n\t\t}\n\t}\n}", "func EqualMapInt32Int8P(map1, map2 map[int32]int8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func verifyObjStringMap(actual attribute.StringMap, expected map[string]interface{}) error {\n\tfor k, v := range expected {\n\t\tvstring := v.(string)\n\t\t// \"-\" make sure the key does not exist.\n\t\tif vstring == \"-\" {\n\t\t\tif _, ok := actual.Get(k); ok {\n\t\t\t\treturn fmt.Errorf(\"key %+v is NOT expected\", k)\n\t\t\t}\n\t\t} else {\n\t\t\tif val, ok := actual.Get(k); ok {\n\t\t\t\t// \"*\" only check key exist\n\t\t\t\tif val != vstring && vstring != \"*\" {\n\t\t\t\t\treturn fmt.Errorf(\"key %+v value doesn't match. Actual %+v, expected %+v\",\n\t\t\t\t\t\tk, val, vstring)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"key %+v is expected\", k)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func EqualMapInt8StrP(map1, map2 map[int8]string) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (m Mapping) equal(other Node) bool {\n\to, ok := other.(Mapping)\n\tif !ok || len(m.pairs) != len(o.pairs) || m.path != o.path {\n\t\treturn false\n\t}\n\tif m.pairs == nil || o.pairs == nil {\n\t\treturn m.pairs == nil && o.pairs == nil\n\t}\n\tfor k, v := range o.pairs {\n\t\tif !equal(m.pairs[k], v) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (resource *ResourceType) Equals(other Type, override EqualityOverrides) bool {\n\tif resource == other {\n\t\t// Same reference\n\t\treturn true\n\t}\n\n\totherResource, ok := other.(*ResourceType)\n\tif !ok {\n\t\treturn false\n\t}\n\n\t// Do cheap tests earlier\n\tif resource.isStorageVersion != otherResource.isStorageVersion ||\n\t\tlen(resource.testcases) != len(otherResource.testcases) ||\n\t\tlen(resource.functions) != len(otherResource.functions) ||\n\t\t!TypeEquals(resource.spec, otherResource.spec, override) ||\n\t\t!TypeEquals(resource.status, otherResource.status, override) ||\n\t\tlen(resource.annotations) != len(otherResource.annotations) ||\n\t\tresource.scope != otherResource.scope ||\n\t\tresource.armType != otherResource.armType ||\n\t\t!TypeEquals(resource.apiVersionTypeName, otherResource.apiVersionTypeName) ||\n\t\t!resource.apiVersionEnumValue.Equals(&otherResource.apiVersionEnumValue) ||\n\t\t!resource.InterfaceImplementer.Equals(otherResource.InterfaceImplementer, override) {\n\t\treturn false\n\t}\n\n\t// Check same functions present\n\tfor name, fn := range otherResource.functions {\n\t\tourFn, ok := resource.functions[name]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\tif !ourFn.Equals(fn, override) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Check same test cases present\n\tfor name, testcase := range otherResource.testcases {\n\t\tourCase, ok := resource.testcases[name]\n\t\tif !ok {\n\t\t\t// Didn't find the func, not equal\n\t\t\treturn false\n\t\t}\n\n\t\tif !ourCase.Equals(testcase, override) {\n\t\t\t// Different testcase, even though same name; not-equal\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Check same annotations present in the same order\n\tfor i, ourAnnotation := range resource.annotations {\n\t\totherAnnotation := otherResource.annotations[i]\n\t\tif ourAnnotation != otherAnnotation {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func EqualMapUint32Int8P(map1, map2 map[uint32]int8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func AssertEqualStringMap(expected map[string]string, result map[string]string) {\n\tAssertType(expected, result)\n\tif expected == nil && result == nil {\n\t\treturn\n\t}\n\tif len(expected) != len(result) {\n\t\tpanic(fmt.Sprintf(\"Error: [] Different count of items\\nExpected Value: %v\\nResult: %v\", expected, result))\n\t}\n\tfor expectedKey := range expected {\n\t\tif result[expectedKey] != expected[expectedKey] {\n\t\t\tpanic(fmt.Sprintf(\"Error: [] Item missing: %v.\\nExpected Value: %v\\nResult: %v\", expected[expectedKey], expected, result))\n\t\t}\n\t}\n}", "func EqualMapStrInt32P(map1, map2 map[string]int32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUint32P(map1, map2 map[uint32]uint32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt8Uint32P(map1, map2 map[int8]uint32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func compareMaps(info string, a, b map[int]bool) {\n\tif len(a) != len(b) {\n\t\tpanic(errors.Bug(\"%s - a.len:%d != b.len:%d\", info, len(a), len(b)))\n\t}\n\tfor k, v := range a {\n\t\tif _, ok := b[k]; !ok {\n\t\t\tpanic(fmt.Sprintf(\"%s - k:%d (%t)\\n\", info, k, v))\n\t\t}\n\t}\n}", "func EqualMapInt8P(map1, map2 map[int8]int8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func diffUrlMap(c *Client, desired, actual *UrlMap, opts ...dcl.ApplyOption) ([]urlMapDiff, error) {\n\tif desired == nil || actual == nil {\n\t\treturn nil, fmt.Errorf(\"nil resource passed to diff - always a programming error: %#v, %#v\", desired, actual)\n\t}\n\n\tvar diffs []urlMapDiff\n\tif compareUrlMapDefaultRouteAction(c, desired.DefaultRouteAction, actual.DefaultRouteAction) {\n\t\tc.Config.Logger.Infof(\"Detected diff in DefaultRouteAction.\\nDESIRED: %v\\nACTUAL: %v\", desired.DefaultRouteAction, actual.DefaultRouteAction)\n\n\t\tdiffs = append(diffs, urlMapDiff{\n\t\t\tUpdateOp: &updateUrlMapUpdateOperation{},\n\t\t\tFieldName: \"DefaultRouteAction\",\n\t\t})\n\n\t}\n\tif !dcl.IsZeroValue(desired.DefaultService) && !dcl.StringCanonicalize(desired.DefaultService, actual.DefaultService) {\n\t\tc.Config.Logger.Infof(\"Detected diff in DefaultService.\\nDESIRED: %v\\nACTUAL: %v\", desired.DefaultService, actual.DefaultService)\n\n\t\tdiffs = append(diffs, urlMapDiff{\n\t\t\tUpdateOp: &updateUrlMapUpdateOperation{},\n\t\t\tFieldName: \"DefaultService\",\n\t\t})\n\n\t}\n\tif compareUrlMapDefaultUrlRedirect(c, desired.DefaultUrlRedirect, actual.DefaultUrlRedirect) {\n\t\tc.Config.Logger.Infof(\"Detected diff in DefaultUrlRedirect.\\nDESIRED: %v\\nACTUAL: %v\", desired.DefaultUrlRedirect, actual.DefaultUrlRedirect)\n\n\t\tdiffs = append(diffs, urlMapDiff{\n\t\t\tUpdateOp: &updateUrlMapUpdateOperation{},\n\t\t\tFieldName: \"DefaultUrlRedirect\",\n\t\t})\n\n\t}\n\tif !dcl.IsZeroValue(desired.Description) && !dcl.StringCanonicalize(desired.Description, actual.Description) {\n\t\tc.Config.Logger.Infof(\"Detected diff in Description.\\nDESIRED: %v\\nACTUAL: %v\", desired.Description, actual.Description)\n\n\t\tdiffs = append(diffs, urlMapDiff{\n\t\t\tUpdateOp: &updateUrlMapUpdateOperation{},\n\t\t\tFieldName: \"Description\",\n\t\t})\n\n\t}\n\tif compareUrlMapHeaderAction(c, desired.HeaderAction, actual.HeaderAction) {\n\t\tc.Config.Logger.Infof(\"Detected diff in HeaderAction.\\nDESIRED: %v\\nACTUAL: %v\", desired.HeaderAction, actual.HeaderAction)\n\n\t\tdiffs = append(diffs, urlMapDiff{\n\t\t\tUpdateOp: &updateUrlMapUpdateOperation{},\n\t\t\tFieldName: \"HeaderAction\",\n\t\t})\n\n\t}\n\tif compareUrlMapHostRuleSlice(c, desired.HostRule, actual.HostRule) {\n\t\tc.Config.Logger.Infof(\"Detected diff in HostRule.\\nDESIRED: %v\\nACTUAL: %v\", desired.HostRule, actual.HostRule)\n\n\t\ttoAdd, toRemove := compareUrlMapHostRuleSets(c, desired.HostRule, actual.HostRule)\n\t\tc.Config.Logger.Infof(\"diff in HostRule is a set field - recomparing with set logic. \\nto add: %#v\\nto remove: %#v\", toAdd, toRemove)\n\t\tif len(toAdd) != 0 || len(toRemove) != 0 {\n\t\t\tc.Config.Logger.Info(\"diff in HostRule persists after set logic analysis.\")\n\t\t\tdiffs = append(diffs, urlMapDiff{\n\t\t\t\tUpdateOp: &updateUrlMapUpdateOperation{},\n\t\t\t\tFieldName: \"HostRule\",\n\t\t\t})\n\t\t}\n\n\t}\n\tif !dcl.IsZeroValue(desired.Name) && !dcl.StringCanonicalize(desired.Name, actual.Name) {\n\t\tc.Config.Logger.Infof(\"Detected diff in Name.\\nDESIRED: %v\\nACTUAL: %v\", desired.Name, actual.Name)\n\n\t\tdiffs = append(diffs, urlMapDiff{\n\t\t\tUpdateOp: &updateUrlMapUpdateOperation{},\n\t\t\tFieldName: \"Name\",\n\t\t})\n\n\t}\n\tif compareUrlMapPathMatcherSlice(c, desired.PathMatcher, actual.PathMatcher) {\n\t\tc.Config.Logger.Infof(\"Detected diff in PathMatcher.\\nDESIRED: %v\\nACTUAL: %v\", desired.PathMatcher, actual.PathMatcher)\n\n\t\ttoAdd, toRemove := compareUrlMapPathMatcherSets(c, desired.PathMatcher, actual.PathMatcher)\n\t\tc.Config.Logger.Infof(\"diff in PathMatcher is a set field - recomparing with set logic. \\nto add: %#v\\nto remove: %#v\", toAdd, toRemove)\n\t\tif len(toAdd) != 0 || len(toRemove) != 0 {\n\t\t\tc.Config.Logger.Info(\"diff in PathMatcher persists after set logic analysis.\")\n\t\t\tdiffs = append(diffs, urlMapDiff{\n\t\t\t\tUpdateOp: &updateUrlMapUpdateOperation{},\n\t\t\t\tFieldName: \"PathMatcher\",\n\t\t\t})\n\t\t}\n\n\t}\n\tif !dcl.IsZeroValue(desired.Region) && !dcl.StringCanonicalize(desired.Region, actual.Region) {\n\t\tc.Config.Logger.Infof(\"Detected diff in Region.\\nDESIRED: %v\\nACTUAL: %v\", desired.Region, actual.Region)\n\t\tdiffs = append(diffs, urlMapDiff{\n\t\t\tRequiresRecreate: true,\n\t\t\tFieldName: \"Region\",\n\t\t})\n\t}\n\tif compareUrlMapTestSlice(c, desired.Test, actual.Test) {\n\t\tc.Config.Logger.Infof(\"Detected diff in Test.\\nDESIRED: %v\\nACTUAL: %v\", desired.Test, actual.Test)\n\n\t\tdiffs = append(diffs, urlMapDiff{\n\t\t\tUpdateOp: &updateUrlMapUpdateOperation{},\n\t\t\tFieldName: \"Test\",\n\t\t})\n\n\t}\n\t// We need to ensure that this list does not contain identical operations *most of the time*.\n\t// There may be some cases where we will need multiple copies of the same operation - for instance,\n\t// if a resource has multiple prerequisite-containing fields. For now, we don't know of any\n\t// such examples and so we deduplicate unconditionally.\n\n\t// The best way for us to do this is to iterate through the list\n\t// and remove any copies of operations which are identical to a previous operation.\n\t// This is O(n^2) in the number of operations, but n will always be very small,\n\t// even 10 would be an extremely high number.\n\tvar opTypes []string\n\tvar deduped []urlMapDiff\n\tfor _, d := range diffs {\n\t\t// Two operations are considered identical if they have the same type.\n\t\t// The type of an operation is derived from the name of the update method.\n\t\tif !dcl.StringSliceContains(fmt.Sprintf(\"%T\", d.UpdateOp), opTypes) {\n\t\t\tdeduped = append(deduped, d)\n\t\t\topTypes = append(opTypes, fmt.Sprintf(\"%T\", d.UpdateOp))\n\t\t} else {\n\t\t\tc.Config.Logger.Infof(\"Omitting planned operation of type %T since once is already scheduled.\", d.UpdateOp)\n\t\t}\n\t}\n\n\treturn deduped, nil\n}", "func EqualMapInt16Int8P(map1, map2 map[int16]int8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func AssertConfigMapEntryEquals(t *testing.T, resource *corev1.ConfigMap, key string, expected string, kindMessage string) string {\n\trequire.NotNil(t, resource, \"ConfigMap is nil for %s\", kindMessage)\n\tname := resource.Name\n\trequire.NotEmpty(t, resource.Data, \"Data is empty in ConfigMap %s for %s\", name, kindMessage)\n\n\tvalue := resource.Data[key]\n\tassert.Equal(t, expected, value, \"ConfigMap %s key %s for %s\", name, key, kindMessage)\n\tt.Logf(\"ConfigMap %s has key %s=%s for %s\", name, key, value, kindMessage)\n\treturn value\n}", "func EqualMapInt8Int32P(map1, map2 map[int8]int32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (rs *ResourceCollection) checkMap() {\n\tif rs.resources == nil {\n\t\trs.resources = make(map[string]Resource)\n\t}\n}", "func EqualMapUint8Int32P(map1, map2 map[uint8]int32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUint32Uint8P(map1, map2 map[uint32]uint8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt32P(map1, map2 map[int32]int32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt32UintP(map1, map2 map[int32]uint) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func compareDefaultIDSetMaps(x, y *DefaultIDSetMap) bool {\n\tif x == nil && y == nil {\n\t\treturn true\n\t}\n\n\tif x == nil || y == nil {\n\t\treturn false\n\t}\n\n\tm1 := toMap(x)\n\tm2 := toMap(y)\n\n\tif len(m1) != len(m2) {\n\t\treturn false\n\t}\n\n\tfor k, v := range m1 {\n\t\tif !compareIDSets(v, m2[k]) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func EqualMapInt16Int32P(map1, map2 map[int16]int32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt32Int16P(map1, map2 map[int32]int16) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapIntInt8P(map1, map2 map[int]int8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt8Int16P(map1, map2 map[int8]int16) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (m1 Map) Equal(m2 Map) bool {\n\tif len(m1) != len(m2) {\n\t\treturn false\n\t}\n\n\tfor k, v := range m1 {\n\t\tif w, ok := m2[k]; !ok || v != w {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func EqualMapStrUint32P(map1, map2 map[string]uint32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapStrInt8P(map1, map2 map[string]int8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt32Uint32P(map1, map2 map[int32]uint32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUintInt32P(map1, map2 map[uint]int32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUint32Int32P(map1, map2 map[uint32]int32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt8IntP(map1, map2 map[int8]int) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func CompareAllocatableResources(expected, got map[string]corev1.ResourceList) (string, string, int, bool) {\n\tif len(got) != len(expected) {\n\t\tframework.Logf(\"-> expected=%v (len=%d) got=%v (len=%d)\", expected, len(expected), got, len(got))\n\t\treturn \"\", \"\", 0, false\n\t}\n\tfor expZoneName, expResList := range expected {\n\t\tgotResList, ok := got[expZoneName]\n\t\tif !ok {\n\t\t\treturn expZoneName, \"\", 0, false\n\t\t}\n\t\tif resName, cmp, ok := CompareResourceList(expResList, gotResList); !ok || cmp != 0 {\n\t\t\treturn expZoneName, resName, cmp, ok\n\t\t}\n\t}\n\treturn \"\", \"\", 0, true\n}", "func sameAPI(apiA, apiB map[string]interface{}) bool {\n\tif len(apiA) != len(apiB) {\n\t\treturn false\n\t}\n\tfor field, valueA := range apiA {\n\t\tvalueB, inB := apiB[field]\n\t\tif !(inB && reflect.DeepEqual(valueA, valueB) || field == \"etag\" || field == \"revision\") {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapIntUint32P(map1, map2 map[int]uint32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func mergeResourceTags(one map[string]string, two map[string]*string) (map[string]*string, bool) {\n\tmergedResourceTags := map[string]*string{}\n\t// \"Copy\" two into a new map.\n\tfor key, value := range two {\n\t\tmergedResourceTags[key] = to.Ptr(*value)\n\t}\n\tchanged := false\n\t// Merge \"one\" into the new map, setting changed if we had to make a modification,\n\t// this is for determining whether we needed to make an update to the existing tags.\n\tfor key, value := range one {\n\t\tval, ok := mergedResourceTags[key]\n\t\tif !ok || *val != value {\n\t\t\tmergedResourceTags[key] = to.Ptr(value)\n\t\t\tchanged = true\n\t\t}\n\t}\n\treturn mergedResourceTags, changed\n}", "func (s *StorageSuite) TestServersEquality(c *check.C) {\n\tservers := Servers{{\n\t\tAdvertiseIP: \"192.168.1.1\",\n\t\tHostname: \"node-1\",\n\t\tRole: \"worker\",\n\t}}\n\ttestCases := []struct {\n\t\tservers Servers\n\t\tresult bool\n\t\tcomment string\n\t}{\n\t\t{\n\t\t\tservers: Servers{{\n\t\t\t\tAdvertiseIP: \"192.168.1.1\",\n\t\t\t\tHostname: \"node-1\",\n\t\t\t\tRole: \"worker\",\n\t\t\t}},\n\t\t\tresult: true,\n\t\t\tcomment: \"Servers should be equal\",\n\t\t},\n\t\t{\n\t\t\tservers: Servers{\n\t\t\t\t{\n\t\t\t\t\tAdvertiseIP: \"192.168.1.1\",\n\t\t\t\t\tHostname: \"node-1\",\n\t\t\t\t\tRole: \"worker\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAdvertiseIP: \"192.168.1.2\",\n\t\t\t\t\tHostname: \"node-2\",\n\t\t\t\t\tRole: \"worker\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tresult: false,\n\t\t\tcomment: \"Servers should not be equal: different number of servers\",\n\t\t},\n\t\t{\n\t\t\tservers: Servers{{\n\t\t\t\tAdvertiseIP: \"192.168.1.2\",\n\t\t\t\tHostname: \"node-1\",\n\t\t\t\tRole: \"worker\",\n\t\t\t}},\n\t\t\tresult: false,\n\t\t\tcomment: \"Servers should not be equal: different IPs\",\n\t\t},\n\t\t{\n\t\t\tservers: Servers{{\n\t\t\t\tAdvertiseIP: \"192.168.1.1\",\n\t\t\t\tHostname: \"node-2\",\n\t\t\t\tRole: \"worker\",\n\t\t\t}},\n\t\t\tresult: false,\n\t\t\tcomment: \"Servers should not be equal: different hostnames\",\n\t\t},\n\t\t{\n\t\t\tservers: Servers{{\n\t\t\t\tAdvertiseIP: \"192.168.1.1\",\n\t\t\t\tHostname: \"node-1\",\n\t\t\t\tRole: \"db\",\n\t\t\t}},\n\t\t\tresult: false,\n\t\t\tcomment: \"Servers should not be equal: different roles\",\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tc.Assert(servers.IsEqualTo(tc.servers), check.Equals, tc.result,\n\t\t\tcheck.Commentf(tc.comment))\n\t}\n}", "func EqualMapUint32Int16P(map1, map2 map[uint32]int16) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapIntStrP(map1, map2 map[int]string) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equalValueForKey(findKey string, map1, map2 *goyaml.Node) bool {\n\tif map1.Kind != goyaml.MappingNode || map2.Kind != goyaml.MappingNode {\n\t\treturn false\n\t}\n\n\tif val1, index1 := findValInMap(findKey, map1); index1 != -1 {\n\t\tif val2, index2 := findValInMap(findKey, map2); index2 != -1 {\n\t\t\treturn deepEqual(val1, val2)\n\t\t}\n\t}\n\treturn false\n}", "func EqualMapInt16StrP(map1, map2 map[int16]string) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func mapEqual(a, b map[interface{}]interface{}) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor akey, avalue := range a {\n\t\tfound := false\n\t\tfor bkey, bvalue := range b {\n\t\t\tif DeepEqual(akey, bkey) {\n\t\t\t\tif !DeepEqual(avalue, bvalue) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUint32IntP(map1, map2 map[uint32]int) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt8UintP(map1, map2 map[int8]uint) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func MapsEqual(a, b map[string]string) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\t// Since they are the same size we only need to check from one side, i.e.\n\t// compare a's values to b's values.\n\tfor k, v := range a {\n\t\tif bv, ok := b[k]; !ok || bv != v {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUint8Uint32P(map1, map2 map[uint8]uint32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapIntUint8P(map1, map2 map[int]uint8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt16Uint32P(map1, map2 map[int16]uint32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt32Uint16P(map1, map2 map[int32]uint16) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt16Uint8P(map1, map2 map[int16]uint8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUint16Int32P(map1, map2 map[uint16]int32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func resourceVersionsMatch(o1 interface{}, o2 interface{}) bool {\n\tr1, ok1 := o1.(metav1.Object)\n\tr2, ok2 := o2.(metav1.Object)\n\tif !ok1 || !ok2 {\n\t\tmsg := fmt.Sprintf(\"error decoding kube objects during update, o1 type: %v, o2 type: %v\",\n\t\t\treflect.TypeOf(o1),\n\t\t\treflect.TypeOf(o2))\n\t\tlog.Scope.Error(msg)\n\t\tstats.RecordEventError(msg)\n\t\treturn false\n\t}\n\treturn r1.GetResourceVersion() == r2.GetResourceVersion()\n}", "func EqualMapUint8P(map1, map2 map[uint8]uint8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapIntInt32P(map1, map2 map[int]int32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUint8StrP(map1, map2 map[uint8]string) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUint8IntP(map1, map2 map[uint8]int) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUintInt8P(map1, map2 map[uint]int8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt8Uint16P(map1, map2 map[int8]uint16) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUint32UintP(map1, map2 map[uint32]uint) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapIntInt16P(map1, map2 map[int]int16) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt16P(map1, map2 map[int16]int16) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func mapsEqual(a, b reflect.Value) bool {\n\tif a.Len() != b.Len() {\n\t\treturn false\n\t}\n\tif a.Len() == 0 && b.Len() == 0 {\n\t\t// Optimize the case where maps are frequently empty\n\t\treturn true\n\t}\n\n\titer := a.MapRange()\n\tfor iter.Next() {\n\t\tk := iter.Key()\n\t\tav := iter.Value()\n\t\tbv := b.MapIndex(k)\n\t\tif !bv.IsValid() {\n\t\t\treturn false\n\t\t}\n\t\tif !fieldsEqual(av.Interface(), bv.Interface()) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func newResourceDelta(\n\ta *resource,\n\tb *resource,\n) *ackcompare.Delta {\n\tdelta := ackcompare.NewDelta()\n\tif (a == nil && b != nil) ||\n\t\t(a != nil && b == nil) {\n\t\tdelta.Add(\"\", a, b)\n\t\treturn delta\n\t}\n\n\tif ackcompare.HasNilDifference(a.ko.Spec.Constraints, b.ko.Spec.Constraints) {\n\t\tdelta.Add(\"Spec.Constraints\", a.ko.Spec.Constraints, b.ko.Spec.Constraints)\n\t} else if a.ko.Spec.Constraints != nil && b.ko.Spec.Constraints != nil {\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.Constraints.EncryptionContextEquals, b.ko.Spec.Constraints.EncryptionContextEquals) {\n\t\t\tdelta.Add(\"Spec.Constraints.EncryptionContextEquals\", a.ko.Spec.Constraints.EncryptionContextEquals, b.ko.Spec.Constraints.EncryptionContextEquals)\n\t\t} else if a.ko.Spec.Constraints.EncryptionContextEquals != nil && b.ko.Spec.Constraints.EncryptionContextEquals != nil {\n\t\t\tif !ackcompare.MapStringStringPEqual(a.ko.Spec.Constraints.EncryptionContextEquals, b.ko.Spec.Constraints.EncryptionContextEquals) {\n\t\t\t\tdelta.Add(\"Spec.Constraints.EncryptionContextEquals\", a.ko.Spec.Constraints.EncryptionContextEquals, b.ko.Spec.Constraints.EncryptionContextEquals)\n\t\t\t}\n\t\t}\n\t\tif ackcompare.HasNilDifference(a.ko.Spec.Constraints.EncryptionContextSubset, b.ko.Spec.Constraints.EncryptionContextSubset) {\n\t\t\tdelta.Add(\"Spec.Constraints.EncryptionContextSubset\", a.ko.Spec.Constraints.EncryptionContextSubset, b.ko.Spec.Constraints.EncryptionContextSubset)\n\t\t} else if a.ko.Spec.Constraints.EncryptionContextSubset != nil && b.ko.Spec.Constraints.EncryptionContextSubset != nil {\n\t\t\tif !ackcompare.MapStringStringPEqual(a.ko.Spec.Constraints.EncryptionContextSubset, b.ko.Spec.Constraints.EncryptionContextSubset) {\n\t\t\t\tdelta.Add(\"Spec.Constraints.EncryptionContextSubset\", a.ko.Spec.Constraints.EncryptionContextSubset, b.ko.Spec.Constraints.EncryptionContextSubset)\n\t\t\t}\n\t\t}\n\t}\n\tif !ackcompare.SliceStringPEqual(a.ko.Spec.GrantTokens, b.ko.Spec.GrantTokens) {\n\t\tdelta.Add(\"Spec.GrantTokens\", a.ko.Spec.GrantTokens, b.ko.Spec.GrantTokens)\n\t}\n\tif ackcompare.HasNilDifference(a.ko.Spec.GranteePrincipal, b.ko.Spec.GranteePrincipal) {\n\t\tdelta.Add(\"Spec.GranteePrincipal\", a.ko.Spec.GranteePrincipal, b.ko.Spec.GranteePrincipal)\n\t} else if a.ko.Spec.GranteePrincipal != nil && b.ko.Spec.GranteePrincipal != nil {\n\t\tif *a.ko.Spec.GranteePrincipal != *b.ko.Spec.GranteePrincipal {\n\t\t\tdelta.Add(\"Spec.GranteePrincipal\", a.ko.Spec.GranteePrincipal, b.ko.Spec.GranteePrincipal)\n\t\t}\n\t}\n\tif ackcompare.HasNilDifference(a.ko.Spec.KeyID, b.ko.Spec.KeyID) {\n\t\tdelta.Add(\"Spec.KeyID\", a.ko.Spec.KeyID, b.ko.Spec.KeyID)\n\t} else if a.ko.Spec.KeyID != nil && b.ko.Spec.KeyID != nil {\n\t\tif *a.ko.Spec.KeyID != *b.ko.Spec.KeyID {\n\t\t\tdelta.Add(\"Spec.KeyID\", a.ko.Spec.KeyID, b.ko.Spec.KeyID)\n\t\t}\n\t}\n\tif ackcompare.HasNilDifference(a.ko.Spec.Name, b.ko.Spec.Name) {\n\t\tdelta.Add(\"Spec.Name\", a.ko.Spec.Name, b.ko.Spec.Name)\n\t} else if a.ko.Spec.Name != nil && b.ko.Spec.Name != nil {\n\t\tif *a.ko.Spec.Name != *b.ko.Spec.Name {\n\t\t\tdelta.Add(\"Spec.Name\", a.ko.Spec.Name, b.ko.Spec.Name)\n\t\t}\n\t}\n\tif !ackcompare.SliceStringPEqual(a.ko.Spec.Operations, b.ko.Spec.Operations) {\n\t\tdelta.Add(\"Spec.Operations\", a.ko.Spec.Operations, b.ko.Spec.Operations)\n\t}\n\tif ackcompare.HasNilDifference(a.ko.Spec.RetiringPrincipal, b.ko.Spec.RetiringPrincipal) {\n\t\tdelta.Add(\"Spec.RetiringPrincipal\", a.ko.Spec.RetiringPrincipal, b.ko.Spec.RetiringPrincipal)\n\t} else if a.ko.Spec.RetiringPrincipal != nil && b.ko.Spec.RetiringPrincipal != nil {\n\t\tif *a.ko.Spec.RetiringPrincipal != *b.ko.Spec.RetiringPrincipal {\n\t\t\tdelta.Add(\"Spec.RetiringPrincipal\", a.ko.Spec.RetiringPrincipal, b.ko.Spec.RetiringPrincipal)\n\t\t}\n\t}\n\n\treturn delta\n}", "func (rm fakeRESTMapper) Equal(other fakeRESTMapper) bool {\n\treturn cmp.Equal(rm.defaultGroupVersions, other.defaultGroupVersions)\n}", "func same(x, y []string) bool {\n\txMap := make(map[string]int)\n\tyMap := make(map[string]int)\n\n\tfor _, xElem := range x {\n\t\txMap[xElem]++\n\t}\n\tfor _, yElem := range y {\n\t\tyMap[yElem]++\n\t}\n\n\tfor xMapKey, xMapVal := range xMap {\n\t\tif yMap[xMapKey] != xMapVal {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUint16Int8P(map1, map2 map[uint16]int8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func compareTeamMaps(a, b Teams) bool {\n\tfor teamIndex, team := range a.Teams {\n\t\tif team.Name != b.Teams[teamIndex].Name {\n\t\t\treturn false\n\t\t}\n\t\tfor acctIndex, acct := range team.Accounts {\n\t\t\tif acct != b.Teams[teamIndex].Accounts[acctIndex] {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func EqualMapUint8Int16P(map1, map2 map[uint8]int16) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func shouldResembleByteMap(actual interface{}, expected ...interface{}) string {\n\tact, ok := actual.(map[string]*bytes.Buffer)\n\tif !ok {\n\t\treturn \"actual is not a map[string]*bytes.Buffer\"\n\t}\n\tif len(expected) != 1 {\n\t\treturn \"expected is not a map[string][]byte\"\n\t}\n\texp, ok := expected[0].(map[string][]byte)\n\tif !ok {\n\t\treturn \"expected is not a map[string][]byte\"\n\t}\n\n\tif len(act) != len(exp) {\n\t\treturn fmt.Sprintf(\"len(actual) != len(expected): %v != %v\", len(act), len(exp))\n\t}\n\n\tfor k, v := range act {\n\t\tif got, want := v.Bytes(), exp[k]; !reflect.DeepEqual(got, want) {\n\t\t\treturn fmt.Sprintf(\"actual[%q] != expected[%q]: %q != %q\", k, k, got, want)\n\t\t}\n\t}\n\treturn \"\"\n}", "func EqualMapInt32IntP(map1, map2 map[int32]int) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt16IntP(map1, map2 map[int16]int) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUintUint32P(map1, map2 map[uint]uint32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt32Uint64P(map1, map2 map[int32]uint64) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapStrIntP(map1, map2 map[string]int) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapIntP(map1, map2 map[int]int) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func TestCopyVMInSyncMap(t *testing.T) {\n\tvar vmOriginal *compute.VirtualMachine = &compute.VirtualMachine{\n\t\tVirtualMachineProperties: &compute.VirtualMachineProperties{\n\t\t\tProvisioningState: pointer.String(\"Failed\"),\n\t\t},\n\t\tName: pointer.String(\"vmOriginal\"),\n\t}\n\tvmCacheOriginal := &sync.Map{}\n\tvmCacheOriginal.Store(\"vmOriginal\", vmOriginal)\n\tvmCacheCopied := Copy(vmCacheOriginal).(*sync.Map)\n\n\tpsOriginal := vmOriginal.VirtualMachineProperties.ProvisioningState\n\tvCopied, ok := vmCacheCopied.Load(\"vmOriginal\")\n\tassert.True(t, ok)\n\tvmCopied := vCopied.(*compute.VirtualMachine)\n\tpsCopied := vmCopied.VirtualMachineProperties.ProvisioningState\n\tassert.Equal(t, psOriginal, psCopied)\n\tassert.Equal(t, vmOriginal.Name, vmCopied.Name)\n}", "func EqualMapInt64Int8P(map1, map2 map[int64]int8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (m *NamespaceMapper) checkMapUniqueness() bool {\n\tvar labelSelector = labels.Set(map[string]string{liqoconst.RemoteClusterID: m.foreignClusterID}).AsSelector()\n\tret, err := m.lister.ByNamespace(m.namespace).List(labelSelector)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif len(ret) > 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func EqualMapStrP(map1, map2 map[string]string) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUint64Int32P(map1, map2 map[uint64]int32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt8Uint64P(map1, map2 map[int8]uint64) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapUint32Int64P(map1, map2 map[uint32]int64) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt64Uint32P(map1, map2 map[int64]uint32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapStrInt16P(map1, map2 map[string]int16) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt64Uint8P(map1, map2 map[int64]uint8) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}" ]
[ "0.7206958", "0.6497191", "0.6308787", "0.6244144", "0.62131625", "0.60163283", "0.5997516", "0.5974839", "0.5958248", "0.5903059", "0.5891591", "0.58830553", "0.5866854", "0.5864131", "0.58572376", "0.5854044", "0.5850056", "0.58350617", "0.5830254", "0.58179975", "0.5817369", "0.58118576", "0.58090955", "0.5804974", "0.5804741", "0.5797625", "0.57973707", "0.57934844", "0.57885325", "0.5784557", "0.5775343", "0.5774848", "0.57522154", "0.5749232", "0.57471323", "0.57468635", "0.5746104", "0.57424086", "0.573553", "0.57306373", "0.572732", "0.57095647", "0.5705392", "0.5699976", "0.56814086", "0.5680513", "0.5680439", "0.5680364", "0.56765735", "0.5668591", "0.5668353", "0.5666264", "0.56579167", "0.56567246", "0.56561977", "0.56529605", "0.56482285", "0.5643094", "0.5638297", "0.5635837", "0.5632568", "0.5629691", "0.56279314", "0.5622459", "0.5617815", "0.561727", "0.5616667", "0.5611739", "0.5606332", "0.55840886", "0.55805147", "0.55771416", "0.55722666", "0.557014", "0.55696213", "0.55647767", "0.5562996", "0.55569655", "0.5553769", "0.5553301", "0.55507463", "0.55480367", "0.5547529", "0.5546656", "0.5542607", "0.5536285", "0.55334806", "0.55325663", "0.55307275", "0.55285215", "0.55129087", "0.55124116", "0.55116653", "0.55082184", "0.54956824", "0.5495414", "0.54917043", "0.5482422", "0.5476435", "0.5466828" ]
0.6054629
5
TestDecodeEncodedPayload checks that the decoding the encoded payload results in the same payload. This is only a basic sanity check.
func TestDecodeEncodedTRC(t *testing.T) { regularCrt := loadCert(t, "./testdata/regular-voting.crt") trc := cppki.TRC{ Version: 1, ID: cppki.TRCID{ ISD: 1, Base: 3, Serial: 4, }, Validity: cppki.Validity{ NotBefore: regularCrt.NotBefore.Add(time.Hour), NotAfter: regularCrt.NotAfter.Add(-time.Hour), }, GracePeriod: 10 * time.Hour, NoTrustReset: false, Votes: []int{1, 2, 4}, Quorum: 1, CoreASes: xtest.MustParseASes("ff00:0:110,ff00:0:120"), AuthoritativeASes: xtest.MustParseASes("ff00:0:110"), Description: "This is a testing ISD", Certificates: []*x509.Certificate{ loadCert(t, "./testdata/sensitive-voting.crt"), regularCrt, }, } raw, err := trc.Encode() require.NoError(t, err) dec, err := cppki.DecodeTRC(raw) require.NoError(t, err) dec.Raw = nil assert.Equal(t, trc, dec) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestDecodePayloadEmpty(t *testing.T) {\n\tassert := assert.New(t)\n\tpayload := bytes.NewBufferString(\"\")\n\n\tdecoded, err := decodePayload(payload.Bytes())\n\n\tassert.Equal(Payload{}, decoded)\n\tassert.Nil(err)\n}", "func TestDecodePayloadBadJSON(t *testing.T) {\n\tassert := assert.New(t)\n\tbody := `{\"foo\": \"bar\", \"baz\": 1`\n\tpayload := bytes.NewBufferString(body)\n\n\tdecoded, err := decodePayload(payload.Bytes())\n\n\tassert.Nil(decoded)\n\tassert.NotNil(err)\n}", "func TestPayloadDecodert(t *testing.T) {\n\t// s := `42:420[\"chat message with ack\",{\"msg\":\"111\"}]`\n\ts := `43:421[\"chat message with ack\",{\"msg\":\"ää\"}]`\n\t// s := `43:421[\"chat message with ack\",{\"msg\":\"kälä\"}]`\n\n\t// fmt.Println(len([]byte(`21[\"chat message with ack\",{\"msg\":\"ää\"}`)))\n\t// fmt.Println(\"actual length\", len([]byte(`21[\"chat message with ack\",{\"msg\":\"kälä\"}]`)))\n\n\tbuf := bytes.NewBuffer([]byte(s))\n\n\tpayloadDecoder := parser.NewPayloadDecoder(buf)\n\n\tpkgDec, err := payloadDecoder.Next()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tdefer pkgDec.Close()\n\n\tdecoded := make([]byte, 1024)\n\tn, err := pkgDec.Read(decoded)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tfmt.Println(\"decoded\", n, string(decoded)[0:n])\n\n\tsaver := &FrameSaver{}\n\n\tsaver.data = []FrameData{\n\t\t{\n\t\t\tBuffer: bytes.NewBuffer(decoded),\n\t\t\tType: engineio.MessageText,\n\t\t},\n\t}\n\n\tdecoder := newDecoder(saver)\n\n\tdecodeData := &[]interface{}{&jsonMsg{}}\n\tpacket := packet{Data: decodeData}\n\n\tif err := decoder.Decode(&packet); err != nil {\n\t\tlog.Println(\"socket Decode error\", err)\n\t\tt.Error(err)\n\t}\n\n\terr = decoder.DecodeData(&packet)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tmsg, err := debugJsonMsgData(&packet)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tfmt.Println(\"jsonMsg.Msg\", msg.Msg)\n\n\tif msg.Msg != \"ää\" {\n\t\tt.Error(\"Bad msg\", msg.Msg)\n\t}\n\n\t// ret, err := s.socketHandler.onPacket(decoder, &p)\n\n}", "func TestDecode(t *testing.T) {\n\ttearDown := setUp(t)\n\tdefer tearDown(t)\n\n\tdata := packet.Serialize()\n\tnewPkt, err := Decode(data, &net.UDPAddr{})\n\tassert.NoError(t, err)\n\n\t// Ensure the new packet serializes the same\n\tnewData := newPkt.Serialize()\n\tassert.Equal(t, data, newData)\n}", "func TestDecodePayloadHappyPath(t *testing.T) {\n\tassert := assert.New(t)\n\tbody := `{\"foo\": \"bar\", \"baz\": 1}`\n\tpayload := bytes.NewBufferString(body)\n\n\tdecoded, err := decodePayload(payload.Bytes())\n\n\tassert.Equal(Payload{\"foo\": \"bar\", \"baz\": float64(1)}, decoded)\n\tassert.Nil(err)\n}", "func TestDecodeBadEncoded(t *testing.T) {\n\tt.Parallel()\n\n\t// remove last character\n\tif passwordDecoded, err := junosdecode.Decode(junWordCoded[:len(junWordCoded)-1]); err == nil {\n\t\tt.Errorf(\"missing character in junWordCoded not detected, passwordDecoded: %s\", passwordDecoded)\n\t}\n\t// add last character\n\tif passwordDecoded, err := junosdecode.Decode(junWordCoded + string(rune(rand.Intn(26)))); err == nil { //nolint: gosec\n\t\tt.Errorf(\"extra character in junWordCoded not detected, passwordDecoded: %s\", passwordDecoded)\n\t}\n\t// add two last characters\n\tif passwordDecoded, err := junosdecode.Decode(\n\t\tjunWordCoded + string(rune(rand.Intn(26))) + string(rune(rand.Intn(26)))); err == nil { //nolint: gosec\n\t\tt.Errorf(\"extra characters in junWordCoded not detected, passwordDecoded: %s\", passwordDecoded)\n\t}\n}", "func TestDecode(t *testing.T) {\n\tif hiddenOne == hiddenZero {\n\t\t// This would be a huge problem.\n\t\tt.Fail()\n\t}\n\n\tif decode(hiddenZero) != \"0\" {\n\t\tt.Fail()\n\t}\n\n\tif decode(hiddenOne) != \"1\" {\n\t\tt.Fail()\n\t}\n}", "func TestDecode(t *testing.T) {\n\tt.Parallel()\n\n\ttestCases := []struct {\n\t\tname string\n\t\ttweakEnc func(*msgpack.Encoder)\n\t\tinput any // will be encoded verbatim with\n\t\texpect *TestMessage\n\t\texpectUnknown protoreflect.RawFields\n\t\texpectRaw msgpack.RawMessage\n\t\texpectDecoded any\n\t\terr string\n\t}{\n\t\t{\n\t\t\tname: \"int32->int64\",\n\t\t\tinput: map[int32]any{\n\t\t\t\t3: int32(10),\n\t\t\t},\n\t\t\texpect: &TestMessage{Intval: 10},\n\t\t},\n\t\t{\n\t\t\tname: \"int8->int64\",\n\t\t\tinput: map[int32]any{\n\t\t\t\t3: int8(10),\n\t\t\t},\n\t\t\texpect: &TestMessage{Intval: 10},\n\t\t},\n\t\t{\n\t\t\tname: \"int64->int32\",\n\t\t\tinput: map[int32]any{\n\t\t\t\t5: int64(10),\n\t\t\t},\n\t\t\texpect: &TestMessage{ShortIntval: 10},\n\t\t},\n\t\t{\n\t\t\tname: \"int64->int32 (overflow)\",\n\t\t\tinput: map[int32]any{\n\t\t\t\t5: int64(math.MaxInt32 * 2),\n\t\t\t},\n\t\t\texpect: &TestMessage{ShortIntval: -2},\n\t\t},\n\t\t{\n\t\t\tname: \"float64->int32\",\n\t\t\tinput: map[int32]any{\n\t\t\t\t5: float64(217),\n\t\t\t},\n\t\t\terr: \"bad type: expected int32, got float64\",\n\t\t},\n\n\t\t{\n\t\t\tname: \"unknown field\",\n\t\t\tinput: map[int32]any{\n\t\t\t\t777: \"nerds\",\n\t\t\t\t3: 100,\n\t\t\t},\n\t\t\texpect: &TestMessage{\n\t\t\t\tIntval: 100,\n\t\t\t},\n\t\t\texpectUnknown: []byte{\n\t\t\t\t250, 255, 255, 255, 15, // proto: 536870911: LEN\n\t\t\t\t10, // proto: 10 bytes in this field\n\t\t\t\t129, // msgpack: 1 element map\n\t\t\t\t205, 3, 9, // msgpack: 777\n\t\t\t\t165, 110, 101, 114, 100, 115, // msgpack: 5-char string, \"nerds\"\n\t\t\t},\n\t\t\texpectRaw: []byte{\n\t\t\t\t130, // 2 item map\n\t\t\t\t3, 100, // tag 3, 100\n\t\t\t\t205, 3, 9, 165, 110, 101, 114, 100, 115, // tag 777, 5 char string \"nerds\"\n\t\t\t},\n\t\t\texpectDecoded: map[int32]any{\n\t\t\t\t3: int64(100),\n\t\t\t\t777: \"nerds\",\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"sparse array\",\n\t\t\tinput: map[int32]any{\n\t\t\t\t13: map[int32]string{\n\t\t\t\t\t3: \"hello\",\n\t\t\t\t\t12: \"there\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpect: &TestMessage{\n\t\t\t\tStrings: []string{\n\t\t\t\t\t\"\", \"\", \"\",\n\t\t\t\t\t\"hello\",\n\t\t\t\t\t\"\", \"\", \"\",\n\t\t\t\t\t\"\", \"\", \"\",\n\t\t\t\t\t\"\", \"\",\n\t\t\t\t\t\"there\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tConvey(`TestDecode`, t, func() {\n\t\tfor _, tc := range testCases {\n\t\t\ttc := tc\n\t\t\tConvey(tc.name, func() {\n\t\t\t\tenc := msgpack.GetEncoder()\n\t\t\t\tdefer msgpack.PutEncoder(enc)\n\n\t\t\t\tbuf := bytes.Buffer{}\n\t\t\t\tenc.Reset(&buf)\n\t\t\t\tif tc.tweakEnc != nil {\n\t\t\t\t\ttc.tweakEnc(enc)\n\t\t\t\t}\n\t\t\t\tSo(enc.Encode(tc.input), ShouldBeNil)\n\n\t\t\t\tmsg := &TestMessage{}\n\t\t\t\terr := Unmarshal(buf.Bytes(), msg)\n\t\t\t\tif tc.err == \"\" {\n\t\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\t\tknown := proto.Clone(msg).(*TestMessage)\n\t\t\t\t\tknown.ProtoReflect().SetUnknown(nil)\n\t\t\t\t\tSo(known, ShouldResembleProto, tc.expect)\n\n\t\t\t\t\tSo(msg.ProtoReflect().GetUnknown(), ShouldResemble, tc.expectUnknown)\n\n\t\t\t\t\tif tc.expectRaw != nil {\n\t\t\t\t\t\traw, err := Marshal(msg, Deterministic)\n\t\t\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\t\t\tSo(raw, ShouldResemble, tc.expectRaw)\n\n\t\t\t\t\t\tif len(msg.ProtoReflect().GetUnknown()) > 0 {\n\t\t\t\t\t\t\tdec := msgpack.GetDecoder()\n\t\t\t\t\t\t\tdefer msgpack.PutDecoder(dec)\n\t\t\t\t\t\t\tdec.Reset(bytes.NewBuffer(raw))\n\t\t\t\t\t\t\tdec.UseLooseInterfaceDecoding(true)\n\t\t\t\t\t\t\tdec.SetMapDecoder(func(d *msgpack.Decoder) (any, error) {\n\t\t\t\t\t\t\t\treturn d.DecodeUntypedMap()\n\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\tdecoded := reflect.MakeMap(reflect.TypeOf(tc.expectDecoded))\n\n\t\t\t\t\t\t\tSo(dec.DecodeValue(decoded), ShouldBeNil)\n\n\t\t\t\t\t\t\tSo(decoded.Interface(), ShouldResemble, tc.expectDecoded)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tSo(err, ShouldErrLike, tc.err)\n\t\t\t\t}\n\n\t\t\t})\n\t\t}\n\t})\n\n}", "func TestDecodePayloadSliceEmpty(t *testing.T) {\n\tassert := assert.New(t)\n\tpayload := bytes.NewBufferString(\"\")\n\n\tdecoded, err := decodePayloadSlice(payload.Bytes())\n\n\tassert.Equal([]Payload{}, decoded)\n\tassert.Nil(err)\n}", "func TestDecode(t *testing.T) {\n\tdec := decode.NewDecoder()\n\t// register creation functions for all the slats.\n\tdec.AddDefaultCallbacks(core.Slats)\n\t// read say story data\n\tvar spec map[string]interface{}\n\tif e := json.Unmarshal([]byte(debug.SayHelloGoodbyeData), &spec); e != nil {\n\t\tt.Fatal(e)\n\t} else if prog, e := dec.ReadSpec(spec); e != nil {\n\t\tt.Fatal(e)\n\t} else if diff := pretty.Diff(debug.SayHelloGoodbye, prog); len(diff) > 0 {\n\t\tt.Fatal(pretty.Sprint(prog))\n\t} else {\n\t\tt.Log(\"ok. decoded story matches expected story\")\n\t}\n}", "func (s *Message) DecodePayload(p interface{}) {\n\tif err := json.Unmarshal(s.Payload, p); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n}", "func TestEncodeAndDecode(t *testing.T) {\n\tt.Parallel()\n\n\tcases := []struct {\n\t\tname string\n\t\tin string\n\t\tencoding Scheme\n\t\tout string\n\t}{\n\t\t{\n\t\t\tname: \"F1F2F3 v1\",\n\t\t\tin: \"\\xF1\\xF2\\xF3\",\n\t\t\tencoding: V1,\n\t\t\tout: \"wUAn\",\n\t\t},\n\t\t{\n\t\t\tname: \"F1F2F3 v2\",\n\t\t\tin: \"\\xF1\\xF2\\xF3\",\n\t\t\tencoding: V2,\n\t\t\tout: \"wUAn\",\n\t\t},\n\t\t{\n\t\t\tname: \"empty string v1\",\n\t\t\tin: \"\",\n\t\t\tencoding: V1,\n\t\t\tout: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"empty string v2\",\n\t\t\tin: \"\",\n\t\t\tencoding: V1,\n\t\t\tout: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"single char v1\",\n\t\t\tin: \"\\x00\",\n\t\t\tencoding: V1,\n\t\t\tout: \"00\",\n\t\t},\n\t\t{\n\t\t\tname: \"single char v2\",\n\t\t\tin: \"\\x00\",\n\t\t\tencoding: V2,\n\t\t\tout: \"..\",\n\t\t},\n\t\t{\n\t\t\tname: \"random string v1\",\n\t\t\tin: \"\\x67\\x9a\\x5c\\x48\\xbe\\x97\\x27\\x75\\xdf\\x6a\",\n\t\t\tencoding: V1,\n\t\t\tout: \"OtdRHAuM9rMUPV\",\n\t\t},\n\t\t{\n\t\t\tname: \"random string v2\",\n\t\t\tin: \"\\x67\\x9a\\x5c\\x48\\xbe\\x97\\x27\\x75\\xdf\\x6a\",\n\t\t\tencoding: V2,\n\t\t\tout: \"OtdRHAuM8rMUPV\",\n\t\t},\n\t}\n\n\tfor _, tt := range cases {\n\t\ttt := tt\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\tencoding := encodings[tt.encoding]\n\n\t\t\tin := []byte(tt.in)\n\t\t\tactual, err := Encode(encoding, in)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"unexpected error for subtest %q: %s\", tt.name, err)\n\t\t\t}\n\t\t\texpected := tt.out\n\n\t\t\tif diff := cmp.Diff(expected, actual); diff != \"\" {\n\t\t\t\tt.Errorf(\"unexpected diff during encoding for subtest %q (-want +got): %s\", tt.name, diff)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestBase64Decode(t *testing.T) {\n\twant := \"Hello World\"\n\tg, _ := phpfuncs.Base64Decode(\"SGVsbG8gV29ybGQ=\")\n\tCoverCheck(t, g, want)\n}", "func testEncodeDecode(i interface{}, t *testing.T) {\n\te := NewEncoder()\n\n\tswitch i.(type) {\n\tcase bool:\n\t\te.EncodeBool(i.(bool))\n\tcase int:\n\t\te.EncodeInt(i.(int))\n\tcase int64:\n\t\te.EncodeInt64(i.(int64))\n\tcase int32:\n\t\te.EncodeInt32(i.(int32))\n\tcase int16:\n\t\te.EncodeInt16(i.(int16))\n\tcase int8:\n\t\te.EncodeInt8(i.(int8))\n\tcase uint:\n\t\te.EncodeUint(i.(uint))\n\tcase uint64:\n\t\te.EncodeUint64(i.(uint64))\n\tcase uint32:\n\t\te.EncodeUint32(i.(uint32))\n\tcase uint16:\n\t\te.EncodeUint16(i.(uint16))\n\tcase uint8:\n\t\te.EncodeUint8(i.(uint8))\n\tcase float64:\n\t\te.EncodeFloat64(i.(float64))\n\tcase float32:\n\t\te.EncodeFloat32(i.(float32))\n\tcase string:\n\t\te.EncodeString(i.(string))\n\tcase []byte:\n\t\te.EncodeData(i.([]byte))\n\t}\n\n\td := NewDecoder(e.Data())\n\n\tvar o interface{}\n\tvar err error\n\n\tswitch i.(type) {\n\tcase bool:\n\t\to, err = d.DecodeBool()\n\tcase int:\n\t\to, err = d.DecodeInt()\n\tcase int64:\n\t\to, err = d.DecodeInt64()\n\tcase int32:\n\t\to, err = d.DecodeInt32()\n\tcase int16:\n\t\to, err = d.DecodeInt16()\n\tcase int8:\n\t\to, err = d.DecodeInt8()\n\tcase uint:\n\t\to, err = d.DecodeUint()\n\tcase uint64:\n\t\to, err = d.DecodeUint64()\n\tcase uint32:\n\t\to, err = d.DecodeUint32()\n\tcase uint16:\n\t\to, err = d.DecodeUint16()\n\tcase uint8:\n\t\to, err = d.DecodeUint8()\n\tcase float64:\n\t\to, err = d.DecodeFloat64()\n\tcase float32:\n\t\to, err = d.DecodeFloat32()\n\tcase string:\n\t\to, err = d.DecodeString()\n\tcase []byte:\n\t\to, err = d.DecodeData()\n\t}\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error decoding type: %s\\n\", err)\n\t}\n\n\tswitch i.(type) {\n\tcase []byte:\n\t\tib := i.([]byte)\n\t\tob := o.([]byte)\n\n\t\tif len(ib) == len(ob) {\n\t\t\tfor j, v := range ib {\n\t\t\t\tif v != ob[j] {\n\t\t\t\t\tt.Fatalf(\"Mismatched values %d and %d.\\n\", v, ob[j])\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tt.Fatalf(\"Data has unequal length %d != %d.\\n\", len(ib), len(ob))\n\t\t}\n\tdefault:\n\t\tif i != o {\n\t\t\tt.Fatalf(\"Expected output %v to match input %v.\\n\", o, i)\n\t\t}\n\t}\n}", "func TestCheckSignatureEncoding(t *testing.T) {\n\tt.Parallel()\n\n\ttests := []struct {\n\t\tname string\n\t\tsig []byte\n\t\tisValid bool\n\t}{\n\t\t{\n\t\t\tname: \"valid signature\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: true,\n\t\t},\n\t\t{\n\t\t\tname: \"empty.\",\n\t\t\tsig: nil,\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"bad magic\",\n\t\t\tsig: decodeHex(\"314402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"bad 1st int marker magic\",\n\t\t\tsig: decodeHex(\"304403204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"bad 2nd int marker\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41032018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"short len\",\n\t\t\tsig: decodeHex(\"304302204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"long len\",\n\t\t\tsig: decodeHex(\"304502204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"long X\",\n\t\t\tsig: decodeHex(\"304402424e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"long Y\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022118152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"short Y\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41021918152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"trailing crap\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d0901\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"X == N \",\n\t\t\tsig: decodeHex(\"30440220fffffffffffffffffffffffffffff\" +\n\t\t\t\t\"ffebaaedce6af48a03bbfd25e8cd0364141022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"X == N \",\n\t\t\tsig: decodeHex(\"30440220fffffffffffffffffffffffffffff\" +\n\t\t\t\t\"ffebaaedce6af48a03bbfd25e8cd0364142022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Y == N\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd410220fffff\" +\n\t\t\t\t\"ffffffffffffffffffffffffffebaaedce6af48a03bb\" +\n\t\t\t\t\"fd25e8cd0364141\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Y > N\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd410220fffff\" +\n\t\t\t\t\"ffffffffffffffffffffffffffebaaedce6af48a03bb\" +\n\t\t\t\t\"fd25e8cd0364142\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"0 len X\",\n\t\t\tsig: decodeHex(\"302402000220181522ec8eca07de4860a4acd\" +\n\t\t\t\t\"d12909d831cc56cbbac4622082221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"0 len Y\",\n\t\t\tsig: decodeHex(\"302402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd410200\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"extra R padding\",\n\t\t\tsig: decodeHex(\"30450221004e45e16932b8af514961a1d3a1a\" +\n\t\t\t\t\"25fdf3f4f7732e9d624c6c61548ab5fb8cd410220181\" +\n\t\t\t\t\"522ec8eca07de4860a4acdd12909d831cc56cbbac462\" +\n\t\t\t\t\"2082221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"extra S padding\",\n\t\t\tsig: decodeHex(\"304502204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022100181\" +\n\t\t\t\t\"522ec8eca07de4860a4acdd12909d831cc56cbbac462\" +\n\t\t\t\t\"2082221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t}\n\n\t// flags := ScriptVerifyStrictEncoding\n\tflags := StandardVerifyFlags\n\tfor _, test := range tests {\n\t\terr := TstCheckSignatureEncoding(test.sig, flags)\n\t\tif err != nil && test.isValid {\n\t\t\tt.Errorf(\"checkSignatureEncoding test '%s' failed \"+\n\t\t\t\t\"when it should have succeeded: %v\", test.name,\n\t\t\t\terr)\n\t\t} else if err == nil && !test.isValid {\n\t\t\tt.Errorf(\"checkSignatureEncooding test '%s' succeeded \"+\n\t\t\t\t\"when it should have failed\", test.name)\n\t\t}\n\t}\n}", "func TestEncoding(t *testing.T) {\n\tif DecUint16(EncUint16(u16)) != u16 {\n\t\tt.Fatal(\"uint32 encode/decode mismatch\")\n\t}\n\tif DecInt32(EncInt32(i32)) != i32 {\n\t\tt.Fatal(\"int32 encode/decode mismatch\")\n\t}\n\tif DecUint32(EncUint32(u32)) != u32 {\n\t\tt.Fatal(\"uint32 encode/decode mismatch\")\n\t}\n\tif DecFloat32(EncFloat32(f32)) != f32 {\n\t\tt.Fatal(\"float32 encode/decode mismatch\")\n\t}\n\tif DecInt64(EncInt64(i64)) != i64 {\n\t\tt.Fatal(\"int64 encode/decode mismatch\")\n\t}\n\tif DecUint64(EncUint64(u64)) != u64 {\n\t\tt.Fatal(\"uint64 encode/decode mismatch\")\n\t}\n\tif DecFloat64(EncFloat64(f64)) != f64 {\n\t\tt.Fatal(\"float64 encode/decode mismatch\")\n\t}\n}", "func TestDecodePayloadSliceBadJSON(t *testing.T) {\n\tassert := assert.New(t)\n\tbody := `[{\"foo\": \"bar\", \"baz\": 1`\n\tpayload := bytes.NewBufferString(body)\n\n\tdecoded, err := decodePayloadSlice(payload.Bytes())\n\n\tassert.Nil(decoded)\n\tassert.NotNil(err)\n}", "func PayloadEqual(a, b interface{}) bool {\r\n\tif a == nil && b == nil {\r\n\t\treturn true\r\n\t}\r\n\tif a == nil || b == nil {\r\n\t\treturn false\r\n\t}\r\n\tswitch a := a.(type) {\r\n\tcase proto.Message:\r\n\t\treturn proto.Equal(a, b.(proto.Message))\r\n\tcase string:\r\n\t\treturn a == b.(string)\r\n\tdefault:\r\n\t\tpanic(fmt.Sprintf(\"payloadEqual: unexpected type %T\", a))\r\n\t}\r\n}", "func TestDecodeDF17MT28(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tframe string\n\t\temergency bool\n\t\tcap int\n\t}{\n\t\t{name: fmt.Sprintf(\"DF17/MT28/ST01 %s\", DF17FrameEmergencyPriority), frame: \"8C7C4A0CE104BC0000000069DE1A\", cap: 4},\n\t\t{name: fmt.Sprintf(\"DF17/MT28/ST01 %s\", DF17FrameEmergencyPriority), frame: \"8D7C4A0CE101950000000095FC54\", cap: 5},\n\t\t{name: fmt.Sprintf(\"DF17/MT28/ST01 %s\", DF17FrameEmergencyPriority), frame: \"8D7C4A0CE104BC0000000031AF62\", cap: 5},\n\t\t{name: fmt.Sprintf(\"DF17/MT28/ST01 %s\", DF17FrameEmergencyPriority), frame: \"8F7C4A0CE104BC00000000814D92\", cap: 7},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tframe, err := DecodeString(tt.frame, time.Now())\n\t\t\tif frame == nil || nil != err {\n\t\t\t\tt.Error(err, \"failed to decode\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif 17 != frame.DownLinkType() {\n\t\t\t\tt.Error(\"Should have been DF17\")\n\t\t\t}\n\t\t\tif 28 != frame.MessageType() {\n\t\t\t\tt.Error(\"Should have been Message Type 28\")\n\t\t\t}\n\t\t\tif 1 != frame.MessageSubType() {\n\t\t\t\tt.Error(\"Should have been Message Type 28\")\n\t\t\t}\n\n\t\t\tif \"7C4A0C\" != frame.IcaoStr() {\n\t\t\t\tt.Errorf(\"Invalid ICAO. 7C4A0C != %s\", frame.IcaoStr())\n\t\t\t}\n\n\t\t\t// todo: determine more tests\n\t\t})\n\t}\n}", "func TestReencode(t *testing.T) {\n\tfor i, tt := range PrimitiveTestData {\n\t\treencode(i, tt.input, tt.reference, t, NineP2000)\n\t}\n\tfor i, tt := range MessageTestData {\n\t\treencode(i, tt.input, tt.reference, t, NineP2000)\n\t}\n}", "func PayloadEqual(a, b interface{}) bool {\n\tif a == nil && b == nil {\n\t\treturn true\n\t}\n\tif a == nil || b == nil {\n\t\treturn false\n\t}\n\tswitch a := a.(type) {\n\tcase proto.Message:\n\t\treturn proto.Equal(a, b.(proto.Message))\n\tcase string:\n\t\treturn a == b.(string)\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"payloadEqual: unexpected type %T\", a))\n\t}\n}", "func DecodePayload(evtID EventType, payload []byte) (interface{}, error) {\n\tt, ok := EvtDataMap[evtID]\n\n\tif !ok {\n\t\tif _, ok := EventsToStringMap[evtID]; ok {\n\t\t\t// valid event\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, &UnknownEventError{Evt: evtID}\n\t}\n\n\tif t == nil {\n\t\treturn nil, nil\n\t}\n\n\tclone := reflect.New(reflect.TypeOf(t)).Interface()\n\terr := msgpack.Unmarshal(payload, clone)\n\treturn clone, err\n}", "func TestDecode(t *testing.T) {\n\traw, err := ioutil.ReadFile(\"xpacket.input\")\n\tif err == nil {\n\t\tofile, err := os.Open(\"xpacket.output\")\n\t\tif err == nil {\n\t\t\tout, err := Decode(ofile)\n\t\t\txassert.IsNil(t, err)\n\t\t\txassert.Equal(t, bytes.Compare(out, raw), 0)\n\t\t}\n\t}\n}", "func TestMessageFromBytes(t *testing.T) {\n\tmessage := &Message{\n\t\tTopic: \"test\",\n\t\tData: []byte(\"test\"),\n\t} // Initialize message\n\n\tencodedMessage, err := message.Bytes() // Get message bytes\n\n\tif err != nil { // Check for errors\n\t\tt.Fatal(err) // Panic\n\t}\n\n\tdecodedMessage, err := MessageFromBytes(encodedMessage) // Decode message\n\n\tif err != nil { // Check for errors\n\t\tt.Fatal(err) // Panic\n\t}\n\n\tif !bytes.Equal(decodedMessage.Data, message.Data) { // Check invalid message\n\t\tt.Fatalf(\"invalid decoded message; got %s, wanted %s\", string(decodedMessage.Data), string(message.Data)) // Panic\n\t}\n}", "func (r *Request) AssertPayload(t *testing.T, payload interface{}) *Request {\n\tvar err error\n\tpj, err := json.Marshal(payload)\n\tif err != nil {\n\t\tpanic(\"test: error marshaling assertion payload: \" + err.Error())\n\t}\n\n\tvar p interface{}\n\terr = json.Unmarshal(pj, &p)\n\tif err != nil {\n\t\tpanic(\"test: error unmarshaling assertion payload: \" + err.Error())\n\t}\n\n\tif !reflect.DeepEqual(p, r.Payload) {\n\t\tt.Fatalf(\"expected request payload to be:\\n%s\\nbut got:\\n%s\", pj, r.RawPayload)\n\t}\n\treturn r\n}", "func TestEncodeDecodeBinary(t *testing.T) {\n\ttestEncodeDecodeFunctions(t,\n\t\tencodeLeaseRequestBinary, encodeLeaseReplyBinary,\n\t\tdecodeLeaseRequestBinary, decodeLeaseReplyBinary)\n}", "func TestDecodePassword(t *testing.T) {\n\tt.Parallel()\n\n\tpasswordDecoded, err := junosdecode.Decode(junWordCoded)\n\tif err != nil {\n\t\tt.Errorf(\"error on decode %v\", err)\n\t}\n\tif passwordDecoded != junWordDecoded {\n\t\tt.Errorf(\"decode password failed\")\n\t}\n}", "func TestEncodeDecode(t *testing.T) {\n\tvar (\n\t\tctx = context.TODO()\n\t\toriginalHeader = header.CommonHeader{\n\t\t\t\"k1\": \"v1\",\n\t\t\t\"k2\": \"v2\",\n\t\t}\n\t\tpayload = \"hello world\"\n\t\trequestID = uint32(111)\n\t)\n\n\t//////////// request part start\n\treq := NewRpcRequest(requestID, originalHeader,\n\t\tbuffer.NewIoBufferString(payload))\n\n\tassert.NotNil(t, req)\n\n\tbuf, err := encodeRequest(ctx, req)\n\tassert.Nil(t, err)\n\n\tcmd, err := decodeRequest(ctx, buf, false)\n\tassert.Nil(t, err)\n\n\tdecodedReq, ok := cmd.(*Request)\n\tassert.True(t, ok)\n\n\t// the decoded header should contains every header set in beginning\n\tfor k, v := range originalHeader {\n\t\tval, ok := decodedReq.Get(k)\n\t\tassert.True(t, ok)\n\t\tassert.Equal(t, v, val)\n\t}\n\n\t// should equal to the original request\n\tassert.Equal(t, decodedReq.GetData().String(), payload)\n\tassert.Equal(t, decodedReq.GetRequestId(), uint64(requestID))\n\tassert.Equal(t, decodedReq.CmdType, bolt.CmdTypeRequest)\n\tassert.False(t, decodedReq.IsHeartbeatFrame())\n\tassert.Equal(t, decodedReq.GetStreamType(), api.Request)\n\n\tdecodedReq.SetRequestId(222)\n\tassert.Equal(t, decodedReq.GetRequestId(), uint64(222))\n\n\tnewData := \"new hello world\"\n\tdecodedReq.SetData(buffer.NewIoBufferString(newData))\n\tassert.Equal(t, newData, decodedReq.GetData().String())\n\t//////////// request part end\n\n\t//////////// response part start\n\tresp := NewRpcResponse(requestID, 0, originalHeader, buffer.NewIoBufferString(payload))\n\tbuf, err = encodeResponse(ctx, resp)\n\tassert.Nil(t, err)\n\n\tcmd, err = decodeResponse(ctx, buf)\n\tassert.Nil(t, err)\n\tdecodedResp, ok := cmd.(*Response)\n\tassert.True(t, ok)\n\tassert.Equal(t, decodedResp.GetData().String(), payload)\n\tassert.Equal(t, decodedResp.GetRequestId(), uint64(requestID))\n\tassert.Equal(t, decodedResp.CmdType, bolt.CmdTypeResponse)\n\tassert.False(t, decodedResp.IsHeartbeatFrame())\n\tassert.Equal(t, decodedResp.GetStreamType(), api.Response)\n\n\tnewRespData := \"new resp data\"\n\tdecodedResp.SetData(buffer.NewIoBufferString(newRespData))\n\tassert.Equal(t, decodedResp.GetData().String(), newRespData)\n\n\tdecodedResp.SetRequestId(222)\n\tassert.Equal(t, decodedResp.GetRequestId(), uint64(222))\n\t//////////// response part end\n}", "func TestEncodeDecode(t *testing.T) {\n\ttimeString := \"1970-01-01T00:01:00Z\"\n\ttimestamp, err := time.Parse(time.RFC3339, timeString)\n\te1 := &Event{Timestamp: timestamp}\n\te1.Data = map[int64]interface{}{-1: int64(20), -2: \"baz\", 10: int64(123)}\n\n\t// Encode\n\tbuffer := new(bytes.Buffer)\n\terr = e1.EncodeRaw(buffer)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to encode: %v\", err)\n\t}\n\n\t// Decode\n\te2 := &Event{}\n\terr = e2.DecodeRaw(buffer)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to decode: %v\", err)\n\t}\n\tif !e1.Equal(e2) {\n\t\tt.Fatalf(\"Events do not match: %v <=> %v\", e1, e2)\n\t}\n}", "func DecodePayload(data []byte) Payload {\n\te := Payload{}\n\te.Length = binary.LittleEndian.Uint32(data[0:4])\n\te.Op = data[4]\n\te.Channel = binary.LittleEndian.Uint32(data[5:9])\n\te.Data = make([]byte, len(data[9:]))\n\tcopy(e.Data, data[9:])\n\treturn e\n}", "func TestDecodePayloadSliceHappyPath(t *testing.T) {\n\tassert := assert.New(t)\n\tbody := `[{\"foo\": \"bar\", \"baz\": 1}]`\n\tpayload := bytes.NewBufferString(body)\n\n\tdecoded, err := decodePayloadSlice(payload.Bytes())\n\n\tassert.Equal([]Payload{Payload{\"foo\": \"bar\", \"baz\": float64(1)}}, decoded)\n\tassert.Nil(err)\n}", "func (d *Decoder) decodePayload(p []byte) (ctx *proto.PacketContext, err error) {\n\tctx = &proto.PacketContext{\n\t\tDirection: d.direction,\n\t\tProtocol: d.registry.Protocol,\n\t\tKnownPacket: false,\n\t\tPayload: p,\n\t}\n\tpayload := bytes.NewReader(p)\n\n\t// Read packet id.\n\tpacketID, err := util.ReadVarInt(payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tctx.PacketID = proto.PacketID(packetID)\n\t// Now the payload reader should only have left the packet's actual data.\n\n\t// Try find and create packet from the id.\n\tctx.Packet = d.registry.CreatePacket(ctx.PacketID)\n\tif ctx.Packet == nil {\n\t\t// Packet id is unknown in this registry,\n\t\t// the payload is probably being forwarded as is.\n\t\treturn\n\t}\n\n\t// Packet is known, decode data into it.\n\tctx.KnownPacket = true\n\tif err = ctx.Packet.Decode(ctx, payload); err != nil {\n\t\tif err == io.EOF { // payload was to short or decoder has a bug\n\t\t\terr = io.ErrUnexpectedEOF\n\t\t}\n\t\treturn ctx, errs.NewSilentErr(\"error decoding packet (type: %T, id: %s, protocol: %s, direction: %s): %w\",\n\t\t\tctx.Packet, ctx.PacketID, ctx.Protocol, ctx.Direction, err)\n\t}\n\n\t// Payload buffer should now be empty.\n\tif payload.Len() != 0 {\n\t\t// packet decoder did not read all of the packet's data!\n\t\td.log.V(1).Info(\"Packet's decoder did not read all of packet's data\",\n\t\t\t\"ctx\", ctx,\n\t\t\t\"decodedBytes\", len(ctx.Payload),\n\t\t\t\"unreadBytes\", payload.Len())\n\t\treturn ctx, proto.ErrDecoderLeftBytes\n\t}\n\n\t// Packet decoder has read exactly all data from the payload.\n\treturn\n}", "func TestParse(t *testing.T) {\n\tvar sigs []signature\n\terr := json.Unmarshal([]byte(testPatterns), &sigs)\n\tif err != nil {\n\t\tt.Error(\"Failed to load fixtures:\", err)\n\t}\n\tfor _, sig := range sigs {\n\t\tsignature, converted, encoding, err := Parse(sig.Signature, LookupEncoding(sig.Encoding))\n\t\tif sig.Converted != converted {\n\t\t\tt.Errorf(\"Signature '%s' should not have been converted\", sig.Signature)\n\t\t}\n\t\tif sig.NewEncoding != \"\" {\n\t\t\tif converted != true && sig.Converted {\n\t\t\t\tt.Error(\"Converted flag should be set to 'true'\")\n\t\t\t}\n\t\t\tnewEncodingReversed := ReverseEncoding(encoding)\n\t\t\tif sig.NewEncoding != newEncodingReversed {\n\t\t\t\tt.Errorf(\"Encoding conversion didn't work got '%s' expected '%s'\", newEncodingReversed, sig.NewEncoding)\n\t\t\t}\n\n\t\t\tif sig.NewSignature != signature {\n\t\t\t\tt.Errorf(\"Newly encoded signature should be '%s' not '%s'\", sig.NewSignature, signature)\n\t\t\t}\n\t\t}\n\t\tif err != nil && sig.Fail != true {\n\t\t\tt.Error(\"Failed to parse signature:\", err, sig.Signature)\n\t\t}\n\t}\n}", "func TestUnmarshalJSONEncodedStrings(t *testing.T) {\n\t// Test with pre-defined inputs and expectations. Inputs will be converted\n\t// to bytes (not json-marshalled), so we'd expect inputs that are not valid\n\t// json-encoded strings to fail.\n\texpectionsTests := []struct {\n\t\tname string\n\t\tjsonPass jsonString\n\t\texpectErr bool\n\t}{\n\t\t// valid json-encoded strings\n\t\t{\n\t\t\tname: \"empty string\",\n\t\t\tjsonPass: `\"\"`,\n\t\t\texpectErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"qutf-8 string\",\n\t\t\tjsonPass: `\"@123\"`,\n\t\t\texpectErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"string with escaped char (\\\")\",\n\t\t\tjsonPass: `\"quote\\\"embedded\"`,\n\t\t\texpectErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"unicode character\",\n\t\t\tjsonPass: `\"\\u5f5b\"`,\n\t\t\texpectErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"unicode surrogate pair\",\n\t\t\tjsonPass: `\"\\uD800\\uDC00\"`,\n\t\t\texpectErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"valid non-utf8 characters\",\n\t\t\tjsonPass: `\"√ç∂\"`,\n\t\t\texpectErr: false,\n\t\t},\n\n\t\t// invalid json strings\n\t\t{\n\t\t\tname: \"unquoted empty string\",\n\t\t\tjsonPass: \"\",\n\t\t\texpectErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"unquoted UTF8 string\",\n\t\t\tjsonPass: `@123`,\n\t\t\texpectErr: true,\n\t\t},\n\t\t{\n\t\t\tname: `quoted string with unescaped \" char`,\n\t\t\tjsonPass: `\"quote\"embedded\"`,\n\t\t\texpectErr: true,\n\t\t},\n\t\t{\n\t\t\tname: `invalid unicode character (\\U instead of \\u)`,\n\t\t\tjsonPass: `\"\\UD800\"`,\n\t\t\texpectErr: true,\n\t\t},\n\t\t{\n\t\t\tname: `invalid unicode surrogate pair (\\U instead of \\u)`,\n\t\t\tjsonPass: `\"\\UD800\\UDC00\"`,\n\t\t\texpectErr: true,\n\t\t},\n\t}\n\n\tfor _, test := range expectionsTests {\n\t\tvar unmarshalledPassBytes PassBytes\n\t\terr := json.Unmarshal(test.jsonPass.bytes(), &unmarshalledPassBytes)\n\t\tif test.expectErr && err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif test.expectErr {\n\t\t\tt.Fatalf(\"%s -> %q: expected error but got nil\", test.name, test.jsonPass)\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%s -> %q: unexpected unmarshal error: %v\", test.name, test.jsonPass, err)\n\t\t}\n\n\t\t// If we got here, we expect unmarshalling to have been successful,\n\t\t// confirm that the unmarshalled password is accurate.\n\t\tactualPassword, err := test.jsonPass.string()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%s: unexpected error getting actual password string from JSON-encoded string (%q): %v\",\n\t\t\t\ttest.name, test.jsonPass, err)\n\t\t}\n\t\tunmarshalunmarshalledPassword := string(unmarshalledPassBytes)\n\t\tif actualPassword != unmarshalunmarshalledPassword {\n\t\t\tt.Fatalf(\"%s: expected %q, got %q\", test.name, actualPassword, unmarshalunmarshalledPassword)\n\t\t}\n\t}\n}", "func TestReadingValidBencodedFile(t *testing.T) {\n\treader, fileErr := os.Open(\"../testresources/single-file.torrent\")\n\tif fileErr != nil {\n\t\tt.Errorf(\"Cannot run test - failed to read file %v\", fileErr)\n\t}\n\n\tdecoded, err := DecodeBencoding(reader)\n\tif err != nil {\n\t\tt.Errorf(\"Error reading bencoded data '%v'\", err)\n\t}\n\n\tannounce := decoded.Get(\"announce\")\n\tif announce != \"http://linuxtracker.org:2710/00000000000000000000000000000000/announce\" {\n\t\tt.Errorf(\"Announce key should have held url value but was '%v'\", announce)\n\t}\n\n\tcreationDate := decoded.Get(\"creation date\")\n\tif creationDate != 1537299287 {\n\t\tt.Errorf(\"Expected creation date to be 1537299287 but was %v\", creationDate)\n\t}\n\n\tencoding := decoded.Get(\"encoding\")\n\tif encoding != \"UTF-8\" {\n\t\tt.Errorf(\"Expected encoding to be 'UTF-8' but was '%v'\", encoding)\n\t}\n\n\tinfoMapUncast := decoded.Get(\"info\")\n\tvar infoMap *model.OrderedMap\n\tswitch v := infoMapUncast.(type) {\n\tcase *model.OrderedMap:\n\t\tinfoMap = v\n\tdefault:\n\t\tt.Errorf(\"Expected info map type to be map[string]interface{} but was %v\", v)\n\t\treturn\n\t}\n\n\tlength := infoMap.Get(\"length\")\n\tif length != 1637744640 {\n\t\tt.Errorf(\"Expected length to be 1637744640 but read out '%v'\", length)\n\t}\n\n\tname := infoMap.Get(\"name\")\n\tif name != \"Reborn-OS-2018.09.17-x86_64.iso\" {\n\t\tt.Errorf(\"Read out unexpected name from info dictionary '%v'\", name)\n\t}\n\n\tpieceLength := infoMap.Get(\"piece length\")\n\tif pieceLength != 1048576 {\n\t\tt.Errorf(\"Expected piece length to be 1048576 but was %v\", pieceLength)\n\t}\n\n\tprivate := infoMap.Get(\"private\")\n\tif private != 1 {\n\t\tt.Errorf(\"Expected private to be 1 but was %v\", private)\n\t}\n\n\tpieces, ok := infoMap.Get(\"pieces\").(string)\n\tif !ok {\n\t\tt.Errorf(\"Could not cast pieces to string\")\n\t}\n\tlengthOfPieces := len(pieces)\n\tif lengthOfPieces != 31240 {\n\t\tt.Errorf(\"Expected length of pieces to be 31240 but was '%v'\", lengthOfPieces)\n\t}\n}", "func VerifyEncoded(pwd []byte, encoded []byte) (bool, error) {\n\tr, err := Decode(encoded)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn r.Verify(pwd)\n}", "func TestEncoding(t *testing.T) {\n\t// Create privkeys and addresses\n\tpriv1 := ed25519.GenPrivKey()\n\tpriv2 := ed25519.GenPrivKey()\n\taddr1 := priv1.PubKey().Address().Bytes()\n\taddr2 := priv2.PubKey().Address().Bytes()\n\n\tsendMsg := MsgSend{\n\t\tFrom: addr1,\n\t\tTo: addr2,\n\t\tAmount: sdk.Coins{sdk.NewCoin(\"testcoins\", sdk.NewInt(100))},\n\t}\n\n\t// Construct transaction\n\tsignBytes := sendMsg.GetSignBytes()\n\tsig, err := priv1.Sign(signBytes)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsendTxBefore := app2Tx{\n\t\tMsg: sendMsg,\n\t\tPubKey: priv1.PubKey(),\n\t\tSignature: sig,\n\t}\n\n\tcdc := NewCodec()\n\ttestTxDecoder := tx2Decoder(cdc)\n\n\tencodedSendTx, err := cdc.MarshalBinaryLengthPrefixed(sendTxBefore)\n\n\trequire.Nil(t, err, \"Error encoding sendTx\")\n\n\tvar tx1 sdk.Tx\n\ttx1, err = testTxDecoder(encodedSendTx)\n\trequire.Nil(t, err, \"Error decoding sendTx\")\n\n\tsendTxAfter := tx1.(app2Tx)\n\n\trequire.Equal(t, sendTxBefore, sendTxAfter, \"Transaction changed after encoding/decoding\")\n\n\tissueMsg := MsgIssue{\n\t\tIssuer: addr1,\n\t\tReceiver: addr2,\n\t\tCoin: sdk.NewCoin(\"testcoin\", sdk.NewInt(100)),\n\t}\n\n\tsignBytes = issueMsg.GetSignBytes()\n\tsig, err = priv1.Sign(signBytes)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tissueTxBefore := app2Tx{\n\t\tMsg: issueMsg,\n\t\tPubKey: priv1.PubKey(),\n\t\tSignature: sig,\n\t}\n\n\tencodedIssueTx, err2 := cdc.MarshalBinaryLengthPrefixed(issueTxBefore)\n\n\trequire.Nil(t, err2, \"Error encoding issueTx\")\n\n\tvar tx2 sdk.Tx\n\ttx2, err2 = testTxDecoder(encodedIssueTx)\n\trequire.Nil(t, err2, \"Error decoding issue Tx\")\n\n\tissueTxAfter := tx2.(app2Tx)\n\n\trequire.Equal(t, issueTxBefore, issueTxAfter, \"Transaction changed after encoding/decoding\")\n\n}", "func TestVarBytesEncodeDecode(t *testing.T) {\n\t// Get a random number of bytes\n\trand.Seed(time.Now().UnixNano())\n\tn := rand.Intn(2048)\n\tbs := randBytes(n)\n\n\t// Serialize\n\tbuf := new(bytes.Buffer)\n\tif err := WriteVarBytes(buf, bs); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Deserialize\n\tvar rbs []byte\n\tif err := ReadVarBytes(buf, &rbs); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Compare\n\tassert.Equal(t, bs, rbs)\n}", "func TestBytesMessage(t *testing.T) {\n\tmessage := &Message{\n\t\tTopic: \"test\",\n\t\tData: []byte(\"test\"),\n\t} // Initialize message\n\n\tencodedMessage, err := message.Bytes() // Encode message\n\n\tif err != nil { // Check for errors\n\t\tt.Fatal(err) // Panic\n\t}\n\n\tif !strings.Contains(string(encodedMessage), \"test\") { // Check invalid encoded message\n\t\tt.Fatal(\"invalid encoded message\") // Panic\n\t}\n}", "func TestEncryptDecryptFramePayload(t *testing.T) {\n\tt.Parallel()\n\t// Create a random key.\n\tkey := fastrand.Bytes(X25519KeyLen)\n\n\t// Initialize the cipher.\n\taead, err := chacha20poly1305.New(key[:])\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// Create a frame that is maller than the encryptedFrameSize, one that is\n\t// the same size and one that is bigger to test for edge cases.\n\tencryptedFrameSize := uint32(ipV4PacketSize)\n\tencryptedFramePayloadSize := int(encryptedFrameSize) - marshaledFrameHeaderSize - aead.Overhead() - aead.NonceSize()\n\tmfs := maxFramePayloadSize(encryptedFrameSize, aead)\n\tsmallFrame := fastrand.Bytes(mfs - 1)\n\tmediumFrame := fastrand.Bytes(mfs)\n\tlargeFrame := fastrand.Bytes(mfs + 1)\n\n\t// Encrypt the frames. Should work for the small and medium frame but not the\n\t// large one.\n\tsmallFrameEncrypted, err := encryptFramePayload(smallFrame, encryptedFrameSize, aead)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tmediumFrameEncrypted, err := encryptFramePayload(mediumFrame, encryptedFrameSize, aead)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = encryptFramePayload(largeFrame, encryptedFrameSize, aead)\n\tif err == nil {\n\t\tt.Fatal(\"encrypting the largeFrame should have failed but didn't\")\n\t}\n\n\t// Check the size of the encrypted frames.\n\tif len(smallFrameEncrypted) != encryptedFramePayloadSize {\n\t\tt.Fatalf(\"expected frame to have size %v but was %v\", encryptedFramePayloadSize, len(smallFrameEncrypted))\n\t}\n\tif len(mediumFrameEncrypted) != encryptedFramePayloadSize {\n\t\tt.Fatalf(\"expected frame to have size %v but was %v\", encryptedFramePayloadSize, len(mediumFrameEncrypted))\n\t}\n\n\t// Decrypt the frames again. The decrypted frames minus padding should match\n\t// the original data.\n\tsmallFrame2, err := decryptFramePayload(smallFrameEncrypted, aead)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tmediumFrame2, err := decryptFramePayload(mediumFrameEncrypted, aead)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsmallFrame2 = smallFrame2[:len(smallFrame)]\n\tmediumFrame2 = mediumFrame2[:len(mediumFrame)]\n\tif !bytes.Equal(smallFrame, smallFrame2) {\n\t\tt.Fatal(\"frames don't match\")\n\t}\n\tif !bytes.Equal(mediumFrame, mediumFrame2) {\n\t\tt.Fatal(\"frames don't match\")\n\t}\n}", "func TestSignEncodeAndDecode(t *testing.T) {\n\tvar r Record\n\tu := UDP(30303)\n\tr.Set(&u)\n\tip := IP{127, 0, 0, 1}\n\tr.Set(&ip)\n\trequire.NoError(t, signTest([]byte{5}, &r))\n\n\tblob, err := r.Encode(nil)\n\trequire.NoError(t, err)\n\n\tvar r2 Record\n\t_, err = r2.Decode(blob)\n\trequire.NoError(t, err)\n\tassert.Equal(t, r, r2)\n\n\tblob2, err := r2.Encode(nil)\n\trequire.NoError(t, err)\n\tassert.Equal(t, blob, blob2)\n}", "func TestFlow_InvalidCoding(t *testing.T) {\n\n\t_, err := DecodeFlow(\"INVALID\")\n\tif err == nil {\n\t\tt.Errorf(\"Unable to detect invalid flow from %s\\n\", \"INVALID\")\n\t}\n\n\t_, err = DecodeFlow(\"Y291Y291\")\n\tif err == nil {\n\t\tt.Errorf(\"Unable to detect invalid flow from %s\\n\", \"INVALID\")\n\t}\n}", "func Test_invalidBitStrings(t *testing.T) {\n\n\tbs1 := &e2sm_rc_pre_v2.BitString{\n\t\tValue: []byte{0xab, 0xbc},\n\t\t//Value: []byte{0xab, 0xbc, 0x00}, // - correct set of bytes to satisfy byte length constraint\n\t\tLen: 22,\n\t}\n\t_, err := newBitString(bs1)\n\t//assert.NilError(t, err)\n\tassert.ErrorContains(t, err, \"bytes are required for length\")\n\n\tbs2 := &e2sm_rc_pre_v2.BitString{\n\t\tValue: []byte{0xab, 0xbc, 0xcf},\n\t\t//Value: []byte{0xab, 0xbc, 0xcc}, // - a correct set of bytes to satisfy octet-alignment constraint\n\t\tLen: 22,\n\t}\n\t_, err = newBitString(bs2)\n\t//assert.NilError(t, err)\n\tassert.ErrorContains(t, err, \"bit string is NOT octet-aligned\")\n\n\t// A valid bit string with proper length and proper octet alignment\n\t// 25 bits need 4 bytes to be encoded successfully\n\t// 4 bytes is 32 bits, 32-25 = 7 (unused bits)\n\t// BitString.Value byte array should be shifted on 7 (unused) bits to the left to be Octet-aligned and satisfy APER encoding rules\n\tbs3 := &e2sm_rc_pre_v2.BitString{\n\t\tValue: []byte{0x09, 0xAB, 0xCD, 0x80},\n\t\tLen: 25,\n\t}\n\tbsC, err := newBitString(bs3)\n\tassert.NilError(t, err)\n\n\tprotoBitString, err := decodeBitString(bsC)\n\tassert.NilError(t, err)\n\t//assert.Assert(t, protoBitString != nil)\n\tassert.Equal(t, int(protoBitString.Len), 25, \"unexpected bit string length\")\n\tassert.DeepEqual(t, protoBitString.Value, []byte{0x09, 0xab, 0xcd, 0x80})\n}", "func IsEncoded(s string) bool {\n\tB64EncodedRegex := *regexp.MustCompile(`^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$`)\n\treturn B64EncodedRegex.MatchString(s)\n}", "func TestUnmarshalBaseMessage(t *testing.T) {\n\tvar baseMessage BaseMessage\n\tbytesBaseMessage, _ := json.Marshal(baseMessage)\n\ttests := []struct {\n\t\tname string\n\t\tbaseMsg []byte\n\t\twant *BaseMessage\n\t\twantErr error\n\t}{\n\t\t{\n\t\t\tname: \"UnmarshalBaseMessageTest-WrongFormat\",\n\t\t\tbaseMsg: []byte(\"\"),\n\t\t\twant: nil,\n\t\t\twantErr: errors.New(\"unexpected end of JSON input\"),\n\t\t},\n\t\t{\n\t\t\tname: \"UnmarshalBaseMessageTest-RightFormat\",\n\t\t\tbaseMsg: bytesBaseMessage,\n\t\t\twant: &baseMessage,\n\t\t\twantErr: nil,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tgot, err := UnmarshalBaseMessage(test.baseMsg)\n\t\t\tif err != nil {\n\t\t\t\tif !reflect.DeepEqual(err.Error(), test.wantErr.Error()) {\n\t\t\t\t\tt.Errorf(\"Error Got = %v,Want =%v\", err.Error(), test.wantErr.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif !reflect.DeepEqual(err, test.wantErr) {\n\t\t\t\t\tt.Errorf(\"Error Got = %v,Want =%v\", err, test.wantErr)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(got, test.want) {\n\t\t\t\tt.Errorf(\"UnmarshalBaseMessage() = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func TestHTTPDecoder_not200(t *testing.T) {\n\thelper.VerifyIfSkipIntegrationTests(t)\n\ttests := []struct {\n\t\tcode int\n\t}{\n\t\t{http.StatusNotFound},\n\t\t{http.StatusBadRequest},\n\t\t{http.StatusInternalServerError},\n\t}\n\n\tfor i, tt := range tests {\n\t\tt.Run(fmt.Sprintf(\"http_#%v\", i), func(t *testing.T) {\n\t\t\tfunc() {\n\t\t\t\tserver := helper.MockServer(tt.code, \"response\")\n\t\t\t\tdefer server.Close()\n\n\t\t\t\tdec := httpdecoder.Decoder{\n\t\t\t\t\tURL: server.URL,\n\t\t\t\t}\n\n\t\t\t\ttopic := \"topic\"\n\t\t\t\tsch := kafka.Schedule{\n\t\t\t\t\tMessage: &confluent.Message{\n\t\t\t\t\t\tTopicPartition: confluent.TopicPartition{\n\t\t\t\t\t\t\tTopic: &topic,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tKey: []byte(\"video-1\"),\n\t\t\t\t\t\tValue: []byte(\"content\"),\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\t// create a copy of the schedule\n\t\t\t\tsch2 := helper.CopyKafkaSchedule(sch)\n\n\t\t\t\tsch3, err := dec.Decode(&sch)\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Error(\"expected error\")\n\t\t\t\t}\n\n\t\t\t\tsch4, ok := sch3.(*kafka.Schedule)\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Errorf(\"unexpected type: %v\", sch3)\n\t\t\t\t}\n\n\t\t\t\tif reflect.DeepEqual(*sch4, sch2) == false {\n\t\t\t\t\tt.Errorf(\"should be equal\")\n\t\t\t\t}\n\t\t\t}()\n\t\t})\n\t}\n}", "func TestEncodeDecodeGob(t *testing.T) {\n\ttestEncodeDecodeFunctions(t,\n\t\tencodeLeaseRequestGob, encodeLeaseReplyGob,\n\t\tdecodeLeaseRequestGob, decodeLeaseReplyGob)\n}", "func TestSignEncodeAndDecodeRandom(t *testing.T) {\n\tvar r Record\n\n\t// random key/value Pairs for testing\n\tPairs := map[string]uint32{}\n\tfor i := 0; i < 10; i++ {\n\t\tkey := randomString(7)\n\t\tvalue := rnd.Uint32()\n\t\tPairs[string(key)] = value\n\t\tv := msg.Uint(value)\n\t\tr.Set(WithEntry(string(key), &v))\n\t}\n\n\trequire.NoError(t, signTest([]byte{5}, &r))\n\t_, err := r.MarshalMsg(nil)\n\trequire.NoError(t, err)\n\n\tfor k, v := range Pairs {\n\t\tdesc := fmt.Sprintf(\"key %q\", k)\n\t\tvar got msg.Uint32\n\t\tbuf := WithEntry(k, &got)\n\t\trequire.NoError(t, r.Load(buf), desc)\n\t\trequire.Equal(t, v, uint32(got), desc)\n\t}\n}", "func TestEncoderAndDecoder(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\n\tinPb := &example.A{\n\t\tDescription: \"hello world!\",\n\t\tNumber: 1,\n\t}\n\t// UUID is 16 byte long\n\tfor i := 0; i < 16; i++ {\n\t\tinPb.Id = append(inPb.Id, byte(i))\n\t}\n\n\tbytes, err := proto.Marshal(inPb)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tmsg := NewMessage(0, bytes)\n\n\te := NewMsgEncoder(buf)\n\te.Encode(msg)\n\n\toutMsg := NewEmptyMessage()\n\n\td := NewMsgDecoder(buf)\n\td.Decode(outMsg)\n\n\tif !reflect.DeepEqual(msg, outMsg) {\n\t\tt.Fatal(\"Messages are not equal!\")\n\t}\n\n\toutPb := new(example.A)\n\n\tproto.Unmarshal(outMsg.bytes, outPb)\n\n\tif !reflect.DeepEqual(outPb, inPb) {\n\t\tt.Fatal(\"Protos are not equal!\")\n\t}\n}", "func testEncodeDecodeFunctions(t *testing.T,\n\tencodeLeaseRequest encodeLeaseRequestFunc,\n\tencodeLeaseReply encodeLeaseReplyFunc,\n\tdecodeLeaseRequest decodeLeaseRequestFunc,\n\tdecodeLeaseReply decodeLeaseReplyFunc) {\n\n\tassert := assert.New(t)\n\n\t// encode a lease request and then decode it\n\tmountByAccountNameReply := &MountByAccountNameReply{\n\t\tMountID: \"66\",\n\t}\n\tleaseRequest := &LeaseRequest{\n\t\tInodeHandle: InodeHandle{\n\t\t\tMountID: mountByAccountNameReply.MountID,\n\t\t\tInodeNumber: testRpcLeaseSingleInodeNumber,\n\t\t},\n\t\tLeaseRequestType: LeaseRequestTypeExclusive,\n\t}\n\tjsonRequest := newJsonRequest(\"RpcLease\")\n\n\t// this marshals both the RPCrequest and the header for the request\n\tleaseRequestHdrBuf, leaseRequestPayloadBuf :=\n\t\tencodeLeaseRequest(leaseRequest, jsonRequest)\n\n\tleaseRequest2, jsonRequest2 :=\n\t\tdecodeLeaseRequest(leaseRequestHdrBuf, leaseRequestPayloadBuf)\n\n\tassert.Equal(leaseRequest, leaseRequest2, \"Decoded struct should match the original\")\n\tassert.Equal(jsonRequest, jsonRequest2, \"Decoded struct should match the original\")\n\n\t// try again with release lease request\n\tleaseRequest.LeaseRequestType = LeaseRequestTypeRelease\n\n\tleaseRequestHdrBuf, leaseRequestPayloadBuf =\n\t\tencodeLeaseRequest(leaseRequest, jsonRequest)\n\n\tleaseRequest2, jsonRequest2 =\n\t\tdecodeLeaseRequest(leaseRequestHdrBuf, leaseRequestPayloadBuf)\n\n\tassert.Equal(leaseRequest, leaseRequest2, \"Decoded struct should match the original\")\n\tassert.Equal(jsonRequest, jsonRequest2, \"Decoded struct should match the original\")\n\n\t// encode reply and decode it\n\tleaseReply := &LeaseReply{\n\t\tLeaseReplyType: LeaseReplyTypeExclusive,\n\t}\n\tjsonReply := newJsonReply()\n\tleaseReplyHdrBuf, leaseReplyPayloadBuf :=\n\t\tencodeLeaseReply(leaseReply, jsonReply)\n\n\tleaseReply2, jsonReply2 :=\n\t\tdecodeLeaseReply(leaseReplyHdrBuf, leaseReplyPayloadBuf)\n\n\tassert.Equal(leaseReply, leaseReply2, \"Decoded struct should match the original\")\n\tassert.Equal(jsonReply, jsonReply2, \"Decoded struct should match the original\")\n\n\t// try again with release lease reply\n\tleaseReply.LeaseReplyType = LeaseReplyTypeReleased\n\n\tleaseReplyHdrBuf, leaseReplyPayloadBuf =\n\t\tencodeLeaseReply(leaseReply, jsonReply)\n\n\tleaseReply2, jsonReply2 =\n\t\tdecodeLeaseReply(leaseReplyHdrBuf, leaseReplyPayloadBuf)\n\n\tassert.Equal(leaseReply, leaseReply2, \"Decoded struct should match the original\")\n\tassert.Equal(jsonReply, jsonReply2, \"Decoded struct should match the original\")\n}", "func TestUsingURLDecoder(t *testing.T) {\n\ttoken := \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJGQ1lZRjJLR0EzQTZHTlZQR0pIVjNUSExYR1VZWkFUREZLV1JTT1czUUo1T0k3QlJST0ZRIiwiaWF0IjoxNTQzOTQzNjc1LCJpc3MiOiJBQ1NKWkhOWlI0QUFUVE1KNzdUV1JONUJHVUZFWFhUS0gzWEtGTldDRkFCVzJRWldOUTRDQkhRRSIsInN1YiI6IkFEVEFHWVZYRkpPRENRM0g0VUZQQU43R1dXWk1BVU9FTTJMMkRWQkFWVFdLM01TU0xUS1JUTzVGIiwidHlwZSI6ImFjdGl2YXRpb24iLCJuYXRzIjp7InN1YmplY3QiOiJmb28iLCJ0eXBlIjoic2VydmljZSJ9fQ.HCZTCF-7wolS3Wjx3swQWMkoDhoo_4gp9EsuM5diJfZrH8s6NTpO0iT7_fKZm7dNDeEoqjwU--3ebp8j-Mm_Aw\"\n\tac, err := DecodeActivationClaims(token)\n\tif err != nil {\n\t\tt.Fatal(\"shouldn't have failed to decode\", err)\n\t}\n\tif ac == nil {\n\t\tt.Fatal(\"should have returned activation\")\n\t}\n}", "func TestEncode(t *testing.T) {\n\tif hiddenOne == hiddenZero {\n\t\t// This would be a huge problem.\n\t\tt.Fail()\n\t}\n\n\tif encode(\"0\") != hiddenZero {\n\t\tt.Fail()\n\t}\n\n\tif encode(\"1\") != hiddenOne {\n\t\tt.Fail()\n\t}\n}", "func Test_JSDecode_Invalid1(t *testing.T) {\n\tequalJSDecode(\n\t\tt,\n\t\t\"\\\\8\\\\9\\\\666\\\\u00ag\\\\u00ga\\\\u0zaa\\\\uz0aa\\\\xag\\\\xga\\\\0123\\\\u00a\",\n\t\t\"89\\x366u00agu00gau0zaauz0aaxagxga\\x0a3u00a\",\n\t)\n}", "func TestHTTPDecoder_200(t *testing.T) {\n\thelper.VerifyIfSkipIntegrationTests(t)\n\n\ttests := []struct {\n\t\tresponse string\n\t\texpectedMessageValue string\n\t}{\n\t\t// message content updated with new content\n\t\t{\"response\", \"response\"},\n\t\t// message content should not be changed when empty response\n\t\t{\"\", \"content\"},\n\t}\n\n\tfor i, tt := range tests {\n\t\tt.Run(fmt.Sprintf(\"case #%v\", i+1), func(t *testing.T) {\n\t\t\tserver := helper.MockServer(200, tt.response)\n\t\t\tdefer server.Close()\n\n\t\t\tdec := httpdecoder.Decoder{\n\t\t\t\tURL: server.URL,\n\t\t\t}\n\n\t\t\ttopic := \"topic\"\n\t\t\tsch := kafka.Schedule{\n\t\t\t\tMessage: &confluent.Message{\n\t\t\t\t\tTopicPartition: confluent.TopicPartition{\n\t\t\t\t\t\tTopic: &topic,\n\t\t\t\t\t},\n\t\t\t\t\tKey: []byte(\"video-1\"),\n\t\t\t\t\tValue: []byte(\"content\"),\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tsch2, err := dec.Decode(&sch)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"unexpected error\")\n\t\t\t}\n\n\t\t\tsch3, ok := sch2.(*kafka.Schedule)\n\t\t\tif !ok {\n\t\t\t\tt.Errorf(\"unexpected type: %T\", sch2)\n\t\t\t}\n\n\t\t\tif string(sch3.Message.Value) != tt.expectedMessageValue {\n\t\t\t\tt.Fatalf(\"message content not correct: %q\", string(sch.Message.Value))\n\t\t\t}\n\t\t})\n\t}\n}", "func TestEncodeDecodeJSON(t *testing.T) {\n\ttestEncodeDecodeFunctions(t,\n\t\tencodeLeaseRequestJson, encodeLeaseReplyJson,\n\t\tdecodeLeaseRequestJson, decodeLeaseReplyJson)\n}", "func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error) {\n\t// Lift the nil check outside of the loop.\n\t_ = enc.decodeMap\n\n\tdsti := 0\n\tolen := len(src)\n\n\tfor len(src) > 0 && !end {\n\t\t// Decode quantum using the base32 alphabet\n\t\tvar dbuf [8]byte\n\t\tdlen := 8\n\n\t\tfor j := 0; j < 8; {\n\n\t\t\tif len(src) == 0 {\n\t\t\t\tif enc.padChar != NoPadding {\n\t\t\t\t\t// We have reached the end and are missing padding\n\t\t\t\t\treturn n, false, CorruptInputError(olen - len(src) - j)\n\t\t\t\t}\n\t\t\t\t// We have reached the end and are not expecting any padding\n\t\t\t\tdlen, end = j, true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tin := src[0]\n\t\t\tsrc = src[1:]\n\t\t\tif in == byte(enc.padChar) && j >= 2 && len(src) < 8 {\n\t\t\t\t// We've reached the end and there's padding\n\t\t\t\tif len(src)+j < 8-1 {\n\t\t\t\t\t// not enough padding\n\t\t\t\t\treturn n, false, CorruptInputError(olen)\n\t\t\t\t}\n\t\t\t\tfor k := 0; k < 8-1-j; k++ {\n\t\t\t\t\tif len(src) > k && src[k] != byte(enc.padChar) {\n\t\t\t\t\t\t// incorrect padding\n\t\t\t\t\t\treturn n, false, CorruptInputError(olen - len(src) + k - 1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdlen, end = j, true\n\t\t\t\t// 7, 5 and 2 are not valid padding lengths, and so 1, 3 and 6 are not\n\t\t\t\t// valid dlen values. See RFC 4648 Section 6 \"Base 32 Encoding\" listing\n\t\t\t\t// the five valid padding lengths, and Section 9 \"Illustrations and\n\t\t\t\t// Examples\" for an illustration for how the 1st, 3rd and 6th base32\n\t\t\t\t// src bytes do not yield enough information to decode a dst byte.\n\t\t\t\tif dlen == 1 || dlen == 3 || dlen == 6 {\n\t\t\t\t\treturn n, false, CorruptInputError(olen - len(src) - 1)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdbuf[j] = enc.decodeMap[in]\n\t\t\tif dbuf[j] == 0xFF {\n\t\t\t\treturn n, false, CorruptInputError(olen - len(src) - 1)\n\t\t\t}\n\t\t\tj++\n\t\t}\n\n\t\t// Pack 8x 5-bit source blocks into 5 byte destination\n\t\t// quantum\n\t\tswitch dlen {\n\t\tcase 8:\n\t\t\tdst[dsti+4] = dbuf[6]<<5 | dbuf[7]\n\t\t\tn++\n\t\t\tfallthrough\n\t\tcase 7:\n\t\t\tdst[dsti+3] = dbuf[4]<<7 | dbuf[5]<<2 | dbuf[6]>>3\n\t\t\tn++\n\t\t\tfallthrough\n\t\tcase 5:\n\t\t\tdst[dsti+2] = dbuf[3]<<4 | dbuf[4]>>1\n\t\t\tn++\n\t\t\tfallthrough\n\t\tcase 4:\n\t\t\tdst[dsti+1] = dbuf[1]<<6 | dbuf[2]<<1 | dbuf[3]>>4\n\t\t\tn++\n\t\t\tfallthrough\n\t\tcase 2:\n\t\t\tdst[dsti+0] = dbuf[0]<<3 | dbuf[1]>>2\n\t\t\tn++\n\t\t}\n\t\tdsti += 5\n\t}\n\treturn n, end, nil\n}", "func decode(k *KeyValue) {\n\tif k.Encoding == \"binary\" {\n\t\tdecoded, err := base64.StdEncoding.DecodeString(k.Data)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error decoding base64 key/value\")\n\t\t}\n\t\tk.Data = string(decoded)\n\t}\n}", "func TestHeader_EncodeAndDecode(t *testing.T) {\n\theader := Header{\n\t\tVersion: 0,\n\t\tMessageType: MsgTypeRequest,\n\t\tCompressType: NoneCompress,\n\t\tSeqID: 1,\n\t\tExtension: 0,\n\t\tBodyLength: 10,\n\t}\n\n\thrd := EncodeHeader(header)\n\n\th, err := DecodeHeader(bytes.NewReader(hrd))\n\tif err != nil {\n\t\tt.Errorf(\"DecodeHeader(%v) Fail\", h)\n\t\treturn\n\t}\n\n\tdiff := cmp.Diff(header, h)\n\tif diff != \"\" {\n\t\tt.Fatalf(diff)\n\t}\n}", "func TestConcatenationFails(t *testing.T) {\n\tt.Parallel()\n\n\tencoding, _ := GetEncoding(V2Padding)\n\n\ta := []byte(\"a\")\n\tb := []byte(\"b\")\n\n\ta2, err := Encode(encoding, a)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tb2, err := Encode(encoding, b)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\t_, err = Decode(encoding, fmt.Sprintf(\"%s%s\", a2, b2))\n\tswitch err {\n\tcase nil:\n\t\tt.Error(\"error is unexpectedly nil\")\n\tdefault:\n\t\tif !strings.Contains(err.Error(), \"illegal base64\") {\n\t\t\tt.Errorf(\"wrong error: %s\", err)\n\t\t}\n\t}\n}", "func TestVarStringEncodeDecode(t *testing.T) {\n\t// Get a random string\n\trand.Seed(time.Now().UnixNano())\n\tn := rand.Intn(2048)\n\tstr := string(randBytes(n))\n\n\t// Serialize\n\tbuf := new(bytes.Buffer)\n\tif err := WriteString(buf, str); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Deserialize\n\trstr, err := ReadString(buf)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Compare\n\tassert.Equal(t, str, rstr)\n}", "func TestMalformedPacket(t *testing.T) {\n\t// copied as bytes from Wireshark, then modified the RelayMessage option length\n\tbytes := []byte{\n\t\t0x0c, 0x00, 0x24, 0x01, 0xdb, 0x00, 0x30, 0x10, 0xb0, 0x8a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x0a, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x0b, 0xab, 0xff, 0xfe, 0x8a,\n\t\t0x6d, 0xf2, 0x00, 0x09, 0x00, 0x50 /*was 0x32*/, 0x01, 0x8d, 0x3e, 0x24, 0x00, 0x01, 0x00, 0x0e, 0x00, 0x01,\n\t\t0x00, 0x01, 0x0c, 0x71, 0x3d, 0x0e, 0x00, 0x0b, 0xab, 0x8a, 0x6d, 0xf2, 0x00, 0x08, 0x00, 0x02,\n\t\t0x00, 0x00, 0x00, 0x03, 0x00, 0x0c, 0xee, 0xbf, 0xfb, 0x6e, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n\t\t0xff, 0xff, 0x00, 0x06, 0x00, 0x02, 0x00, 0x17, 0x00, 0x25, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x09,\n\t\t0x00, 0x03, 0x08, 0x00, 0xf0, 0x7f, 0x06, 0xd6, 0x4c, 0x3c, 0x00, 0x12, 0x00, 0x04, 0x09, 0x01,\n\t\t0x08, 0x5a,\n\t}\n\tpacket := Packet6(bytes)\n\t_, err := packet.dhcp6message()\n\tif err == nil {\n\t\tt.Fatalf(\"Should be unable to extract dhcp6message, but did not fail\")\n\t}\n}", "func TestMarshalUnmarshal(t *testing.T) {\n\tcheckDirectUnmarshal := func(password string, expectMarshalError bool) error {\n\t\t// marshal to json first\n\t\tpwJSON, err := json.Marshal(password)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// unmarshal back from json\n\t\tvar pwFromJSON PassBytes\n\t\tif err = json.Unmarshal(pwJSON, &pwFromJSON); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// confirm accuracy of unmarshal\n\t\tunmarshalledPassword := string(pwFromJSON)\n\t\tif password != unmarshalledPassword {\n\t\t\treturn fmt.Errorf(\"original pw: %q marshalled to %q unmarshalled to %q\",\n\t\t\t\tpassword, string(pwJSON), unmarshalledPassword)\n\t\t}\n\t\treturn nil\n\t}\n\n\tcheckUnmarshalAsBodyProperty := func(password string, expectMarshalError bool) error {\n\t\t// marshal to json first\n\t\toriginalObj := struct {\n\t\t\tPassword string `json:\"pass\"`\n\t\t}{\n\t\t\tPassword: password,\n\t\t}\n\t\tjsonObj, err := json.Marshal(originalObj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// unmarshal back from json\n\t\tvar restoredObj = new(struct {\n\t\t\tPassword PassBytes `json:\"pass\"`\n\t\t})\n\t\tif err = json.Unmarshal(jsonObj, restoredObj); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// confirm accuracy of unmarshal\n\t\tunmarshalledPassword := string(restoredObj.Password)\n\t\tif password != unmarshalledPassword {\n\t\t\treturn fmt.Errorf(\"original obj: %v (password %q) marshalled to %s and unmarshalled to %v (password %q)\",\n\t\t\t\toriginalObj, password, string(jsonObj), restoredObj, unmarshalledPassword)\n\t\t}\n\t\treturn nil\n\t}\n\n\t// test with 100 randomly generated strings of length between 0 and 19 chars\n\tfor i := 0; i < 100; i++ {\n\t\ts := randomString(i % 20)\n\t\texpectMarshalError := !json.Valid([]byte(s)) // expect marshal error if s contains invalid chars\n\t\tif err := checkDirectUnmarshal(s, expectMarshalError); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif err := checkUnmarshalAsBodyProperty(s, expectMarshalError); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}", "func TestSpecialTests(t *testing.T) {\n\terr := RunTestEncode(slip44.BITCOIN, TestcaseEncode {\n\t\tname: \"Positive encode case but expecting excpetion\",\n\t\tinput: \"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa\",\n\t\terr: errors.New(\"Error\"),\n\t})\n\tif err == nil {\n\t\tt.Errorf(\"Expected error error mismatch\")\n\t}\n\t\n\terr = RunTestEncode(slip44.BITCOIN, TestcaseEncode {\n\t\tname: \"Negative case but expecting output\",\n\t\tinput: \"bc1vehk7cnpwgz0ta92\",\n\t\toutput: \"0014751e76e8199196d454941c45d1b3a323f1433bd6\",\n\t})\n\tif err == nil {\n\t\tt.Errorf(\"Expected error error mismatch\")\n\t}\n\n\terr = RunTestDecode(slip44.BITCOIN, TestcaseDecode {\n\t\tname: \"Positive decode case but expecting excpetion\",\n\t\tinput: \"76a91462e907b15cbf27d5425399ebf6f0fb50ebb88f1888ac\",\n\t\terr: errors.New(\"Error\"),\n\t})\n\tif err == nil {\n\t\tt.Errorf(\"Expected error error mismatch\")\n\t}\n\n\terr = RunTestDecode(slip44.BITCOIN, TestcaseDecode {\n\t\tname: \"Negative case but expecting output\",\n\t\tinput: \"00140102\",\n\t\toutput: \"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa\",\n\t})\n\tif err == nil {\n\t\tt.Errorf(\"Expected error error mismatch\")\n\t}\n\n\terr = RunTestDecode(slip44.BITCOIN, TestcaseDecode {\n\t\tname: \"Not hex\",\n\t\tinput: \"THIS IS NOT A HEX\",\n\t\terr: errors.New(\"Preparation error\"),\n\t})\n\tif err == nil {\n\t\tt.Errorf(\"Expected error for not hex\")\n\t}\n}", "func testDecoder(kv *mvccpb.KeyValue) (interface{}, error) {\n\tvar i, err = strconv.ParseInt(string(kv.Value), 10, 64)\n\treturn int(i), err\n}", "func UnmarshalTransactionPayload(r *bytes.Buffer, f *TransactionPayload) error {\n\treturn encoding.ReadVarBytesUint32LE(r, &f.Data)\n}", "func (b *mockEncoder) Decode(data []byte, value interface{}, _ ...interface{}) error {\n\treturn json.Unmarshal(data, value)\n}", "func TestUnmarshalMembershipDetail(t *testing.T) {\n\tvar memDetail MembershipDetail\n\tbytesMemDetail, _ := json.Marshal(memDetail)\n\ttests := []struct {\n\t\tname string\n\t\tmembershipDetail []byte\n\t\twant *MembershipDetail\n\t\twantErr error\n\t}{\n\t\t{\n\t\t\tname: \"UnMarshalMembershipDetailTest-WrongFormat\",\n\t\t\tmembershipDetail: []byte(\"\"),\n\t\t\twant: nil,\n\t\t\twantErr: errors.New(\"unexpected end of JSON input\"),\n\t\t},\n\t\t{\n\t\t\tname: \"UnMarshalMembershipDetailTest-CorrectFormat\",\n\t\t\tmembershipDetail: bytesMemDetail,\n\t\t\twant: &memDetail,\n\t\t\twantErr: nil,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tgot, err := UnmarshalMembershipDetail(test.membershipDetail)\n\t\t\tif err != nil {\n\t\t\t\tif !reflect.DeepEqual(err.Error(), test.wantErr.Error()) {\n\t\t\t\t\tt.Errorf(\"Error Got = %v,Want =%v\", err.Error(), test.wantErr.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif !reflect.DeepEqual(err, test.wantErr) {\n\t\t\t\t\tt.Errorf(\"Error Got = %v,Want =%v\", err, test.wantErr)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !reflect.DeepEqual(got, test.want) {\n\t\t\t\tt.Errorf(\"UnmarshalMembershipDetail() = %v, want %v\", got, test.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func SetupDecode(r io.Reader) (string, error) {\n\tb := make([]byte, LenTotal)\n\n\tif n, _ := r.Read(b); n != LenTotal {\n\t\treturn \"\", fmt.Errorf(\"did not receive the correct amount of info, got %d, want %d\", n, LenTotal)\n\t}\n\tif !uuidRE.Match(b) {\n\t\treturn \"\", fmt.Errorf(\"did not contain a valid UUIDv4\")\n\t}\n\treturn string(b), nil\n}", "func VerifyPayloadPattern(payload, pattern []byte) error {\n\tpatternSize := len(pattern)\n\tnReplica := len(payload) / patternSize\n\n\tfor i := 0; i < nReplica; i++ {\n\t\tbN := payload[0:patternSize] // Next pattern sized bytes\n\t\tpayload = payload[patternSize:] // Shift payload for next iteration\n\n\t\tif !bytes.Equal(bN, pattern) {\n\t\t\treturn fmt.Errorf(\"bytes are not in the expected format. payload[%d-Replica]=%v, pattern=%v\", i, bN, pattern)\n\t\t}\n\t}\n\n\tif !bytes.Equal(payload, pattern[:len(payload)]) {\n\t\treturn fmt.Errorf(\"last %d bytes are not in the expected format. payload=%v, expected=%v\", len(payload), payload, pattern[:len(payload)])\n\t}\n\n\treturn nil\n}", "func base64Decode(s string) ([]byte, error) {\n\t// add back missing padding\n\tswitch len(s) % 4 {\n\tcase 2:\n\t\ts += \"==\"\n\tcase 3:\n\t\ts += \"=\"\n\t}\n\treturn base64.URLEncoding.DecodeString(s)\n}", "func base64Decode(s string) ([]byte, error) {\n\t// add back missing padding\n\tswitch len(s) % 4 {\n\tcase 2:\n\t\ts += \"==\"\n\tcase 3:\n\t\ts += \"=\"\n\t}\n\treturn base64.URLEncoding.DecodeString(s)\n}", "func (p *ubPayload) Decode(enc []byte) (graph.NodePayload, error) {\n\tin := string(enc)\n\tl := in[0] - charOffset\n\tflags, e := strconv.Atoi(in[1 : 1+l])\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tret := &ubPayload{flags: flags, suffix: in[1+l:]}\n\treturn ret, nil\n}", "func TestEventPayload(t *testing.T) {\n\tassert := asserts.NewTesting(t, asserts.FailStop)\n\n\tpayloadIn := []string{\"a\", \"b\", \"c\"}\n\tpayloadOutA := []string{}\n\tevt, err := mesh.NewEvent(\"test\", payloadIn)\n\tassert.NoError(err)\n\tassert.Equal(evt.Topic(), \"test\")\n\tassert.True(evt.HasPayload())\n\terr = evt.Payload(&payloadOutA)\n\tassert.NoError(err)\n\tassert.Length(payloadOutA, 3)\n\tassert.Equal(payloadOutA, payloadIn)\n\n\tpayloadOutB := []int{}\n\tevt, err = mesh.NewEvent(\"test\", 1, 2, 3, 4, 5)\n\tassert.NoError(err)\n\tassert.Equal(evt.Topic(), \"test\")\n\tassert.True(evt.HasPayload())\n\terr = evt.Payload(&payloadOutB)\n\tassert.NoError(err)\n\tassert.Length(payloadOutB, 5)\n\tassert.Equal(payloadOutB, []int{1, 2, 3, 4, 5})\n}", "func (m *MockSession) GetDataEncoded() []byte {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetDataEncoded\")\n\tret0, _ := ret[0].([]byte)\n\treturn ret0\n}", "func TestTokenPayload(t *testing.T) {\n\tdb.InitDB()\n\tvar router *gin.Engine = routes.SetupRouter()\n\n\tvar user models.UserCreate = utils.CreateUser(\"Tom\", \"qwerty1234\", t, router)\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\n\tsplittedToken := strings.Split(user.Token, \".\")\n\tif len(splittedToken) != 3 {\n\t\tlog.Fatal(\"Bad token.\")\n\t\tt.Fail()\n\t}\n\n\theader := splittedToken[0]\n\tpayload := splittedToken[1]\n\tsignature := splittedToken[2]\n\n\tdecPayloadByte, err := base64.RawURLEncoding.DecodeString(payload)\n\n\tvar payloadObj models.JwtPayload\n\terr = json.Unmarshal(decPayloadByte, &payloadObj)\n\tif err != nil {\n\t\tlog.Fatal(\"Bad output: \", err.Error())\n\t\tt.Fail()\n\t}\n\tpayloadObj.Iat = 123456\n\tpayloadObj.Exp = 123456\n\tjsonPayload, _ := json.Marshal(payloadObj)\n\tnewPayload := base64.RawURLEncoding.EncodeToString([]byte(string(jsonPayload)))\n\n\tmodifiedToken := header + \".\" + newPayload + \".\" + signature\n\n\tvar url string = \"/v1/user/\" + strconv.Itoa(user.ID)\n\tvar bearer = \"Bearer \" + modifiedToken\n\trecord := httptest.NewRecorder()\n\trequest, _ := http.NewRequest(\"GET\", url, nil)\n\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\trequest.Header.Add(\"Authorization\", bearer)\n\n\trouter.ServeHTTP(record, request)\n\n\tvar message Message\n\terr = json.Unmarshal([]byte(record.Body.String()), &message)\n\tif err != nil {\n\t\tlog.Fatal(\"Bad output: \", err.Error())\n\t\tt.Fail()\n\t}\n\n\tassert.Equal(t, record.Code, 403)\n\tassert.Equal(t, message.Message, \"Bad signature\")\n\n\tuser.Token = utils.ConnectUser(\"Tom\", \"qwerty1234\", t, router)\n\tutils.CleanUser(user.ID, user.Token, t, router)\n\tdb.CloseDB()\n}", "func DecodeAndEncodeRTTest(t *testing.T, xmlPath string, includeDirs []string) {\n\tfor index, c := range casesMsgsTest {\n\t\t// Encode using CT\n\t\tdCT, err := gomavlib.NewDialectCT(3, ctMessages)\n\t\trequire.NoError(t, err)\n\t\tdMsgCT, ok := dCT.Messages[c.id]\n\t\trequire.Equal(t, true, ok)\n\t\tbytesEncoded, err := dMsgCT.Encode(c.parsed, c.isV2)\n\t\trequire.NoError(t, err)\n\t\trequire.Equal(t, c.raw, bytesEncoded)\n\n\t\t// Decode bytes using CT method for RT vs CT comparison later\n\t\tmsgDecodedCT, err := dMsgCT.Decode(c.raw, c.isV2)\n\t\trequire.NoError(t, err)\n\n\t\tif index != 1 && index != 9 { // require.Equal will not work for two equal messages with a field of NaN, since two NaN values are defined as not equal.\n\t\t\trequire.Equal(t, c.parsed, msgDecodedCT)\n\t\t}\n\n\t\t// Decode bytes using RT\n\t\tdefs, version, err := libgen.XMLToFields(xmlPath, includeDirs)\n\t\trequire.NoError(t, err)\n\n\t\t// Create dialect from the parsed defs.\n\t\tdRT, err := gomavlib.NewDialectRT(version, defs)\n\t\tdMsgRT := dRT.Messages[c.id]\n\t\trequire.NoError(t, err)\n\t\trequire.Equal(t, uint(3), dRT.GetVersion())\n\n\t\t// Decode bytes using RT\n\t\tmsgDecoded, err := dMsgRT.Decode(bytesEncoded, c.isV2)\n\t\trequire.NoError(t, err)\n\n\t\t//Make sure all fields of dMsgCT match equivalent values of RT msgDecoded\n\t\t//Compare all fields of all RT and CT Messages\n\t\tv := reflect.ValueOf(msgDecodedCT).Elem()\n\t\tfor j := 0; j < len(dMsgCT.Fields); j++ {\n\t\t\tfCT := dMsgCT.Fields[j]\n\t\t\toriginalName := fCT.GetName()\n\t\t\tname := dialectMsgDefToGo(originalName)\n\t\t\tfRT := msgDecoded.(*gomavlib.DynamicMessage).Fields[originalName]\n\t\t\tfCTVal := v.FieldByName(name)\n\t\t\tfieldType, arrayLength, err := findFieldType(msgDecoded.(*gomavlib.DynamicMessage), originalName)\n\t\t\trequire.NoError(t, err)\n\t\t\tswitch fieldType {\n\t\t\tcase \"int8\":\n\t\t\t\tif arrayLength != 0 {\n\t\t\t\t\trtResult := fRT.([]int8)\n\t\t\t\t\tctResult := make([]int8, arrayLength)\n\t\t\t\t\tfor i := 0; i < arrayLength; i++ {\n\t\t\t\t\t\tif fCTVal.Index(i).Kind() == reflect.Int || fCTVal.Index(i).Kind() == reflect.Int8 {\n\t\t\t\t\t\t\tctResult[i] = int8(fCTVal.Index(i).Int())\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tctResult[i] = int8(fCTVal.Index(i).Uint())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trequire.Equal(t, ctResult, rtResult)\n\t\t\t\t} else {\n\t\t\t\t\tif fCTVal.Kind() == reflect.Int || fCTVal.Kind() == reflect.Int8 {\n\t\t\t\t\t\trequire.Equal(t, int8(fCTVal.Int()), fRT.(int8))\n\t\t\t\t\t} else {\n\t\t\t\t\t\trequire.Equal(t, int8(fCTVal.Uint()), fRT.(int8))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"uint8\":\n\t\t\t\tif arrayLength != 0 {\n\t\t\t\t\trtResult := fRT.([]uint8)\n\t\t\t\t\tctResult := make([]uint8, arrayLength)\n\t\t\t\t\tfor i := 0; i < arrayLength; i++ {\n\t\t\t\t\t\tif fCTVal.Index(i).Kind() == reflect.Int || fCTVal.Index(i).Kind() == reflect.Int8 {\n\t\t\t\t\t\t\tctResult[i] = uint8(fCTVal.Index(i).Int())\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tctResult[i] = uint8(fCTVal.Index(i).Uint())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trequire.Equal(t, ctResult, rtResult)\n\t\t\t\t} else {\n\t\t\t\t\tif fCTVal.Kind() == reflect.Int || fCTVal.Kind() == reflect.Int8 {\n\t\t\t\t\t\trequire.Equal(t, uint8(fCTVal.Int()), fRT.(uint8))\n\t\t\t\t\t} else {\n\t\t\t\t\t\trequire.Equal(t, uint8(fCTVal.Uint()), fRT.(uint8))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"int16\":\n\t\t\t\tif arrayLength != 0 {\n\t\t\t\t\trtResult := fRT.([]int16)\n\t\t\t\t\tctResult := make([]int16, arrayLength)\n\t\t\t\t\tfor i := 0; i < arrayLength; i++ {\n\t\t\t\t\t\tif fCTVal.Index(i).Kind() == reflect.Int || fCTVal.Index(i).Kind() == reflect.Int16 {\n\t\t\t\t\t\t\tctResult[i] = int16(fCTVal.Index(i).Int())\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tctResult[i] = int16(fCTVal.Index(i).Uint())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trequire.Equal(t, ctResult, rtResult)\n\t\t\t\t} else {\n\t\t\t\t\tif fCTVal.Kind() == reflect.Int || fCTVal.Kind() == reflect.Int16 {\n\t\t\t\t\t\trequire.Equal(t, int16(fCTVal.Int()), fRT.(int16))\n\t\t\t\t\t} else {\n\t\t\t\t\t\trequire.Equal(t, int16(fCTVal.Uint()), fRT.(int16))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tcase \"uint16\":\n\t\t\t\tif arrayLength != 0 {\n\t\t\t\t\trtResult := fRT.([]uint16)\n\t\t\t\t\tctResult := make([]uint16, arrayLength)\n\t\t\t\t\tfor i := 0; i < arrayLength; i++ {\n\t\t\t\t\t\tif fCTVal.Index(i).Kind() == reflect.Int || fCTVal.Index(i).Kind() == reflect.Int16 {\n\t\t\t\t\t\t\tctResult[i] = uint16(fCTVal.Index(i).Int())\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tctResult[i] = uint16(fCTVal.Index(i).Uint())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trequire.Equal(t, ctResult, rtResult)\n\t\t\t\t} else {\n\t\t\t\t\tif fCTVal.Kind() == reflect.Int || fCTVal.Kind() == reflect.Int16 {\n\t\t\t\t\t\trequire.Equal(t, uint16(fCTVal.Int()), fRT.(uint16))\n\t\t\t\t\t} else {\n\t\t\t\t\t\trequire.Equal(t, uint16(fCTVal.Uint()), fRT.(uint16))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tcase \"int32\":\n\t\t\t\tif arrayLength != 0 {\n\t\t\t\t\trtResult := fRT.([]int32)\n\t\t\t\t\tctResult := make([]int32, arrayLength)\n\t\t\t\t\tfor i := 0; i < arrayLength; i++ {\n\t\t\t\t\t\tif fCTVal.Index(i).Kind() == reflect.Int || fCTVal.Index(i).Kind() == reflect.Int32 {\n\t\t\t\t\t\t\tctResult[i] = int32(fCTVal.Index(i).Int())\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tctResult[i] = int32(fCTVal.Index(i).Uint())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trequire.Equal(t, ctResult, rtResult)\n\t\t\t\t} else {\n\t\t\t\t\tif fCTVal.Kind() == reflect.Int || fCTVal.Kind() == reflect.Int32 {\n\t\t\t\t\t\trequire.Equal(t, int32(fCTVal.Int()), fRT.(int32))\n\t\t\t\t\t} else {\n\t\t\t\t\t\trequire.Equal(t, int32(fCTVal.Uint()), fRT.(int32))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"uint32\":\n\t\t\t\tif arrayLength != 0 {\n\t\t\t\t\trtResult := fRT.([]uint32)\n\t\t\t\t\tctResult := make([]uint32, arrayLength)\n\t\t\t\t\tfor i := 0; i < arrayLength; i++ {\n\t\t\t\t\t\tif fCTVal.Index(i).Kind() == reflect.Int || fCTVal.Index(i).Kind() == reflect.Int32 {\n\t\t\t\t\t\t\tctResult[i] = uint32(fCTVal.Index(i).Int())\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tctResult[i] = uint32(fCTVal.Index(i).Uint())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trequire.Equal(t, ctResult, rtResult)\n\t\t\t\t} else {\n\t\t\t\t\tif fCTVal.Kind() == reflect.Int || fCTVal.Kind() == reflect.Int32 {\n\t\t\t\t\t\trequire.Equal(t, uint32(fCTVal.Int()), fRT.(uint32))\n\t\t\t\t\t} else {\n\t\t\t\t\t\trequire.Equal(t, uint32(fCTVal.Uint()), fRT.(uint32))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tcase \"int64\":\n\t\t\t\tif arrayLength != 0 {\n\t\t\t\t\trtResult := fRT.([]int64)\n\t\t\t\t\tctResult := make([]int64, arrayLength)\n\t\t\t\t\tfor i := 0; i < arrayLength; i++ {\n\t\t\t\t\t\tif fCTVal.Index(i).Kind() == reflect.Int || fCTVal.Index(i).Kind() == reflect.Int64 {\n\t\t\t\t\t\t\tctResult[i] = int64(fCTVal.Index(i).Int())\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tctResult[i] = int64(fCTVal.Index(i).Uint())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trequire.Equal(t, ctResult, rtResult)\n\t\t\t\t} else {\n\t\t\t\t\tif fCTVal.Kind() == reflect.Int || fCTVal.Kind() == reflect.Int64 {\n\t\t\t\t\t\trequire.Equal(t, int64(fCTVal.Int()), fRT.(int64))\n\t\t\t\t\t} else {\n\t\t\t\t\t\trequire.Equal(t, int64(fCTVal.Uint()), fRT.(int64))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tcase \"uint64\":\n\t\t\t\tif arrayLength != 0 {\n\t\t\t\t\trtResult := fRT.([]uint64)\n\t\t\t\t\tctResult := make([]uint64, arrayLength)\n\t\t\t\t\tfor i := 0; i < arrayLength; i++ {\n\t\t\t\t\t\tif fCTVal.Index(i).Kind() == reflect.Int || fCTVal.Index(i).Kind() == reflect.Int64 {\n\t\t\t\t\t\t\tctResult[i] = uint64(fCTVal.Index(i).Int())\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tctResult[i] = uint64(fCTVal.Index(i).Uint())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trequire.Equal(t, ctResult, rtResult)\n\t\t\t\t} else {\n\t\t\t\t\tif fCTVal.Kind() == reflect.Int || fCTVal.Kind() == reflect.Int64 {\n\t\t\t\t\t\trequire.Equal(t, uint64(fCTVal.Int()), fRT.(uint64))\n\t\t\t\t\t} else {\n\t\t\t\t\t\trequire.Equal(t, uint64(fCTVal.Uint()), fRT.(uint64))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"float64\":\n\t\t\t\tif arrayLength != 0 {\n\t\t\t\t\ttemp := fRT.([]gomavlib.JsonFloat64)\n\t\t\t\t\trtResult := make([]float64, arrayLength)\n\t\t\t\t\tctResult := make([]float64, arrayLength)\n\t\t\t\t\tfor i := 0; i < arrayLength; i++ {\n\t\t\t\t\t\tctResult[i] = float64(fCTVal.Index(i).Float())\n\t\t\t\t\t\trtResult[i] = temp[i].F\n\t\t\t\t\t}\n\t\t\t\t\tif index == 9 {\n\t\t\t\t\t\tfor i := 0; i < arrayLength; i++ {\n\t\t\t\t\t\t\tif math.IsNaN(ctResult[i]) {\n\t\t\t\t\t\t\t\tcheck := math.IsNaN(rtResult[i])\n\t\t\t\t\t\t\t\trequire.Equal(t, true, check)\n\t\t\t\t\t\t\t} else if math.IsInf(ctResult[i], 1) {\n\t\t\t\t\t\t\t\tcheck := math.IsInf(rtResult[i], 1)\n\t\t\t\t\t\t\t\trequire.Equal(t, true, check)\n\t\t\t\t\t\t\t} else if math.IsInf(ctResult[i], -1) {\n\t\t\t\t\t\t\t\tcheck := math.IsInf(rtResult[i], -1)\n\t\t\t\t\t\t\t\trequire.Equal(t, true, check)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\trequire.Equal(t, ctResult, rtResult)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\trequire.Equal(t, float64(fCTVal.Float()), fRT.(gomavlib.JsonFloat64).F)\n\t\t\t\t}\n\n\t\t\tcase \"float32\":\n\t\t\t\tif arrayLength != 0 {\n\t\t\t\t\ttemp := fRT.([]gomavlib.JsonFloat32)\n\t\t\t\t\trtResult := make([]float32, arrayLength)\n\t\t\t\t\tctResult := make([]float32, arrayLength)\n\t\t\t\t\tfor i := 0; i < arrayLength; i++ {\n\t\t\t\t\t\tctResult[i] = float32(fCTVal.Index(i).Float())\n\t\t\t\t\t\trtResult[i] = temp[i].F\n\t\t\t\t\t}\n\t\t\t\t\trequire.Equal(t, ctResult, rtResult)\n\t\t\t\t} else {\n\t\t\t\t\tif index == 1 { // Use CT Val to check for NaN, +Inf, and -Inf. Use this to test RT results.\n\t\t\t\t\t\tnan := math.IsNaN(fCTVal.Float())\n\t\t\t\t\t\tposInf := math.IsInf(fCTVal.Float(), 1)\n\t\t\t\t\t\tnegInf := math.IsInf(fCTVal.Float(), -1)\n\t\t\t\t\t\tif nan {\n\t\t\t\t\t\t\ttest := math.IsNaN(float64(fRT.(gomavlib.JsonFloat32).F))\n\t\t\t\t\t\t\trequire.Equal(t, true, test)\n\t\t\t\t\t\t} else if posInf {\n\t\t\t\t\t\t\ttest := math.IsInf(float64(fRT.(gomavlib.JsonFloat32).F), 1)\n\t\t\t\t\t\t\trequire.Equal(t, true, test)\n\t\t\t\t\t\t} else if negInf {\n\t\t\t\t\t\t\ttest := math.IsInf(float64(fRT.(gomavlib.JsonFloat32).F), -1)\n\t\t\t\t\t\t\trequire.Equal(t, true, test)\n\t\t\t\t\t\t} else { // Else treat normally\n\t\t\t\t\t\t\trequire.Equal(t, float32(fCTVal.Float()), fRT.(gomavlib.JsonFloat32).F)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else { // Else treat normally\n\t\t\t\t\t\trequire.Equal(t, float32(fCTVal.Float()), fRT.(gomavlib.JsonFloat32).F)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tcase \"string\":\n\t\t\t\trequire.Equal(t, fCTVal.String(), fRT.(string))\n\n\t\t\tdefault:\n\t\t\t\terr = errors.New(\"invalid type so unable to convert interface values\")\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t\t// Encode using RT\n\t\tbytesEncodedByRT, err := dMsgRT.Encode(msgDecoded, c.isV2)\n\t\trequire.NoError(t, err)\n\t\trequire.Equal(t, c.raw, bytesEncodedByRT)\n\t}\n}", "func ValidatePayload(payload []byte, sig string, tokenGenerator func() []byte) bool {\n\tvar event GenericEvent\n\tif err := json.Unmarshal(payload, &event); err != nil {\n\t\tlogrus.WithError(err).Info(\"validatePayload couldn't unmarshal the github event payload\")\n\t\treturn false\n\t}\n\n\tif !strings.HasPrefix(sig, \"sha1=\") {\n\t\treturn false\n\t}\n\tsig = sig[5:]\n\tsb, err := hex.DecodeString(sig)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\torgRepo := event.Repo.FullName\n\t// If orgRepo is empty, the event is probably org-level, so try getting org name from the Org info.\n\tif orgRepo == \"\" {\n\t\torgRepo = event.Org.Login\n\t}\n\thmacs, err := extractHMACs(orgRepo, tokenGenerator)\n\tif err != nil {\n\t\tlogrus.WithError(err).Warning(\"failed to get an appropriate hmac secret\")\n\t\treturn false\n\t}\n\n\t// If we have a match with any valid hmac, we can validate successfully.\n\tfor _, key := range hmacs {\n\t\tmac := hmac.New(sha1.New, key)\n\t\tmac.Write(payload)\n\t\texpected := mac.Sum(nil)\n\t\tif hmac.Equal(sb, expected) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func testCoder(rt reflect.Type, tc typeCoder) {\n\ts := \"encode\"\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tpanic(errors.New(\"typeCoder can't \" + s + \" type: \" + rt.String()))\n\t\t}\n\t}()\n\tv := reflect.New(rt).Elem()\n\tcw := &Coder{data: make([]byte, 64)}\n\ttc.wf(cw, v)\n\ts = \"decode\"\n\tcr := &Coder{data: cw.Bytes()}\n\ttc.rf(v, cr)\n}", "func TestDecoderInt(t *testing.T) {\n\n\ttype TestInt struct {\n\t\tInt int\n\t\tInt8 int8\n\t\tInt16 int16\n\t\tInt32 int32\n\t\tInt64 int64\n\t\tIntPtr *int\n\t\tInt8Ptr *int8\n\t\tInt16Ptr *int16\n\t\tInt32Ptr *int32\n\t\tInt64Ptr *int64\n\t\tIntArray []int\n\t\tIntPtrArray []*int\n\t\tIntArrayArray [][]int\n\t\tIntPtrArrayArray [][]*int\n\t\tIntMap map[int]int\n\t\tIntPtrMap map[*int]*int\n\t\tNoURLValue int\n\t\tIntNoValues int\n\t\tInt8NoValues int8\n\t\tInt16NoValues int16\n\t\tInt32NoValues int32\n\t\tInt64NoValues int64\n\t}\n\n\tvalues := url.Values{\n\t\t\"Int\": []string{\"3\"},\n\t\t\"Int8\": []string{\"3\"},\n\t\t\"Int16\": []string{\"3\"},\n\t\t\"Int32\": []string{\"3\"},\n\t\t\"Int64\": []string{\"3\"},\n\t\t\"IntPtr\": []string{\"3\"},\n\t\t\"Int8Ptr\": []string{\"3\"},\n\t\t\"Int16Ptr\": []string{\"3\"},\n\t\t\"Int32Ptr\": []string{\"3\"},\n\t\t\"Int64Ptr\": []string{\"3\"},\n\t\t\"IntArray\": []string{\"1\", \"2\", \"3\"},\n\t\t\"IntPtrArray[0]\": []string{\"1\"},\n\t\t\"IntPtrArray[2]\": []string{\"3\"},\n\t\t\"IntArrayArray[0][0]\": []string{\"1\"},\n\t\t\"IntArrayArray[0][2]\": []string{\"3\"},\n\t\t\"IntArrayArray[2][0]\": []string{\"1\"},\n\t\t\"IntPtrArrayArray[0][0]\": []string{\"1\"},\n\t\t\"IntPtrArrayArray[0][2]\": []string{\"3\"},\n\t\t\"IntPtrArrayArray[2][0]\": []string{\"1\"},\n\t\t\"IntMap[1]\": []string{\"3\"},\n\t\t\"IntPtrMap[1]\": []string{\"3\"},\n\t}\n\n\tvar test TestInt\n\n\ttest.IntArray = make([]int, 4)\n\n\tdecoder := NewDecoder()\n\terrs := decoder.Decode(&test, values)\n\tEqual(t, errs, nil)\n\n\tEqual(t, test.Int, int(3))\n\tEqual(t, test.Int8, int8(3))\n\tEqual(t, test.Int16, int16(3))\n\tEqual(t, test.Int32, int32(3))\n\tEqual(t, test.Int64, int64(3))\n\n\tEqual(t, *test.IntPtr, int(3))\n\tEqual(t, *test.Int8Ptr, int8(3))\n\tEqual(t, *test.Int16Ptr, int16(3))\n\tEqual(t, *test.Int32Ptr, int32(3))\n\tEqual(t, *test.Int64Ptr, int64(3))\n\n\tEqual(t, len(test.IntArray), 7)\n\tEqual(t, test.IntArray[0], int(0))\n\tEqual(t, test.IntArray[1], int(0))\n\tEqual(t, test.IntArray[2], int(0))\n\tEqual(t, test.IntArray[3], int(0))\n\tEqual(t, test.IntArray[4], int(1))\n\tEqual(t, test.IntArray[5], int(2))\n\tEqual(t, test.IntArray[6], int(3))\n\n\tEqual(t, len(test.IntPtrArray), 3)\n\tEqual(t, *test.IntPtrArray[0], int(1))\n\tEqual(t, test.IntPtrArray[1], nil)\n\tEqual(t, *test.IntPtrArray[2], int(3))\n\n\tEqual(t, len(test.IntArrayArray), 3)\n\tEqual(t, len(test.IntArrayArray[0]), 3)\n\tEqual(t, len(test.IntArrayArray[1]), 0)\n\tEqual(t, len(test.IntArrayArray[2]), 1)\n\tEqual(t, test.IntArrayArray[0][0], int(1))\n\tEqual(t, test.IntArrayArray[0][1], int(0))\n\tEqual(t, test.IntArrayArray[0][2], int(3))\n\tEqual(t, test.IntArrayArray[2][0], int(1))\n\n\tEqual(t, len(test.IntPtrArrayArray), 3)\n\tEqual(t, len(test.IntPtrArrayArray[0]), 3)\n\tEqual(t, len(test.IntPtrArrayArray[1]), 0)\n\tEqual(t, len(test.IntPtrArrayArray[2]), 1)\n\tEqual(t, *test.IntPtrArrayArray[0][0], int(1))\n\tEqual(t, test.IntPtrArrayArray[0][1], nil)\n\tEqual(t, *test.IntPtrArrayArray[0][2], int(3))\n\tEqual(t, *test.IntPtrArrayArray[2][0], int(1))\n\n\tEqual(t, len(test.IntMap), 1)\n\tEqual(t, len(test.IntPtrMap), 1)\n\n\tv, ok := test.IntMap[1]\n\tEqual(t, ok, true)\n\tEqual(t, v, int(3))\n\n\tEqual(t, test.NoURLValue, int(0))\n\n\tEqual(t, test.IntNoValues, int(0))\n\tEqual(t, test.Int8NoValues, int8(0))\n\tEqual(t, test.Int16NoValues, int16(0))\n\tEqual(t, test.Int32NoValues, int32(0))\n\tEqual(t, test.Int64NoValues, int64(0))\n}", "func (p *Bare) payloadLenOk() bool {\n\tx := p.expectedPayloadLen()\n\treturn len(p.payload) == x || -1 == x\n}", "func (d *decoder) Decode(s *bufio.Scanner) (obj interface{}, err error) {\n\tb, err := ReadBytes(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(b) == 0 {\n\t\tlog.Err(\"empty or malformed payload: %q\", b)\n\t\treturn nil, ErrBadMsg\n\t}\n\n\tswitch b[0] {\n\tcase STRING:\n\t\treturn decodeString(b)\n\tcase INT:\n\t\treturn decodeInt(b)\n\tcase NIL:\n\t\treturn nil, decodeNil(s)\n\tcase SLICE:\n\t\treturn d.decodeSlice(b, s)\n\tcase MAP:\n\t\treturn d.decodeMap(b, s)\n\tcase ERROR:\n\t\treturn decodeErr(b)\n\t}\n\n\tlog.Err(\"unsupported payload type: %q\", b)\n\treturn nil, ErrUnsupportedType\n}", "func (enc *Base64Encoding) Base64Decode(src []byte) ([]byte, error) {\n\tnumOfEquals := 4 - (len(src) % 4)\n\tfor i := 0; i < numOfEquals; i++ {\n\t\tsrc = append(src, '=')\n\t}\n\tdst := make([]byte, enc.Encoding.DecodedLen(len(src)))\n\tn, err := enc.Encoding.Decode(dst, src)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dst[:n], nil\n}", "func TestDecodeInfraLogs(t *testing.T) {\n\tvar logs []InfraLog\n\tin := join(InfraContainerLogStr, JournalLogStr)\n\tdec := json.NewDecoder(strings.NewReader(in))\n\tdec.DisallowUnknownFields()\n\terr := dec.Decode(&logs)\n\tif err != nil {\n\t\tfmt.Printf(\"%#v\", err)\n\t\tt.Fail()\n\t}\n\tif len(logs) != 2 {\n\t\tt.Fail()\n\t}\n}", "func TestWriterMetadataUnchangedEncoding(t *testing.T) {\n\tencodedWm := []byte{\n\t\t0x89, 0xa3, 0x42, 0x49, 0x44, 0xc4, 0x10, 0x0,\n\t\t0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,\n\t\t0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa9,\n\t\t0x44, 0x69, 0x73, 0x6b, 0x55, 0x73, 0x61, 0x67,\n\t\t0x65, 0x64, 0xa2, 0x49, 0x44, 0xc4, 0x10, 0x1,\n\t\t0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,\n\t\t0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x16, 0xb3,\n\t\t0x4c, 0x61, 0x73, 0x74, 0x4d, 0x6f, 0x64, 0x69,\n\t\t0x66, 0x79, 0x69, 0x6e, 0x67, 0x57, 0x72, 0x69,\n\t\t0x74, 0x65, 0x72, 0xa4, 0x75, 0x69, 0x64, 0x31,\n\t\t0xa8, 0x52, 0x65, 0x66, 0x42, 0x79, 0x74, 0x65,\n\t\t0x73, 0x63, 0xaa, 0x55, 0x6e, 0x72, 0x65, 0x66,\n\t\t0x42, 0x79, 0x74, 0x65, 0x73, 0x65, 0xa6, 0x57,\n\t\t0x46, 0x6c, 0x61, 0x67, 0x73, 0xa, 0xa7, 0x57,\n\t\t0x72, 0x69, 0x74, 0x65, 0x72, 0x73, 0x92, 0xa4,\n\t\t0x75, 0x69, 0x64, 0x31, 0xa4, 0x75, 0x69, 0x64,\n\t\t0x32, 0xa4, 0x64, 0x61, 0x74, 0x61, 0xc4, 0x2,\n\t\t0xa, 0xb,\n\t}\n\n\texpectedWm := WriterMetadataV2{\n\t\tSerializedPrivateMetadata: []byte{0xa, 0xb},\n\t\tLastModifyingWriter: \"uid1\",\n\t\tWriters: []keybase1.UID{\"uid1\", \"uid2\"},\n\t\tID: tlf.FakeID(1, false),\n\t\tBID: NullBranchID,\n\t\tWFlags: 0xa,\n\t\tDiskUsage: 100,\n\t\tRefBytes: 99,\n\t\tUnrefBytes: 101,\n\t}\n\n\tc := kbfscodec.NewMsgpack()\n\n\tvar wm WriterMetadataV2\n\terr := c.Decode(encodedWm, &wm)\n\trequire.NoError(t, err)\n\n\trequire.Equal(t, expectedWm, wm)\n\n\tbuf, err := c.Encode(wm)\n\trequire.NoError(t, err)\n\trequire.Equal(t, encodedWm, buf)\n}", "func Test_ParseFrame(t *testing.T) {\n\tdata := [][]byte{\n\t\t{0x10, 0x81, 0x0, 0x0, 0x05, 0xff, 0x01, 0x01, 0x30, 0x01, 0x62, 0x02, 0xbb, 0x00, 0xbe, 0x00},\n\t}\n\n\tgot, err := ParseFrame(data[0])\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tlog.Printf(\"[%v] %v\\n\", \"\", got)\n\n\twant := Frame{\n\t\tData: Data{0x10, 0x81, 0x0, 0x0, 0x05, 0xff, 0x01, 0x01, 0x30, 0x01, 0x62, 0x02, 0xbb, 0x00, 0xbe, 0x00},\n\t\tEHD: Data{0x10, 0x81},\n\t\tTID: Data{0x00, 0x00},\n\t\tEData: Data{0x05, 0xff, 0x01, 0x01, 0x30, 0x01, 0x62, 0x02, 0xbb, 0x00, 0xbe, 0x00},\n\t\tSEOJ: Data{0x05, 0xff, 0x01},\n\t\tDEOJ: Data{0x01, 0x30, 0x01},\n\t\tESV: ESVType(0x62),\n\t\tOPC: Data{0x02},\n\t\tProperties: []Property{\n\t\t\t{Code: 0xbb, Len: 0, Data: []byte{}},\n\t\t\t{Code: 0xbe, Len: 0, Data: []byte{}},\n\t\t},\n\t}\n\n\tif diff := cmp.Diff(want, got); diff != \"\" {\n\t\tt.Errorf(\"ParseFrame differs: (-want +got)\\n%s\", diff)\n\t}\n}", "func encodeDecode(t *testing.T, fileName, filterName string) {\n\tt.Helper()\n\n\tt.Logf(\"testFile: %s with filter:%s\\n\", fileName, filterName)\n\n\tf, err := filter.NewFilter(filterName, nil)\n\tif err != nil {\n\t\tt.Errorf(\"Problem: %v\\n\", err)\n\t}\n\n\traw, err := os.Open(fileName)\n\tif err != nil {\n\t\tt.Errorf(\"%s: %v\", fileName, err)\n\t\treturn\n\t}\n\tdefer raw.Close()\n\n\tenc, err := f.Encode(raw)\n\tif err != nil {\n\t\tt.Errorf(\"Problem encoding: %v\\n\", err)\n\t}\n\n\tdec, err := f.Decode(enc)\n\tif err != nil {\n\t\tt.Errorf(\"Problem decoding: %v\\n\", err)\n\t}\n\n\t// Compare decoded bytes with original bytes.\n\tgolden, err := os.Open(fileName)\n\tif err != nil {\n\t\tt.Errorf(\"%s: %v\", fileName, err)\n\t\treturn\n\t}\n\tdefer golden.Close()\n\n\tg, err := io.ReadAll(golden)\n\tif err != nil {\n\t\tt.Errorf(\"%s: %v\", fileName, err)\n\t\treturn\n\t}\n\n\td, err := io.ReadAll(dec)\n\tif err != nil {\n\t\tt.Errorf(\"%s: %v\", fileName, err)\n\t\treturn\n\t}\n\n\tif len(d) != len(g) {\n\t\tt.Errorf(\"%s: length mismatch %d != %d\", fileName, len(d), len(g))\n\t\treturn\n\t}\n\n\tfor i := 0; i < len(d); i++ {\n\t\tif d[i] != g[i] {\n\t\t\tt.Errorf(\"%s: mismatch at %d, 0x%02x != 0x%02x\\n\", fileName, i, d[i], g[i])\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func (c *DubboTestCodec) Decode(data []byte) (*remoting.DecodeResult, int, error) {\n\tif c.isRequest(data) {\n\t\treq, len, err := c.decodeRequest(data)\n\t\tif err != nil {\n\t\t\treturn &remoting.DecodeResult{}, len, perrors.WithStack(err)\n\t\t}\n\t\treturn &remoting.DecodeResult{IsRequest: true, Result: req}, len, perrors.WithStack(err)\n\t} else {\n\t\tresp, len, err := c.decodeResponse(data)\n\t\tif err != nil {\n\t\t\treturn &remoting.DecodeResult{}, len, perrors.WithStack(err)\n\t\t}\n\t\treturn &remoting.DecodeResult{IsRequest: false, Result: resp}, len, perrors.WithStack(err)\n\t}\n}", "func Decode(src []byte) (dst [10]byte)", "func TestTableSection(t *testing.T) {\n testCases := []struct{\n name string\n encoded []byte\n decoded TableSection\n status error\n }{\n // Normal decode, min only\n { \"decode1\",\n []byte{ 0x01, 0x70, 0x00, 0x01 },\n TableSection{\n []Table{\n { Limit{ 0x01, 0 }, 0x70 },\n },\n },\n nil },\n\n // Normal decode, min + max\n { \"decodeAB\",\n []byte{ 0x01, 0x70, 0x01, 0x0A, 0x0B },\n TableSection{\n []Table{\n { Limit{ 0x0A, 0x0B }, 0x70 },\n },\n },\n nil },\n\n // Normal decode, min only, 2 tables\n { \"decode2\",\n []byte{ 0x02, 0x70, 0x00, 0x01, 0x6F, 0x00, 0x02 },\n TableSection{\n []Table{\n { Limit{ 0x01, 0 }, 0x70 },\n { Limit{ 0x02, 0 }, 0x6F },\n },\n },\n nil },\n }\n\n for _, test := range testCases {\n t.Run(test.name, func(t *testing.T) {\n section, err := readTableSection(test.encoded)\n if (err != test.status) {\n t.Error(\"Unexpected decoding status: \", err)\n }\n if (err == nil) {\n if (len(section.table) != len(test.decoded.table)) {\n t.Error(\"Unexpected decoded length: \", section)\n }\n\n // Assume each successful decode has at least 1 table\n if (section.table[0] != test.decoded.table[0]) {\n t.Error(\"Unexpected decoded table[0]: \", section)\n }\n }\n })\n }\n}", "func testRoundTripUint32(t *testing.T, encoder func([]byte, []uint32) int, decoder func([]uint32, []byte), data []uint32, expectedSize int) {\n\tencodedRaw := make([]byte, MaxSize32(len(data)))\n\tencodedSize := encoder(encodedRaw, data)\n\tif expectedSize >= 0 && encodedSize != expectedSize {\n\t\tt.Errorf(\"got encodedSize: %d, expected: %d\", encodedSize, expectedSize)\n\t}\n\tencoded := make([]byte, encodedSize, encodedSize) // ensure the encoded size is precise\n\tcopy(encoded, encodedRaw)\n\tdecodedData := make([]uint32, len(data), len(data))\n\tdecoder(decodedData, encoded)\n\tfor i := range data {\n\t\tif decodedData[i] != data[i] {\n\t\t\tt.Errorf(\"got decodedData[%d]: %d, expected: %d\", i, decodedData[i], data[i])\n\t\t}\n\t}\n}", "func test() {\n\to := decode(\"101\")\n\tfmt.Println(o, \"== 1\")\n\to = decode(\"111\")\n\tfmt.Println(o, \"== 3\")\n\to = decode(\"12\")\n\tfmt.Println(o, \"== 2\")\n\to = decode(\"27\")\n\tfmt.Println(o, \"== 1\")\n}", "func RunCodecTest(t *testing.T, cases []CodecTestCase) {\n\tt.Helper()\n\n\tfor _, c := range cases {\n\t\tt.Run(c.Name, func(t *testing.T) {\n\t\t\tt.Run(\"decode\", func(t *testing.T) {\n\t\t\t\t// create a new instance of the same type as c.Struct\n\t\t\t\ttyp := reflect.ValueOf(c.Struct).Type()\n\t\t\t\tvar v reflect.Value\n\t\t\t\tswitch typ.Kind() {\n\t\t\t\tcase reflect.Ptr:\n\t\t\t\t\tv = reflect.New(typ.Elem()) // typ: *struct, v: *struct\n\t\t\t\tcase reflect.Slice:\n\t\t\t\t\tv = reflect.New(typ) // typ: []x, v: *[]x\n\t\t\t\tdefault:\n\t\t\t\t\tt.Fatalf(\"%T is not a pointer or a slice\", c.Struct)\n\t\t\t\t}\n\n\t\t\t\tif _, err := ua.Decode(c.Bytes, v.Interface()); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\t// if v is a *[]x we need to dereference it before comparing it.\n\t\t\t\tif typ.Kind() == reflect.Slice {\n\t\t\t\t\tv = v.Elem()\n\t\t\t\t}\n\t\t\t\tverify.Values(t, \"\", v.Interface(), c.Struct)\n\t\t\t})\n\n\t\t\tt.Run(\"encode\", func(t *testing.T) {\n\t\t\t\tb, err := ua.Encode(c.Struct)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t\tverify.Values(t, \"\", b, c.Bytes)\n\t\t\t})\n\t\t})\n\t}\n}", "func TestPbEncoderAndDecoder(t *testing.T) {\n\tregister(0, reflect.TypeOf(example.A{}))\n\n\tbuf := new(bytes.Buffer)\n\n\tinPb := &example.A{\n\t\tDescription: \"hello world!\",\n\t\tNumber: 1,\n\t}\n\t// UUID is 16 byte long\n\tfor i := 0; i < 16; i++ {\n\t\tinPb.Id = append(inPb.Id, byte(i))\n\t}\n\n\tmsg := NewPbMessage(0, inPb)\n\n\te := NewMsgEncoder(buf)\n\te.EncodePb(msg)\n\n\toutMsg := NewEmptyPbMessage()\n\n\td := NewMsgDecoder(buf)\n\terr := d.DecodePb(outMsg)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif !reflect.DeepEqual(msg, outMsg) {\n\t\tt.Fatal(\"Messages are not equal!\")\n\t}\n\n\tif !reflect.DeepEqual(inPb, outMsg.pb) {\n\t\tt.Fatal(\"Protos are not equal!\")\n\t}\n}", "func DecodePayload(payload []byte) (*TKAQ, error) {\n\treturn &TKAQ{\n\t\tTimestamp: decodeFloat(payload[0:4]),\n\t\tLong: decodeFloat(payload[4:8]),\n\t\tLat: decodeFloat(payload[8:12]),\n\t\tAltitude: decodeFloat(payload[12:16]),\n\t\tRelativeHumidity: decodeFloat(payload[16:20]),\n\t\tTemperature: decodeFloat(payload[20:24]),\n\t\tStatus: payload[24],\n\t\tCO2PPM: decodeUint16(payload[25:27]),\n\t\tTVOCPPB: decodeUint16(payload[27:29]),\n\t\tPM10: decodeUint16(payload[33:35]),\n\t\tPM25: decodeUint16(payload[35:37]),\n\t}, nil\n}", "func decodeData(data string, encodedType Encode) ([]byte, error) {\n\tvar keyDecoded []byte\n\tvar err error\n\tswitch encodedType {\n\tcase None:\n\t\tkeyDecoded = []byte(data)\n\tcase HEX:\n\t\tkeyDecoded, err = hex.DecodeString(data)\n\tcase Base64:\n\t\tkeyDecoded, err = base64.StdEncoding.DecodeString(data)\n\tdefault:\n\t\treturn keyDecoded, fmt.Errorf(\"secretInfo PublicKeyDataType unsupport\")\n\t}\n\treturn keyDecoded, err\n}", "func TestAssertEqualBytes(t *testing.T) {\n\tdata := []byte{9, 9, 1, 1, 1, 9, 9}\n\tassertBytesEqual(t, data, data, \"Self\")\n\tassertBytesEqual(t, data[1:4], data[1:4], \"Self\")\n\tassertBytesEqual(t, []byte{1, 1}, []byte{1, 1}, \"Simple match\")\n\tassertBytesEqual(t, []byte{1, 2, 3}, []byte{1, 2, 3}, \"content mismatch\")\n\tassertBytesEqual(t, []byte{1, 1, 1}, data[2:5], \"slice match\")\n}", "func TestAddToSecretFromDataBase64EncodesInput(t *testing.T) {\n\tt.Parallel()\n\n\tcontents := random.UniqueId()\n\tsecret := PrepareSecret(\n\t\t\"test-namespace\",\n\t\t\"test-name\",\n\t\tmap[string]string{},\n\t\tmap[string]string{},\n\t)\n\tAddToSecretFromData(secret, \"data\", []byte(contents))\n\tassert.Equal(t, secret.Data[\"data\"], []byte(contents))\n}", "func Test(t *testing.T) {\n\ttype Movie struct {\n\t\tTitle, Subtitle string\n\t\tYear int\n\t\tActor map[string]string\n\t\tOscars []string\n\t\tSequel *string\n\t}\n\tstrangelove := Movie{\n\t\tTitle: \"Dr. Strangelove\",\n\t\tSubtitle: \"How I Learned to Stop Worrying and Love the Bomb\",\n\t\tYear: 1964,\n\t\tActor: map[string]string{\n\t\t\t\"Dr. Strangelove\": \"Peter Sellers\",\n\t\t\t\"Grp. Capt. Lionel Mandrake\": \"Peter Sellers\",\n\t\t\t\"Pres. Merkin Muffley\": \"Peter Sellers\",\n\t\t\t\"Gen. Buck Turgidson\": \"George C. Scott\",\n\t\t\t\"Brig. Gen. Jack D. Ripper\": \"Sterling Hayden\",\n\t\t\t`Maj. T.J. \"King\" Kong`: \"Slim Pickens\",\n\t\t},\n\t\tOscars: []string{\n\t\t\t\"Best Actor (Nomin.)\",\n\t\t\t\"Best Adapted Screenplay (Nomin.)\",\n\t\t\t\"Best Director (Nomin.)\",\n\t\t\t\"Best Picture (Nomin.)\",\n\t\t},\n\t}\n\n\t// Encode it\n\tdata, err := Marshal(strangelove)\n\tif err != nil {\n\t\tt.Fatalf(\"Marshal failed: %v\", err)\n\t}\n\tt.Logf(\"Marshal() = %s\\n\", data)\n\n\t// Decode it\n\tvar movie Movie\n\tif err := Unmarshal(data, &movie); err != nil {\n\t\tt.Fatalf(\"Unmarshal failed: %v\", err)\n\t}\n\tt.Logf(\"Unmarshal() = %+v\\n\", movie)\n\n\t// Check equality.\n\tif !reflect.DeepEqual(movie, strangelove) {\n\t\tt.Fatal(\"not equal\")\n\t}\n\n\t// Pretty-print it:\n\tdata, err = MarshalIndent(strangelove)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Logf(\"MarshalIdent() = %s\\n\", data)\n}", "func bytesDecode(raw []byte) (*encryptedData, error) {\n\tmacLen := 32\n\tivLen := 16\n\tif len(raw) == 0 {\n\t\treturn nil, errors.Errorf(\"raw must not be empty\")\n\t}\n\n\tif len(raw) < macLen+ivLen+pubKeyBytesLenCompressed+1 {\n\t\treturn nil, errors.Errorf(\"raw data does not have enough bytes to be encoded\")\n\t}\n\n\tif raw[0] != cipher.AES256CBC {\n\t\treturn nil, errors.Errorf(\"invalid prefix\")\n\t}\n\traw = raw[1:]\n\tdecompressedKey := decompress(raw[ivLen : ivLen+pubKeyBytesLenCompressed])\n\t// iv and mac must be created this way to ensure the cap of the array is not different\n\tiv := make([]byte, ivLen)\n\tcopy(iv, raw[:ivLen])\n\tmac := make([]byte, macLen)\n\tcopy(mac, raw[ivLen+pubKeyBytesLenCompressed:ivLen+pubKeyBytesLenCompressed+macLen])\n\n\tret := &encryptedData{\n\t\tInitializationVector: iv,\n\t\tEphemeralPublicKey: decompressedKey,\n\t\tMessageAuthenticationCode: mac,\n\t\tCiphertext: raw[ivLen+pubKeyBytesLenCompressed+macLen:],\n\t}\n\tif err := ret.verify(); err != nil {\n\t\treturn nil, errors.WithMessage(err, \"encrypted data is invalid\")\n\t}\n\n\treturn ret, nil\n}", "func TestConnectDecodeEncodeEquiv(t *testing.T) {\n\tmsgBytes := []byte{\n\t\tbyte(CONNECT << 4),\n\t\t60,\n\t\t0, // Length MSB (0)\n\t\t4, // Length LSB (4)\n\t\t'M', 'Q', 'T', 'T',\n\t\t4, // Protocol level 4\n\t\t206, // connect flags 11001110, will QoS = 01\n\t\t0, // Keep Alive MSB (0)\n\t\t10, // Keep Alive LSB (10)\n\t\t0, // Client ID MSB (0)\n\t\t7, // Client ID LSB (7)\n\t\t's', 'u', 'r', 'g', 'e', 'm', 'q',\n\t\t0, // Will Topic MSB (0)\n\t\t4, // Will Topic LSB (4)\n\t\t'w', 'i', 'l', 'l',\n\t\t0, // Will Message MSB (0)\n\t\t12, // Will Message LSB (12)\n\t\t's', 'e', 'n', 'd', ' ', 'm', 'e', ' ', 'h', 'o', 'm', 'e',\n\t\t0, // Username ID MSB (0)\n\t\t7, // Username ID LSB (7)\n\t\t's', 'u', 'r', 'g', 'e', 'm', 'q',\n\t\t0, // Password ID MSB (0)\n\t\t10, // Password ID LSB (10)\n\t\t'v', 'e', 'r', 'y', 's', 'e', 'c', 'r', 'e', 't',\n\t}\n\n\tmsg := NewConnectMessage()\n\tn, err := msg.Decode(msgBytes)\n\n\trequire.NoError(t, err, \"Error decoding message.\")\n\trequire.Equal(t, len(msgBytes), n, \"Error decoding message.\")\n\n\tdst := make([]byte, 100)\n\tn2, err := msg.Encode(dst)\n\n\trequire.NoError(t, err, \"Error decoding message.\")\n\trequire.Equal(t, len(msgBytes), n2, \"Error decoding message.\")\n\trequire.Equal(t, msgBytes, dst[:n2], \"Error decoding message.\")\n\n\tn3, err := msg.Decode(dst)\n\n\trequire.NoError(t, err, \"Error decoding message.\")\n\trequire.Equal(t, len(msgBytes), n3, \"Error decoding message.\")\n}", "func TestRepackEventABIWithTopics(t *testing.T) {\n\tjsonAbi := `[{\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"name\": \"a\",\n \"type\": \"uint256\"\n },\n {\n \"indexed\": false,\n \"name\": \"b\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"name\": \"c\",\n \"type\": \"bytes20\"\n },\n {\n \"indexed\": false,\n \"name\": \"d\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"MyEvent\",\n \"type\": \"event\"\n }]`\n\n\tparsedABI, err := abi.JSON(strings.NewReader(jsonAbi))\n\trequire.NoError(t, err, \"failed parsing ABI\")\n\n\tlog := &adapter.TransactionLog{\n\t\tPackedTopics: [][]byte{unique32BytesFor(11), unique32BytesFor(22), unique32BytesFor(33)},\n\t\tData: append(unique32BytesFor(44), unique32BytesFor(55)...),\n\t}\n\n\tres, err := repackEventABIWithTopics(parsedABI.Events[\"MyEvent\"], log)\n\trequire.NoError(t, err, \"failed to run repackEventABIWithTopics\")\n\n\trequire.Equal(t, unique32BytesFor(22), get32BytesAtIndex(res, 0))\n\trequire.Equal(t, unique32BytesFor(44), get32BytesAtIndex(res, 1))\n\trequire.Equal(t, unique32BytesFor(33), get32BytesAtIndex(res, 2))\n\trequire.Equal(t, unique32BytesFor(55), get32BytesAtIndex(res, 3))\n}" ]
[ "0.7281458", "0.6913997", "0.6887471", "0.65974265", "0.658577", "0.6559383", "0.64981526", "0.64610136", "0.6437047", "0.6213342", "0.6192326", "0.61338687", "0.6059971", "0.60194135", "0.59999216", "0.5964416", "0.5939682", "0.5885714", "0.5879129", "0.5861864", "0.58497125", "0.5818779", "0.5795533", "0.57720006", "0.5736795", "0.5727014", "0.56949514", "0.56711924", "0.5665765", "0.5658176", "0.56553406", "0.56551063", "0.5639878", "0.5615923", "0.55984807", "0.55699325", "0.553991", "0.5539089", "0.5529287", "0.54974055", "0.5488126", "0.54777694", "0.5452465", "0.5439874", "0.54382336", "0.5433286", "0.5428946", "0.5408752", "0.53932285", "0.5371038", "0.53649104", "0.53593624", "0.5357561", "0.5320092", "0.5303427", "0.5302631", "0.5296066", "0.5290385", "0.5285067", "0.5282764", "0.52795184", "0.5279339", "0.52723163", "0.52629286", "0.5261407", "0.5258918", "0.5241399", "0.52292454", "0.52253395", "0.52081203", "0.52081203", "0.5186305", "0.5183027", "0.5178792", "0.51771945", "0.51766163", "0.51750827", "0.51738745", "0.5139072", "0.5129457", "0.5119864", "0.511065", "0.5108438", "0.51005936", "0.50984997", "0.5096903", "0.5088477", "0.508834", "0.50564456", "0.5030136", "0.5003522", "0.49858803", "0.49834722", "0.49789724", "0.49754357", "0.49708086", "0.49680015", "0.49678135", "0.49557203", "0.4955455", "0.49552888" ]
0.0
-1
ConcatSlice Returns a Concatenanted byte array into string
func ConcatSlice(sliceToConcat []byte) string { var dummy string for index := 0; index < len(sliceToConcat)-1; index++ { dummy = dummy + string(sliceToConcat[index]) + "-" } dummy = dummy + string(sliceToConcat[len(sliceToConcat)-1]) return dummy }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ConcatSlice(sliceToConcat []byte) string {\n\tstringRep := \"\"\n\n\tfor index := 0; index < len(sliceToConcat); index++ {\n\t\tstringRep = stringRep + string(sliceToConcat[index])\n\n\t\tif index+1 != len(sliceToConcat) {\n\t\t\tstringRep = stringRep + \"-\"\n\t\t}\n\t}\n\n\treturn stringRep\n}", "func ConcatenateBytes(data ...[]byte) []byte {\n\tfinalLength := 0\n\tfor _, slice := range data {\n\t\tfinalLength += len(slice)\n\t}\n\tresult := make([]byte, finalLength)\n\tlast := 0\n\tfor _, slice := range data {\n\t\tfor i := range slice {\n\t\t\tresult[i+last] = slice[i]\n\t\t}\n\t\tlast += len(slice)\n\t}\n\treturn result\n}", "func ConcatByteSlices(arrays ...[]byte) []byte {\n\treturn concatByteSlices(arrays...)\n}", "func (s *SliceOfByte) Concat(items []byte) *SliceOfByte {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func concat(a string, b string) string {\n\tvals := make([]byte, 0, 10)\n\tvals = append(vals, a...)\n\tvals = append(vals, b...)\n\treturn string(vals)\n}", "func (s *SliceOfUint8) Concat(items []uint8) *SliceOfUint8 {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func Concat(in []string) (rv string) {\n\n\tswitch len(in) {\n\n\tcase 0:\n\t\treturn \"\"\n\n\tcase 1:\n\t\treturn in[0]\n\n\tcase 2:\n\t\treturn in[0] + in[1]\n\n\tcase 3:\n\t\treturn in[0] + in[1] + in[2]\n\t}\n\n\tn := 0\n\n\tfor i := 0; i < len(in); i++ {\n\t\tn += len(in[i])\n\t}\n\n\tb := make([]byte, n)\n\n\tbp := copy(b, in[0])\n\n\tfor _, s := range in[1:] {\n\t\tbp += copy(b[bp:], s)\n\t}\n\n\treturn string(b)\n}", "func AppendByte(slice []byte, data ...byte) []byte {\n m := len(slice)\n n := m + len(data)\n if n > cap(slice) { // if necessary, reallocate\n // allocate double what's needed, for future growth.\n newSlice := make([]byte, (n+1)*2)\n copy(newSlice, slice)\n slice = newSlice\n }\n\tfmt.Println(slice)\n slice = slice[0:n]\n\tfmt.Println(slice)\n\tfmt.Println(slice[m:n])\n copy(slice[m:n], data)\n\tfmt.Println(slice)\n return slice\n}", "func (c *Client) Concat(ctx context.Context, p *ConcatPayload) (res string, err error) {\n\tvar ires any\n\tires, err = c.ConcatEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(string), nil\n}", "func CopySlice(slice []byte) []byte {\n\tcopy := append(slice[:0:0], slice...)\n\treturn copy\n}", "func joinBytes(args ...[]byte) []byte {\n\treturn bytes.Join(args, []byte{})\n}", "func Concat(size int, arrays ...[]byte) ([]byte, error) {\n\tarr := make([]byte, size)\n\ti := 0\n\tfor _, array := range arrays {\n\t\tfor _, b := range array {\n\t\t\tarr[i] = b\n\t\t\ti++\n\t\t}\n\t}\n\tif i != size {\n\t\treturn nil, fmt.Errorf(\"size argument does not match %d vs %d\", size, i)\n\t}\n\treturn arr, nil\n}", "func append(arr1 []byte, arr2 []byte) []byte {\n\tarr1Len := len(arr1);\n\tnewLen := len(arr1) + len(arr2);\n\tresult := make([]byte, newLen);\n\t\n\tfor i:= 0; i < arr1Len; i++ {\n\t\tresult[i] = arr1[i];\n\t};\n\t\n\tfor i := 0; i < len(arr2); i++ {\n\t\tresult[i + arr1Len] = arr2[i];\n\t};\n\treturn result;\n}", "func BytesCombine(pBytes ...[]byte) []byte {\n\treturn bytes.Join(pBytes, []byte(\"\"))\n}", "func ExtendByteSlice(b []byte, needLen int) []byte {\n\treturn bytes.Extend(b, needLen)\n}", "func testAppendStringToByteSlice() {\n\tfmt.Println(\"testAppendStringToByteSlice\")\n\ts := []byte(\"hello\")\n\ts = append(s, \" world\"...)\n\tfmt.Println(s)\n\tfmt.Println()\n}", "func (s Slice) Prepend(elems ...byte) Slice {\n\tpad := len(elems)\n\tif pad%wordSize != 0 || pad > s.Pad() {\n\t\tl := wordSize + len(elems) + len(s)\n\t\treturn append(append(make([]byte, wordSize, l), elems...), s...)[wordSize:]\n\t}\n\n\thdr := (*reflect.SliceHeader)(unsafe.Pointer(&s))\n\thdr.Data -= uintptr(pad)\n\thdr.Cap += pad\n\thdr.Len += pad\n\n\tcopy(s, elems)\n\treturn s\n}", "func byteSliceToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}", "func (s *SliceOfInt8) Concat(items []int8) *SliceOfInt8 {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func (s *SliceOfUint) Concat(items []uint) *SliceOfUint {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func Concat(args ...interface{}) (out []byte) {\n\tfor _, arg := range args {\n\t\tswitch v := arg.(type) {\n\t\tcase string:\n\t\t\tout = append(out, []byte(v)...)\n\t\tcase []byte:\n\t\t\tout = append(out, v...)\n\t\t}\n\t}\n\treturn out\n}", "func multiAppend(slices ...[]byte) []byte {\n\tvar length int\n\tfor _, s := range slices {\n\t\tlength += len(s)\n\t}\n\ttmp := make([]byte, length)\n\tvar i int\n\tfor _, s := range slices {\n\t\ti += copy(tmp[i:], s)\n\t}\n\treturn tmp\n}", "func (s *SliceOfString) Concat(items []string) *SliceOfString {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func ConcatCopyPreAllocate(slices [][]byte) []byte {\n\tvar totalLen int\n\tfor _, s := range slices {\n\t\ttotalLen += len(s)\n\t}\n\ttmp := make([]byte, totalLen)\n\tvar i int\n\tfor _, s := range slices {\n\t\ti += copy(tmp[i:], s)\n\t}\n\treturn tmp\n}", "func SliceBytes(a []byte, fn func([]byte)) {\n\tpermutationsBytes(a, 0, fn)\n}", "func byteSlice(ns []uint32) []byte {\n\tb := make([]byte, len(ns))\n\tfor i, n := range ns {\n\t\tb[i] = byte(n)\n\t}\n\treturn b\n}", "func (b *Buffer) Slice() []byte {\n\t// Skip IP and UDP headers\n\treturn b[(ipv4HeaderSize + udp4HeaderSize):]\n}", "func cByteSlice(b []byte) *C.char {\n\tvar c *C.char\n\tif len(b) > 0 {\n\t\tcData := C.malloc(C.size_t(len(b)))\n\t\tcopy((*[1 << 24]byte)(cData)[0:len(b)], b)\n\t\tc = (*C.char)(cData)\n\t}\n\treturn c\n}", "func CopySlice(b []byte) []byte {\n\tnewB := make([]byte, len(b))\n\tcopy(newB, b)\n\treturn newB\n}", "func ByteSliceToString(b []byte) string {\n\ts := \"\"\n\tsliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))\n\tstringHeader := (*reflect.StringHeader)(unsafe.Pointer(&s))\n\tstringHeader.Data = sliceHeader.Data\n\tstringHeader.Len = sliceHeader.Len\n\treturn s\n}", "func slicetostr(buf []uint8) string {\n\tend := 0\n\tfor i := range buf {\n\t\tend = i\n\t\tif buf[i] == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn string(buf[:end])\n}", "func (slice ByteSlice) Append(data []byte) []byte {\r\n\tl := len(slice)\r\n\tif l + len(data) > cap(slice) { //reallocated\r\n\t\t// Allocate double what's needed, for future growth\r\n\t\tnewSlice := make([]byte, (l + len(data))*2)\r\n\t\t// The copy function is predeclared and works for any slice type.\r\n\t\tcopy(newSlice, slice)\r\n\t\tslice = newSlice\r\n\t}\r\n\tslice = slice[0:l + len(data)]\r\n\tfor i, c := range data{\r\n\t\tslice[l+i] = c\r\n\t}\r\n\treturn slice\r\n}", "func copySlice(a []byte) []byte {\n\trv := make([]byte, len(a))\n\tcopy(rv, a)\n\treturn rv\n}", "func (s *SliceOfUint16) Concat(items []uint16) *SliceOfUint16 {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func AppendByte(slice []byte, data ...byte) []byte {\n\tm := len(slice)\n\tn := m + len(data)\n\tif n > cap(slice) { // if necessary, reallocate\n\t\t// allocate double what's needed, for future growth.\n\t\tnewSlice := make([]byte, (n+1)*2)\n\t\tcopy(newSlice, slice)\n\t\tslice = newSlice\n\t}\n\tslice = slice[0:n]\n\tcopy(slice[m:n], data)\n\treturn slice\n}", "func (b byteSlice) ToString() string {\n\tvar a []string\n\tfor _, by := range b {\n\t\ta = append(a, string(by))\n\t}\n\n\treturn strings.Join(a, \" \")\n}", "func SliceByteToString(b []byte) string {\n\tbh := (*reflect.SliceHeader)(unsafe.Pointer(&b))\n\tsh := reflect.StringHeader{\n\t\tData: bh.Data,\n\t\tLen: bh.Len,\n\t}\n\treturn *(*string)(unsafe.Pointer(&sh))\n}", "func copySlice(s []byte) []byte {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tb := make([]byte, len(s))\n\tcopy(b, s)\n\treturn b\n}", "func appendOne(arr1 []byte, oneByte byte) []byte {\n\tresult := make([]byte, len(arr1) + 1);\n\tfor i:= 0; i < len(arr1); i++ {\n\t\tresult[i] = arr1[i];\n\t};\n\tresult[len(result) - 1] = oneByte;\n\treturn result;\n}", "func Concat(x string, y string) (z bytes.Buffer) {\n\tz.Write([]byte(x))\n\tz.Write([]byte(y))\n\treturn\n}", "func moveSliceToBytes(s *gorocksdb.Slice) []byte {\n\tdefer s.Free()\n\tif !s.Exists() {\n\t\treturn nil\n\t}\n\tv := make([]byte, len(s.Data()))\n\tcopy(v, s.Data())\n\treturn v\n}", "func moveSliceToBytes(s *gorocksdb.Slice) []byte {\n\tdefer s.Free()\n\tif !s.Exists() {\n\t\treturn nil\n\t}\n\tv := make([]byte, len(s.Data()))\n\tcopy(v, s.Data())\n\treturn v\n}", "func (s *SliceOfUint64) Concat(items []uint64) *SliceOfUint64 {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func WriteSlice(buffer []byte, offset int, value []byte, valueOffset int, valueSize int) {\n copy(buffer[offset:offset + len(value)], value[valueOffset:valueOffset + valueSize])\n}", "func (c StringArrayCollection) Concat(value interface{}) Collection {\n\tvar d = make([]string, len(c.value))\n\tcopy(d, c.value)\n\treturn StringArrayCollection{\n\t\tvalue: append(d, value.([]string)...),\n\t\tBaseCollection: BaseCollection{length: c.length + len(value.([]string))},\n\t}\n}", "func getString(log log.T, byteArray []byte, offset int, stringLength int) (result string, err error) {\n\tbyteArrayLength := len(byteArray)\n\tif offset > byteArrayLength-1 || offset+stringLength-1 > byteArrayLength-1 || offset < 0 {\n\t\tlog.Error(\"getString failed: Offset is invalid.\")\n\t\treturn \"\", errors.New(\"Offset is outside the byte array.\")\n\t}\n\n\t//remove nulls from the bytes array\n\tb := bytes.Trim(byteArray[offset:offset+stringLength], \"\\x00\")\n\n\treturn strings.TrimSpace(string(b)), nil\n}", "func ConcatString(left []string, right []string) []string {\n\tresult := make([]string, 0)\n\tresult = append(result, left...)\n\tresult = append(result, right...)\n\treturn result\n}", "func (b bit128) toByteSlice() []byte {\n\tdst := make([]byte, 16)\n\t_ = dst[15]\n\tbinary.BigEndian.PutUint64(dst[0:8], b[0])\n\tbinary.BigEndian.PutUint64(dst[8:16], b[1])\n\treturn dst\n}", "func (bs ByteSlice) String() string {\n\treturn hex.EncodeToString([]byte(bs))\n}", "func duplicateSlice(data []byte) []byte {\n\tresult := make([]byte, len(data))\n\tcopy(result, data)\n\treturn result\n}", "func Append(slice []int, byte_array []byte) ([]int, bool) {\n\tif len(byte_array) > cap(slice)-len(slice) {\n\t\treturn nil, true\n\t}\n\ts := make([]int, len(slice)+len(byte_array))\n\tcopy(s, slice)\n\tfor i := 0; i < len(byte_array); i++ {\n\t\ts[len(slice)+int(i)] = int(byte_array[i])\n\t}\n\treturn s, false\n}", "func (s *SliceOfInt16) Concat(items []int16) *SliceOfInt16 {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func (s *SliceOfByte) Append(item byte) *SliceOfByte {\n\ts.items = append(s.items, item)\n\treturn s\n}", "func StringBytes(b []byte) string { return *(*string)(Pointer(&b)) }", "func ByteSlice(s string) []byte {\n\tsh := *(*StringHeader)(unsafe.Pointer(&s))\n\tbh := SliceHeader{\n\t\tData: sh.Data,\n\t\tLen: sh.Len,\n\t\tCap: sh.Len,\n\t}\n\n\treturn *(*[]byte)(unsafe.Pointer(&bh))\n}", "func (s Slice) Append(elems ...byte) Slice {\n\tif cap(s) < len(s)+len(elems) {\n\t\tslice := append(make([]byte, wordSize), append(s, elems...)...)\n\t\treturn slice[wordSize:]\n\t}\n\treturn append(s, elems...)\n}", "func ConcatArray(array []string) string {\n\tvar buffer bytes.Buffer\n\tfor i := 0; i < len(array); i++ {\n\t\tbuffer.WriteString(array[i])\n\t\tif i <= len(array)-1 {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t}\n\treturn buffer.String()\n}", "func String(b []byte) (s string) {\n pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))\n pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))\n pstring.Data = pbytes.Data\n pstring.Len = pbytes.Len\n return\n}", "func (a *ArrayBytes) String() string {\n\tx := a.a\n\tformattedBytes := make([]string, len(x))\n\tfor i, v := range x {\n\t\tformattedBytes[i] = v.String()\n\t}\n\treturn strings.Join(formattedBytes, \",\")\n}", "func sliceForAppend(in []byte, n int) (head, tail []byte) {\n\tif total := len(in) + n; cap(in) >= total {\n\t\thead = in[:total]\n\t} else {\n\t\thead = make([]byte, total)\n\t\tcopy(head, in)\n\t}\n\ttail = head[len(in):]\n\treturn\n}", "func (s *SliceOfInterface) Concat(items []interface{}) *SliceOfInterface {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func (in *InBuffer) Slice(n int) []byte {\n\tr := in.Data[in.ReadPos : in.ReadPos+n]\n\tin.ReadPos += n\n\treturn r\n}", "func (in *InBuffer) Slice(n int) []byte {\n\tr := in.Data[in.ReadPos : in.ReadPos+n]\n\tin.ReadPos += n\n\treturn r\n}", "func (ad *stubAddService) Concat(ctx context.Context, a string, b string) (res string, err error) {\n\tres = a + b\n\terr = ad.nc.Publish(addTopic, []byte(res))\n\tif err != nil {\n\t\tlevel.Error(ad.logger).Log(\"method\", \"ad.nc.Publish\", \"value\", res, \"err\", err)\n\t\treturn\n\t}\n\n\treturn res, err\n}", "func (jbobject *JavaNioCharBuffer) Slice() *JavaNioCharBuffer {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"slice\", \"java/nio/CharBuffer\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tretconv := javabind.NewJavaToGoCallable()\n\tdst := &javabind.Callable{}\n\tretconv.Dest(dst)\n\tif err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {\n\t\tpanic(err)\n\t}\n\tretconv.CleanUp()\n\tunique_x := &JavaNioCharBuffer{}\n\tunique_x.Callable = dst\n\treturn unique_x\n}", "func (s *SliceOfUint32) Concat(items []uint32) *SliceOfUint32 {\n\ts.items = append(s.items, items...)\n\treturn s\n}", "func (i *Iter) returnSlice(a, b int) []byte {\n\tif i.rb.src.bytes == nil {\n\t\treturn i.buf[:copy(i.buf[:], i.rb.src.str[a:b])]\n\t}\n\treturn i.rb.src.bytes[a:b]\n}", "func (b *ByteArray) WriteSlice() []byte {\n\tb.prepare()\n\treturn getSlice(b.writePos)\n}", "func bytesReassemble(b []byte, piecesLengthArray []int64) (data []byte) {\n\tvar length = int64(len(piecesLengthArray))\n\tvar bytLength = int64(len(b))\n\tvar sum int64\n\tfor _, piecesLength := range piecesLengthArray {\n\t\tsum += piecesLength\n\t}\n\n\tif sum != bytLength {\n\t\tpanic(fmt.Errorf(\"byes sum is not matched with sum of piecesLengthArray, %d != %d\", bytLength, sum))\n\t}\n\tdata = make([]byte, bytLength)\n\tvar oldStart, start, subLength int64\n\n\tfor i := length - 1; i >= 0; i-- {\n\t\tsubLength = piecesLengthArray[i]\n\t\toldStart = bytLength - subLength\n\t\tcopy(data[start:start+subLength], b[oldStart:oldStart+subLength])\n\t\tstart += subLength\n\t\tbytLength -= subLength\n\t}\n\n\treturn data\n}", "func slicetostr(s1 []int) string{\r\n\ts2 := strings.Replace(strings.Trim(fmt.Sprint(s1), \"[]\"), \" \", \"\", -1)\r\n\tfmt.Printf(\"the s2 is :%s\\n\",s2)\r\n\treturn s2\r\n}", "func SliceJoin(a []Stringer, sep string) string {\n\tswitch len(a) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn a[0].String()\n\tcase 2:\n\t\t// Special case for common small values.\n\t\t// Remove if golang.org/issue/6714 is fixed\n\t\treturn a[0].String() + sep + a[1].String()\n\tcase 3:\n\t\t// Special case for common small values.\n\t\t// Remove if golang.org/issue/6714 is fixed\n\t\treturn a[0].String() + sep + a[1].String() + sep + a[2].String()\n\t}\n\tn := len(sep) * (len(a) - 1)\n\tfor i := 0; i < len(a); i++ {\n\t\tn += len(a[i].String())\n\t}\n\n\tb := make([]byte, n)\n\tbp := copy(b, a[0].String())\n\tfor _, s := range a[1:] {\n\t\tbp += copy(b[bp:], sep)\n\t\tbp += copy(b[bp:], s.String())\n\t}\n\treturn string(b)\n}", "func (v DataSlice) String() string { return StringSlice(\", \", \"[\", \"]\", v.Slice()...) }", "func Slice(s string) (b []byte) {\n\tpbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))\n\tpstring := (*reflect.StringHeader)(unsafe.Pointer(&s))\n\tpbytes.Data = pstring.Data\n\tpbytes.Len = pstring.Len\n\tpbytes.Cap = pstring.Len\n\treturn\n}", "func String(b []byte) (s string) {\n\tpbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))\n\tpstring := (*reflect.StringHeader)(unsafe.Pointer(&s))\n\tpstring.Data = pbytes.Data\n\tpstring.Len = pbytes.Len\n\treturn\n}", "func appendRepeatedBytes(dst []byte, repeatedBytes []byte, number int) []byte {\n\tfor number > 0 {\n\t\tn := number\n\t\tif n > len(repeatedBytes) {\n\t\t\tn = len(repeatedBytes)\n\t\t}\n\t\tdst = append(dst, repeatedBytes[:n]...)\n\t\tnumber -= n\n\t}\n\treturn dst\n}", "func Concat(s, t []rune) []rune {\n\tn := make([]rune, 0, len(s)+len(t))\n\tn = append(n, s...)\n\tn = append(n, t...)\n\treturn n\n}", "func StringSlice(slice Slice) (str string) {\n\tsb := poolStringBuilder.Get().(*StringBuilder)\n\tsb.Grow(ceil32(ByteSizeJSONSlice(slice)))\n\tEncodeJSONSlice(sb, slice)\n\tstr = sb.String()\n\tsb.Reset()\n\tpoolStringBuilder.Put(sb)\n\treturn\n}", "func StringConcat(s1, s2 string) string {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(s1)\n\tbuffer.WriteString(s2)\n\treturn buffer.String()\n}", "func ByteSlice2String(bs []byte) string {\n\treturn *(*string)(unsafe.Pointer(&bs))\n}", "func cut(left, right byte, begin int, src []byte) (remain []byte, cut []byte) {\n\tstart := bytes.IndexByte(src[begin:], left)\n\tend := start + 1 + bytes.IndexByte(src[begin+start+1:], right)\n\tcut = make([]byte, end-start-1)\n\tcopy(cut, src[begin+start+1:begin+end])\n\tremain = append(src[:begin+start], src[begin+end+1:]...)\n\treturn\n}", "func BenchmarkConcatStrByAdd(b *testing.B) {\n\telements := []string{ \"1\", \"2\", \"3\", \"4\" }\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tret := \"\"\n\t\tfor _, element := range elements {\n\t\t\tret += element\n\t\t}\n\t}\n\tb.StopTimer()\n}", "func (s *SliceOfByte) Unshift(item byte) *SliceOfByte {\n\ts.items = append([]byte{item}, s.items...)\n\treturn s\n}", "func SpliceString(array []string, start int, length int, appends []string) {\n\tnewArray := make([]string, 0)\n\tleft := (array)[0:start]\n\tright := (array)[(start + length):len(array)]\n\tnewArray = append(newArray, left...)\n\tnewArray = append(newArray, appends...)\n\tnewArray = append(newArray, right...)\n\tarray = newArray\n}", "func rsCombinedBytes(rBytes, sBytes []byte, pubKey *ecdsa.PublicKey) ([]byte, error) {\n\tkeySize, err := ecdsakeyBytes(pubKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"RSCombinedBytes: ecdsa key bytes error %v\", err)\n\t}\n\trsize := len(rBytes)\n\tssize := len(sBytes)\n\tif rsize > keySize || ssize > keySize {\n\t\treturn nil, fmt.Errorf(\"RSCombinedBytes: error. keySize %v, rSize %v, sSize %v\", keySize, rsize, ssize)\n\t}\n\n\t// basically the size is 32 bytes. the r and s needs to be both left padded to two 32 bytes slice\n\t// into a single signature buffer\n\tbuffer := make([]byte, keySize*2)\n\tstartPos := keySize - rsize\n\tcopy(buffer[startPos:], rBytes)\n\tstartPos = keySize*2 - ssize\n\tcopy(buffer[startPos:], sBytes)\n\treturn buffer[:], nil\n}", "func ExampleConcat() {\n\tvar buf1 bytes.Buffer\n\tvar buf2 bytes.Buffer\n\n\tbuf1.WriteString(\"ciao\\n\")\n\tbuf1.WriteString(\"salve\\n\")\n\n\tbuf2.WriteString(\"Andre\\n\")\n\tbuf2.WriteString(\"Parro\\n\")\n\tbuf2.WriteString(\"The end\\n\")\n\n\terr := horzcat.Concat(horzcat.Options{\n\t\tSep: \",\",\n\t\tTail: \"!\",\n\t}, &buf1, &buf2)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// Output: ciao,Andre!\n\t// salve,Parro!\n\t// The end!\n}", "func bytesToString(bytes []byte) (s string) {\n\tslice := (*reflect.SliceHeader)(unsafe.Pointer(&bytes))\n\tstr := (*reflect.StringHeader)(unsafe.Pointer(&s))\n\tstr.Data = slice.Data\n\tstr.Len = slice.Len\n\treturn s\n}", "func bytesToString(bytes []byte) (s string) {\n\tslice := (*reflect.SliceHeader)(unsafe.Pointer(&bytes))\n\tstr := (*reflect.StringHeader)(unsafe.Pointer(&s))\n\tstr.Data = slice.Data\n\tstr.Len = slice.Len\n\treturn s\n}", "func int8SliceToString(char []int8) string {\n\ts := make([]string, len(char))\n\tfor i := range s {\n\t\ts[i] = string(char[i])\n\t}\n\treturn strings.Join(s, \"\")\n\t// TODO maybe change this to convert exclusively to [65]int8 array ?\n}", "func ByteToString(b *[]byte) string {\n\tresult := *b\n\treturn string(result[:])\n}", "func Concat(path, path2 []string) []string {\n\tpathCopy := make([]string, len(path))\n\tcopy(pathCopy, path)\n\n\tif len(path) == 0 {\n\t\tpath2Copy := make([]string, len(path2))\n\t\tcopy(path2Copy, path)\n\t\treturn path2Copy\n\t}\n\n\tif len(path2) == 0 {\n\t\treturn pathCopy\n\t}\n\n\tif path[len(path)-1] != path2[0] {\n\t\tlog.Fatalln(\"Tried to compute\", path, \"+\", path2, \"but their ends differ\")\n\t}\n\n\tpathCopy = append(pathCopy[:len(pathCopy)-1], path2...)\n\treturn pathCopy\n}", "func ConcatOffset(scope *Scope, concat_dim tf.Output, shape []tf.Output) (offset []tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"ConcatOffset\",\n\t\tInput: []tf.Input{\n\t\t\tconcat_dim, tf.OutputList(shape),\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tvar idx int\n\tvar err error\n\tif offset, idx, err = makeOutputList(op, idx, \"offset\"); err != nil {\n\t\tscope.UpdateErr(\"ConcatOffset\", err)\n\t\treturn\n\t}\n\treturn offset\n}", "func byteString(b []byte) string {\n\tif len(b) < 1 {\n\t\treturn \"\"\n\t}\n\n\ts := make([]byte, len(b)*3-1)\n\ti, j := 0, 0\n\tfor n := len(b) - 1; i < n; i, j = i+1, j+3 {\n\t\ts[j+0] = hex[(b[i] >> 4)]\n\t\ts[j+1] = hex[(b[i] & 0x0f)]\n\t\ts[j+2] = ' '\n\t}\n\ts[j+0] = hex[(b[i] >> 4)]\n\ts[j+1] = hex[(b[i] & 0x0f)]\n\treturn string(s)\n}", "func (c StringArrayCollection) Prepend(values ...interface{}) Collection {\n\n\tvar d StringArrayCollection\n\n\tvar n = make([]string, len(c.value))\n\tcopy(n, c.value)\n\n\td.value = append([]string{values[0].(string)}, n...)\n\td.length = len(d.value)\n\n\treturn d\n}", "func BCat(b1, b2 []byte) []byte {\n\treturn append(b1, b2...)\n}", "func sliceToString(a []int) string {\n\tb := \"\"\n\tfor _, v := range a {\n\t\tb += strconv.Itoa(v)\n\t}\n\treturn b\n}", "func caddSlice(out, a []float64, c float64)", "func addSlice(out, a, b []float64)", "func (m *mmapData) pushStringSlice(ss []string) **C.char {\n\tarr := unsafe.Pointer(&m.data[m.offset])\n\tnextptr := arr\n\tm.offset += ptrSize * (len(ss) + 1)\n\tfor _, s := range ss {\n\t\tptr := m.pushString(s)\n\t\t*(*unsafe.Pointer)(nextptr) = unsafe.Pointer(ptr)\n\t\tnextptr = unsafe.Pointer(uintptr(nextptr) + uintptr(ptrSize))\n\t}\n\t*(*unsafe.Pointer)(nextptr) = unsafe.Pointer(nil)\n\tm.panicIfOverAllocated()\n\treturn (**C.char)(arr)\n}", "func paddedAppend(size uint, dst, src []byte) []byte {\n\tfor i := 0; i < int(size)-len(src); i++ {\n\t\tdst = append(dst, 0)\n\t}\n\treturn append(dst, src...)\n}", "func ReplaceSlice(b []byte, start, end int, repl []byte) []byte {\n\tdst := make([]byte, 0, len(b)-end+start+len(repl))\n\tdst = append(dst, b[:start]...)\n\tdst = append(dst, repl...)\n\tdst = append(dst, b[end:]...)\n\treturn dst\n}" ]
[ "0.77931696", "0.7339889", "0.7212358", "0.6981443", "0.6410898", "0.63878906", "0.6327533", "0.61192644", "0.60112464", "0.5952378", "0.59362984", "0.59355867", "0.5909852", "0.589257", "0.58814573", "0.5867457", "0.5865077", "0.5848797", "0.58426183", "0.58351725", "0.5766381", "0.57578796", "0.5750988", "0.57433146", "0.5733062", "0.5671343", "0.5645158", "0.56343085", "0.5595055", "0.5588167", "0.5549101", "0.55431014", "0.5531783", "0.5523918", "0.55155474", "0.5497109", "0.5484942", "0.54719424", "0.5468103", "0.5458864", "0.5440912", "0.5440912", "0.5417571", "0.54175425", "0.54133576", "0.54091376", "0.537281", "0.53598356", "0.53248966", "0.53180563", "0.52571213", "0.52519625", "0.524389", "0.52413434", "0.52398294", "0.5238469", "0.5229625", "0.52195424", "0.5216219", "0.51941836", "0.51878095", "0.5183437", "0.5183437", "0.51594126", "0.5157141", "0.5153386", "0.5139499", "0.5122492", "0.5115132", "0.5114981", "0.5114911", "0.51034665", "0.5079392", "0.5075524", "0.50742567", "0.50734854", "0.5072832", "0.50654244", "0.50650895", "0.50632954", "0.506207", "0.5061793", "0.5055116", "0.5051377", "0.5048316", "0.5047529", "0.5047529", "0.50467044", "0.5038415", "0.50279343", "0.50265205", "0.50258267", "0.5020592", "0.50173324", "0.50166506", "0.5003937", "0.4997212", "0.49943063", "0.49902582", "0.49894074" ]
0.776643
1
UseHTTPClient allows the default http client to be overriden for calls to the flow service. This function must be called prior to flows.WithFlow to take effect (e.g. from an init method)
func UseHTTPClient(client *http.Client) { httpClient = client }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func UseHttpClient(client *http.Client) {\n\tdefaultHttpClient = client\n}", "func (o *GetTaskStatesDeprecatedParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (c *Client) SetHTTPClient(client *http.Client) {\n\tif client == nil {\n\t\tc.httpClient = http.DefaultClient\n\t\treturn\n\t}\n\tc.httpClient = client\n}", "func (o *IntegrationsManualHTTPSCreateParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetRuleChainParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *UpdateFlowParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetNetworkExternalParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetIPLoadbalancingServiceNameTaskParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *PostIPLoadbalancingServiceNameHTTPFrontendParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *DeprecatedCycleParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetCustomRuleParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func SetHTTPClient(client *http.Client) {\n\thttpClient = client\n}", "func (o *GetNetworkAppliancePortParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *HandleGetAboutUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *HasFlowRunningByFlowIDParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *SetPlanParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ListPipelinesParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (c *Client) SetHTTPClient(httpClient HTTPClient) {\n\tif httpClient == nil {\n\t\tc.client = http.DefaultClient\n\t} else {\n\t\tc.client = httpClient\n\t}\n}", "func (o *GetProductUpgradeURLUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *OptionsTodoTodoidParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ReadLogicalRouterParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetAppsAppCallsCallParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ResolveBatchParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (service *BaseService) SetHTTPClient(client *http.Client) {\n\tsetMinimumTLSVersion(client)\n\n\tif isRetryableClient(service.Client) {\n\t\t// If \"service\" is currently holding a retryable client,\n\t\t// then set \"client\" as the embedded client used for individual requests.\n\t\ttr := service.Client.Transport.(*retryablehttp.RoundTripper)\n\t\ttr.Client.HTTPClient = client\n\t} else {\n\t\t// Otherwise, just hang \"client\" directly off the base service.\n\t\tservice.Client = client\n\t}\n}", "func (o *GetContentSourceUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ToggleNetworkGeneratorsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ExtrasGraphsReadParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *PostHyperflexAutoSupportPoliciesParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *IPAMServicesReadParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *DownloadFlowFileContentParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *CleanUpTasksDeprecatedParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ImportApplicationUsingPOSTParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *VirtualizationChoicesReadParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func SetHTTPClient(newClient *http.Client) {\n\thttpClient = newClient\n}", "func (sm *Manager) SetHTTPClient(c *http.Client) {\n\tsm.client = c\n}", "func (sm *Manager) SetHTTPClient(c *http.Client) {\n\tsm.client = c\n}", "func (o *ListTaskNexusParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ModifyProxyConfigInternalParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ExportProductsUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func WithHTTPClient(httpclient *http.Client) ClientOption {\n\treturn func(client *Client) {\n\t\tclient.httpClient = httpclient\n\t}\n}", "func SetHTTPClient(httpClient *http.Client) func(*Client) error {\n\treturn func(client *Client) error {\n\t\tclient.client = httpClient\n\n\t\treturn nil\n\t}\n}", "func (o *AddOrUpdateNodePoolConfigItemParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetFyiSettingsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetDatalakeDbConfigParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *UpdateFeaturesConfigurationParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *RecommendMultiClusterParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetProcessorsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *CreateDashboardRenderTaskParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ShowPackageParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetSimulationActivityParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetContentSourcesUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *NearestUsingGET1Params) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func SetHTTPClient(c *http.Client) auth.Option {\n\treturn internal.SetRequesterHTTPClient(c)\n}", "func SetHTTPClient(c *http.Client) auth.Option {\n\treturn internal.SetRequesterHTTPClient(c)\n}", "func (o *LineRouteParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *RetrievePortalSessionParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *UpdateNetworkHTTPServerParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *FetchIntegrationFormParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *AllLookmlTestsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *PostLolGameflowV1ReconnectParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetUserUsageParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetTransportNodeParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ExportUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *CreateGitWebhookUsingPOSTParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetReceiptsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ConfigGetParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *AddServerGroupInUpstreamParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func WithHTTPClient(httpClient *http.Client) Option {\n\treturn func(cfg *config) {\n\t\tcfg.httpClient = httpClient\n\t}\n}", "func (o *UpdateSyncRuleParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetTasksGetPhpParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetV1FunctionalitiesParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetNutritionForSingleParsedPlainTextIngredientParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetSellerServicesUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetWorkItemParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetTerraformConfigurationSourcesUsingGET1Params) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *StartGatewayBundleUsingPOSTParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *SyncStatusUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *PutTravelExpensePassengerIDParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetPackageSearchActionOldSpacesParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func SetHTTPClient(client *http.Client) error {\n\tif client == nil {\n\t\treturn errHTTPClientInvalid\n\t}\n\tm.Lock()\n\t_HTTPClient = client\n\tm.Unlock()\n\treturn nil\n}", "func (o *UpdateDmrClusterLinkParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetRecentFoodsParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ListNodesParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func WithHTTPClient(client *http.Client) ClientOption {\n\treturn func(c *Client) {\n\t\tc.httpClient = client\n\t}\n}", "func WithHTTPClient(client *http.Client) Opt {\n\treturn func(c *Client) error {\n\t\tif client != nil {\n\t\t\tc.client = client\n\t\t}\n\t\treturn nil\n\t}\n}", "func WithHTTPClient(client *http.Client) Opt {\n\treturn func(c *Client) {\n\t\tc.httpClient = client\n\t}\n}", "func (o *ConvertParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ImportStore1Params) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *MetroclusterInterconnectGetParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *SendTransacSMSParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *PostAutoDiscoveryPingsweepParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *GetNetworkSwitchSettingsQosRuleParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *CreateCartUsingPOSTParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *UpdateTransactionCategorizationRuleParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func WithHTTPClient(httpClient *http.Client) ClientOption {\n\treturn func(c *Client) {\n\t\tc.httpClient = httpClient\n\t}\n}", "func (o *GetAnOrderProductParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *ChatNewParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *CreateCrossConnectParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *SyncCmOnDatalakeClusterParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func WithHTTPClient(httpClient *http.Client) ClientOption {\n\treturn func(client *Client) {\n\t\tclient.httpClient = httpClient\n\t}\n}" ]
[ "0.75783104", "0.7506294", "0.7492137", "0.74902767", "0.7485698", "0.7479744", "0.7455541", "0.7439341", "0.7431533", "0.74264723", "0.7426049", "0.7418902", "0.7417015", "0.7413888", "0.74032027", "0.73680377", "0.7363684", "0.7361882", "0.7361576", "0.7346382", "0.73421276", "0.7339704", "0.7336977", "0.73348427", "0.7325213", "0.7310317", "0.7310018", "0.7303343", "0.72923493", "0.72895205", "0.7279939", "0.72708297", "0.7263784", "0.72555417", "0.7254894", "0.7254894", "0.72546154", "0.7254103", "0.7253536", "0.7252925", "0.724889", "0.72469294", "0.7245118", "0.7242398", "0.7238493", "0.7237625", "0.72373605", "0.7235493", "0.72350496", "0.7232581", "0.7232173", "0.723137", "0.7228894", "0.7228894", "0.7228814", "0.7227494", "0.7227388", "0.7226614", "0.7223513", "0.72207046", "0.7218773", "0.72177863", "0.7213054", "0.7212131", "0.7212092", "0.72081107", "0.7206745", "0.72063017", "0.72017", "0.7201433", "0.7200652", "0.7198402", "0.7191427", "0.71858305", "0.7185585", "0.7179499", "0.71791697", "0.7178855", "0.71787447", "0.7178224", "0.7174923", "0.7171664", "0.71620756", "0.7158993", "0.7151265", "0.7151079", "0.7150205", "0.71489835", "0.7146087", "0.71420455", "0.7138097", "0.7136371", "0.7134407", "0.71337545", "0.71299064", "0.71290755", "0.7127779", "0.712537", "0.712457", "0.711978" ]
0.8034563
0
Debug enables internal library debugging
func Debug(withDebug bool) { // go won't cast bool to uint32, you better believe it var bint uint32 if withDebug { bint++ } atomic.StoreUint32(&debugMu, bint) debug("Enabled debugging") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *Provider) Debug(debug bool) {}", "func (p *Provider) Debug(debug bool) {}", "func (p *Provider) Debug(debug bool) {}", "func (p *Provider) Debug(debug bool) {}", "func EnableDebug() {\n\tisDebug = true\n}", "func SetDebug() {\n\tglobalDebug = true\n}", "func (patchwork *Patchwork) Debug() {\n\tpatchwork.debug = true\n}", "func SetDebugMode(b bool) { env.SetDebugMode(b) }", "func (s *BasePlSqlParserListener) EnterLibrary_debug(ctx *Library_debugContext) {}", "func selectDebug() {\n\tDEBUG_GATE = false\n\tDEBUG_STATE = true\n}", "func (fp MockProvider) Debug(b bool) {\n\tfp.faux.Debug(b)\n}", "func SetDebug(flag bool) {\n\tdebug = flag\n}", "func (c *APIClient) Debug() {\n\tc.debug = true\n}", "func (p *Poloniex) Debug() {\r\n\tp.debug = true\r\n}", "func Debug(flag bool) {\n\tskiplist.Debug = flag\n\tmm.Debug = flag\n}", "func SetDebug(b bool) {\n\tisDebug = b\n}", "func (rl *limiter) Debug(enable bool) {\n\trl.debug = enable\n}", "func SetDebug(mode bool) {\n\tdebug = mode\n}", "func SetDebug(b bool) {\n\tdebugon = b\n}", "func debug(s string) {\n\tif isDebugMode {\n\t\tfmt.Printf(\"DEBUG: %s\", s)\n\t}\n}", "func (p *Provider) Debug(debug bool) {\n\tp.debug = debug\n}", "func Debug(v bool, m ...interface{}) {\n\tif v {\n\t\tpc := make([]uintptr, 15)\n\t\tn := runtime.Callers(2, pc)\n\t\tframes := runtime.CallersFrames(pc[:n])\n\t\tframe, _ := frames.Next()\n\t\tlog.Printf(\"DEBUG [%v] %v\", frame.Function, fmt.Sprintln(m...))\n\t}\n}", "func SetDebug(value bool) {\n\tdebug = value\n}", "func (wfw *impl) Debug(d bool) Interface { wfw.debug = d; return wfw }", "func debug(format string, args ...interface{}) {\n\tif debugOn {\n\t\tlog.Printf(\"DEBUG: \"+format, args...)\n\t}\n}", "func (l BlackHole) IsDebug() bool { return l.EnableDebug }", "func Debug(ctx context.Context, args ...interface{}) {\n\tglobal.Debug(ctx, args...)\n}", "func ToggleDebugMode() {\n\tDEBUG = !DEBUG\n}", "func (e *Engine) Debug(enabled bool) *Engine {\n\te.Verbose = enabled\n\treturn e\n}", "func (e *Env) DebugEnabled() bool {\n\treturn true\n}", "func SetDebug(debug bool) {\n\tAPI.DEBUG = debug\n}", "func init() {\n\tdebug.Disable()\n}", "func (e *Env) SetDebugMode(b bool) { e.debugMode = b }", "func (player *Player) EnableDebug() {\n\tplayer.debug = true\n}", "func enable_debug() {\n\tnfo.SetOutput(nfo.DEBUG, os.Stdout)\n\tnfo.SetFile(nfo.DEBUG, nfo.GetFile(nfo.ERROR))\n}", "func SetDebug(debug bool) {\n\tmgo.SetDebug(debug)\n}", "func SetDebug(debug bool) {\n\tisDebug = debug\n}", "func debug(message string) {\n if DebugMode {\n fmt.Fprintln(os.Stderr, \"DEBUG:\", message)\n }\n}", "func EnableDebug(isEnable bool) {\n\tdefaultEnableDebug = isEnable\n}", "func (c *Client) EnableDebug() {\n\tc.Debug = true\n}", "func Enable() {\n\tdebug = true\n}", "func debug(m string, v interface{}) {\n\tif DebugMode {\n\t\tlog.Printf(m+\":%+v\", v)\n\t}\n}", "func Debug(msg string) {\n log.Debug(msg)\n}", "func EnableDebugMode() {\n\tDefaultLogger.Init(os.Stderr, LogLevelDebug)\n}", "func (a *APITest) Debug() *APITest {\n\ta.debugEnabled = true\n\treturn a\n}", "func Bcm2835_set_debug(Debug byte) {\n\tcDebug, _ := (C.uint8_t)(Debug), cgoAllocsUnknown\n\tC.bcm2835_set_debug(cDebug)\n}", "func (d *DummyLogger) Debug(format string) {}", "func DebugMode() bool {\n\treturn debugMode\n}", "func DebugMode() bool {\n\treturn debugMode\n}", "func Debug(v ...interface{}) {\n\tif enableDebug {\n\t\tinfoLog(v...)\n\t}\n}", "func TestDebug(t *testing.T) {\n\tvar data = []byte(`Log this!`)\n\tapolog.Debug(data)\n}", "func debug(stuff string) {\n\tif DEBUG {\n\t\tfmt.Println(stuff)\n\t}\n}", "func (cdp *Client) Debug(enable bool) *Client {\n\tcdp.debug = enable\n\treturn cdp\n}", "func GetDebugMode() bool { return env.GetDebugMode() }", "func (aps *ApiServer) SetDebug() {\n\tgin.SetMode(gin.DebugMode)\n}", "func Debug(msg string){\n\tif IsDebug() {\n\t\tlog.Println(msg)\n\t}\n}", "func Debug(text string) {\n\tprintLog(\"debug\", text)\n}", "func debugTrace(err error) {\n\tif debug != \"enable\" {\n\t\treturn\n\t}\n\tfmt.Println(\"StackTrace =====================\")\n\tfmt.Printf(\"%+v\\n\", err)\n}", "func (c DQLConfig) MakeDebug() {\n\tc.make(\"debug\", \"debug\", false)\n}", "func InDebugging() bool { return env.InDebugging() }", "func (db RDB) Debug(enable bool) {\n\tdb.debug = enable\n}", "func IsDebug() bool {\n\treturn enableDebug\n}", "func (lc mockNotifyLogger) Debug(msg string, args ...interface{}) {\n}", "func EnableDebugLogging(logger logFunc) {\n\tdebugLogger = logger\n}", "func Debug(args ...interface{}) {\n\tNewDefaultEntry().Debug(args...)\n}", "func Debug(data []byte) {\n\tlog.Print(\"DEBUG: \", string(data))\n}", "func Debug() {\n\tfmt.Println(\"Debug go-media-devices-state module...\")\n\tfmt.Println()\n\n\tisCameraOn, err := camera.IsCameraOn()\n\tfmt.Println()\n\tif err != nil {\n\t\tfmt.Println(\"Is camera on: ERROR:\", err)\n\t} else {\n\t\tfmt.Println(\"Camera state:\", formatBool(isCameraOn))\n\t}\n\n\tfmt.Println()\n\n\tisMicrophoneOn, err := microphone.IsMicrophoneOn()\n\tfmt.Println()\n\tif err != nil {\n\t\tfmt.Println(\"isMicrophoneOn(): ERROR:\", err)\n\t} else {\n\t\tfmt.Println(\"Microphone state:\", formatBool(isMicrophoneOn))\n\t}\n}", "func (app *App) debug(msg string) {\n\tif app.Debug {\n\t\tlog.Println(msg)\n\t}\n}", "func Init(debugMode bool) {\n\tdbgMode = debugMode\n}", "func Debug(g *types.Cmd) {\n\tg.Debug = true\n}", "func Debug(ctx ...interface{}) {\n\tlogNormal(debugStatus, time.Now(), ctx...)\n}", "func GloballyEnableDebugLogForTest() {\r\n\tglobalLogger.consoleLevel.SetLevel(zapcore.DebugLevel)\r\n}", "func WithDebugMode() *debug {\n\treturn &debug{}\n}", "func (n *Null) Debug(args ...interface{}) {\n}", "func (n Noop) Debug(args ...interface{}) {\n\tpanic(\"noop log\")\n}", "func Debug(fn func()) {\n\n\tSetDumpCode(\"1\")\n\tdefer SetDumpCode(\"0\")\n\tfn()\n}", "func (l *Impl) Debug(format string, args ...interface{}) {\n\tl.write(\"DEBUG\", format, args...)\n}", "func WithDebugMode() Option {\n\treturn withDebugMode{}\n}", "func Debug(i interface{}) {\n\tl.Debug(i)\n}", "func SetDebug(dbg bool) {\n\tlogger.Debug = dbg\n}", "func SetDebugMode(f bool) {\n\tdebugMode = f\n}", "func (z *Logger) Debug(args ...interface{}) {\n\tz.SugaredLogger.Debug(args...)\n}", "func debug(format string, args ...interface{}) {\n\tif IsDebug {\n\t\tLog.Debug(fmt.Sprintf(format, args...))\n\t}\n}", "func (l nullLogger) Debug(msg string, ctx ...interface{}) {}", "func Debug(v string) {\n\tDefaultTarget.Debug(v)\n}", "func SetDebug(val bool) {\n\tif val {\n\t\tatomic.StoreUint32(&debug, 1)\n\t} else {\n\t\tatomic.StoreUint32(&debug, 0)\n\t}\n}", "func debugPrint(text string) {\n\tif (debugon) {\n\t\tfmt.Println(text)\n\t}\n}", "func DebugEnabled(enabled bool) {\n\tdefaultDaemon.DebugEnabled(enabled)\n}", "func SetDebug(debug bool) {\n\tcurrentDebug = debug\n}", "func Debug(msg ...interface{}) {\n\tCurrent.Debug(msg...)\n}", "func Debug(format string, a ...interface{}) {\n\tif DebuggingEnabled {\n\t\tfmt.Printf(format, a...)\n\t}\n}", "func setDebug(w io.Writer, debug bool) {\n\tif !debug {\n\t\tpp.SetDefaultOutput(ioutil.Discard)\n\t\treturn\n\t}\n\tif w == nil {\n\t\tvar err error\n\t\tw, err = os.OpenFile(filepath.Join(\".\", \"ali-debug.log\"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tpp.SetDefaultOutput(w)\n}", "func Debug(args ...interface{}) {\r\n\tLogger.Debug(\"\", args)\r\n}", "func SetDebug(debug bool) {\n\tglobalLoggerLock.Lock()\n\tglobalDebug = debug\n\tglobalLoggerLock.Unlock()\n}", "func (logger MockLogger) Debug(args ...interface{}) {\n\tlogger.Sugar.Debug(args)\n}", "func (c *Client) Debug(debug bool) {\n\tc.debug = debug\n}", "func (c *Poloniex) SetDebug(enable bool) {\n\tc.client.debug = enable\n}", "func (logger *Logger) Debug(args ...interface{}) {\n\tlogger.std.Log(append([]interface{}{\"Debug\"}, args...)...)\n}", "func (l *XORMLogBridge) Debug(v ...interface{}) {\n\tlog.Debug(v...)\n}", "func (w *Writer) Debug(m string) error {}" ]
[ "0.7404367", "0.7404367", "0.7404367", "0.7404367", "0.7245704", "0.7190543", "0.7055543", "0.7013385", "0.6999899", "0.6962028", "0.6916196", "0.6909126", "0.6896783", "0.6890489", "0.6818804", "0.678027", "0.6773512", "0.67285407", "0.6721295", "0.6720024", "0.67121613", "0.6709491", "0.67081404", "0.6669631", "0.6663734", "0.6659744", "0.66510725", "0.66351426", "0.6603982", "0.6598362", "0.65788573", "0.6572346", "0.65644264", "0.65630096", "0.65610355", "0.6559256", "0.655882", "0.65549415", "0.65388054", "0.6517454", "0.65062827", "0.6497867", "0.6484751", "0.6446476", "0.64417887", "0.6434217", "0.6431725", "0.64299554", "0.64299554", "0.642756", "0.64262694", "0.641617", "0.64140505", "0.6408929", "0.6386457", "0.6378972", "0.6372776", "0.6364835", "0.6357255", "0.6337364", "0.63358146", "0.6334775", "0.63292986", "0.63226503", "0.63100797", "0.6306058", "0.63025194", "0.6300547", "0.62983966", "0.6291799", "0.62795395", "0.62745535", "0.6272165", "0.6251665", "0.6249051", "0.62485516", "0.62409073", "0.62341243", "0.62339073", "0.62284756", "0.621378", "0.6213737", "0.6202232", "0.6200142", "0.61937517", "0.618865", "0.6187662", "0.6185564", "0.61746526", "0.61732817", "0.61727226", "0.6171062", "0.61473614", "0.61448807", "0.61345893", "0.6128512", "0.6126846", "0.61257434", "0.61178553", "0.6116" ]
0.6418893
51
Log to stderr when Debug mode is enabled
func Log(msg string) { debug(msg) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func debug(message string) {\n if DebugMode {\n fmt.Fprintln(os.Stderr, \"DEBUG:\", message)\n }\n}", "func EnableDebugMode() {\n\tDefaultLogger.Init(os.Stderr, LogLevelDebug)\n}", "func debugLog(msg ...interface{}) {\n\tlogLocker.Lock()\n\tdefer logLocker.Unlock()\n\tif *confVerbose {\n\t\tcolor.White(fmt.Sprint(time.Now().Format(\"02_01_06-15.04.05\"), \"[DEBUG] ->\", msg))\n\t}\n}", "func Debug(args ...interface{}) {\n\terrorLogger.Debug(args...)\n}", "func debugTrace(err error) {\n\tif debug != \"enable\" {\n\t\treturn\n\t}\n\tfmt.Println(\"StackTrace =====================\")\n\tfmt.Printf(\"%+v\\n\", err)\n}", "func Debug(ctx context.Context, err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\tif ctx == nil {\n\t\tctx = defaultContext\n\t}\n\tif !verbose {\n\t\tif v, _ := ctx.Value(logContextKeyDebug).(bool); !v {\n\t\t\treturn\n\t\t}\n\t}\n\tctx = addSource(ctx, err)\n\n\tgetLogger(ctx).WithError(err).Infoln()\n}", "func myDebug(format string, a ...interface{}) {\n\tif FlagDebug {\n\t\tformat = fmt.Sprintf(\"[DEBUG] %s\\n\", format)\n\t\tfmt.Fprintf(os.Stderr, format, a...)\n\t}\n}", "func (d *DummyLogger) Debug(format string) {}", "func DebugLog(debugMode bool, args ...interface{}) {\n\tif debugMode {\n\t\tlog.Println(\"[EPSAGON]\", args)\n\t}\n}", "func Debug(msg string){\n\tif IsDebug() {\n\t\tlog.Println(msg)\n\t}\n}", "func debugLog(msg interface{}) {\n fmt.Fprintln(os.Stderr, msg)\n}", "func setDebug(w io.Writer, debug bool) {\n\tif !debug {\n\t\tpp.SetDefaultOutput(ioutil.Discard)\n\t\treturn\n\t}\n\tif w == nil {\n\t\tvar err error\n\t\tw, err = os.OpenFile(filepath.Join(\".\", \"ali-debug.log\"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tpp.SetDefaultOutput(w)\n}", "func (r *Reporter) Debug(msg string, ctx ...interface{}) {\n\tif r.Logging != nil {\n\t\tr.Logging.Debug(msg, ctx...)\n\t}\n}", "func (l *thundraLogger) Debug(v ...interface{}) {\n\tif logLevelId > debugLogLevelId {\n\t\treturn\n\t}\n\tlogManager.recentLogLevel = debugLogLevel\n\tlogManager.recentLogLevelId = debugLogLevelId\n\tl.Output(2, fmt.Sprint(v...))\n}", "func (logger *Logger) Debug(args ...interface{}) {\n\tlogger.std.Log(append([]interface{}{\"Debug\"}, args...)...)\n}", "func (w *Writer) Debug(m string) error {}", "func debugLog(v ...interface{}) {\n\tif *isDebug || *isVerbose {\n\t\tlog.Println(v...)\n\t}\n}", "func (l nullLogger) Debug(msg string, ctx ...interface{}) {}", "func Debug(format string, args ...interface{}) {\n\tif !Debugging {\n\t\treturn\n\t}\n\tlog.Printf(format, args...)\n}", "func debug(format string, args ...interface{}) {\n\tif debugOn {\n\t\tlog.Printf(\"DEBUG: \"+format, args...)\n\t}\n}", "func Debug(msg string) {\n log.Debug(msg)\n}", "func Debug(v ...interface{}) {\n\tif jl.level != INFO {\n\t\tvar s string\n\t\tjl.stdlog.SetPrefix(\"[DEBUG] \")\n\t\tif jl.flag == LstdFlags|Lshortfile {\n\t\t\ts = generateStdflagShortFile()\n\t\t}\n\n\t\ts = s + fmt.Sprintln(v...)\n\t\tjl.stdlog.Print(s)\n\t}\n}", "func Debug(msg ...interface{}) {\n\tif LevelDebug >= logLevel {\n\t\tsyslog.Println(\"D:\", msg)\n\t}\n}", "func Debug(msg string, a ...interface{}) {\n if *verbose {\n formatted := fmt.Sprintf(msg, a...)\n logger.Println(fmt.Sprintf(\"\\033[35;1mDEBUG:\\033[0m %s\", formatted))\n }\n}", "func logDebug(r *http.Request, msg string) {\n\tif Debug {\n\t\tlogEvent(r, \"debug\", msg)\n\t}\n}", "func (l *Logger) DebugE(err error) {\r\n\tl.Debug(err.Error())\r\n}", "func (h *Hub) EnableDebug(enable bool) {\n\tif enable {\n\t\tlog.SetOutput(os.Stdout)\n\t} else {\n\t\tlog.SetOutput(ioutil.Discard)\n\t}\n}", "func (rl *limiter) Debug(enable bool) {\n\trl.debug = enable\n}", "func Debug(v ...interface{}) {\n\tif enableDebug {\n\t\tinfoLog(v...)\n\t}\n}", "func Debug(args ...interface{}) {\n\tlogWithFilename().Debug(args...)\n}", "func GloballyDisableDebugLogForTest() {\r\n\tglobalLogger.consoleLevel.SetLevel(zapcore.ErrorLevel)\r\n}", "func (z *Logger) Debug(args ...interface{}) {\n\tz.SugaredLogger.Debug(args...)\n}", "func (n Noop) Debug(args ...interface{}) {\n\tpanic(\"noop log\")\n}", "func (dl *defaultLogger) Debug(msg string) {\n\tdl.Print(msg)\n}", "func logDebug(text string, params ...interface{}) {\n\tif !*debug {\n\t\treturn\n\t}\n\tline := fmt.Sprintf(text, params...)\n\tlog.Printf(\"DEBUG: %s\", line)\n}", "func Debug(ctx ...interface{}) {\n\tlogNormal(debugStatus, time.Now(), ctx...)\n}", "func Debug(msg ...interface{}) {\n\tlog(defaultLogger, DEBUG, msg...)\n}", "func (app *App) debug(msg string) {\n\tif app.Debug {\n\t\tlog.Println(msg)\n\t}\n}", "func debug(msg string, args ...interface{}) {\n\tif *verbose {\n\t\tif len(args) > 0 {\n\t\t\tlog.Printf(msg, args...)\n\t\t} else {\n\t\t\tlog.Printf(msg)\n\t\t}\n\t}\n}", "func setDebug(w io.Writer, debug bool) {\n\tif !debug {\n\t\treturn\n\t}\n\tif w == nil {\n\t\tdir, err := configDir()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif err := os.MkdirAll(dir, os.ModePerm); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tw, err = os.OpenFile(filepath.Join(dir, \"debug.log\"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.ModePerm)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tlog.SetOutput(w)\n}", "func (s *Scope) Debug(msg string, fields ...zapcore.Field) {\n\tif s.GetOutputLevel() >= DebugLevel {\n\t\ts.emit(zapcore.DebugLevel, s.GetStackTraceLevel() >= ErrorLevel, msg, fields)\n\t}\n}", "func (logger *Logger) Debug(msg string, extras ...map[string]string) error {\n\tif DebugLevel >= logger.LogLevel {\n\t\treturn logger.Log(msg, DebugLevel, extras...)\n\t}\n\treturn nil\n}", "func Debug(s string) {\n\tif Verbose == true {\n\t\tprintln(s)\n\t}\n}", "func (l *Logger) Debug(msg string, v ...interface{}) {\n\tif l.debug {\n\t\tfmt.Fprint(l.stderr, addColor(DebugPrefix+\" \", Cyan))\n\t\tl.Msg(msg, v...)\n\t}\n}", "func (stimLogger *FullStimLogger) Debug(message ...interface{}) {\n\tif stimLogger.highestLevel >= DebugLevel {\n\t\tif stimLogger.setLogger == nil {\n\t\t\tif stimLogger.forceFlush {\n\t\t\t\tstimLogger.writeLogs(stimLogger.formatString(DebugLevel, debugMsg, message...))\n\t\t\t} else {\n\t\t\t\tstimLogger.formatAndLog(DebugLevel, debugMsg, message...)\n\t\t\t}\n\t\t} else {\n\t\t\tstimLogger.setLogger.Debug(message...)\n\t\t}\n\t}\n}", "func (zw *ZerologWriter) DebugLogging(enabled bool) { zw.w.DebugLogging(enabled) }", "func (zw *ZerologWriter) DebugLogging(enabled bool) { zw.w.DebugLogging(enabled) }", "func (l Logger) Debug(msg ...interface{}) {\n\tif l.Level <= log.DebugLevel {\n\t\tout := fmt.Sprint(append([]interface{}{l.DebugColor.Sprint(\"DEBUG: \")}, msg...)...)\n\t\tout = checkEnding(out)\n\t\tfmt.Fprint(l.DebugOut, out)\n\t}\n}", "func enable_debug() {\n\tnfo.SetOutput(nfo.DEBUG, os.Stdout)\n\tnfo.SetFile(nfo.DEBUG, nfo.GetFile(nfo.ERROR))\n}", "func debug(s string) {\n\tif isDebugMode {\n\t\tfmt.Printf(\"DEBUG: %s\", s)\n\t}\n}", "func LogDebug(debug bool, text string) {\n\tif debug {\n\t\tfmt.Println(Timestamp(), \"DEBUG:\", text)\n\t}\n}", "func Debug(log string, v ...interface{}) {\n\tsyslog.Printf(\"DEBUG \"+log, v...)\n}", "func Debug(message string) {\n\tif logLevel >= 1 {\n\t\tlogger.Printf(\"DEBUG %s\", message)\n\t}\n}", "func Debug(v bool, m ...interface{}) {\n\tif v {\n\t\tpc := make([]uintptr, 15)\n\t\tn := runtime.Callers(2, pc)\n\t\tframes := runtime.CallersFrames(pc[:n])\n\t\tframe, _ := frames.Next()\n\t\tlog.Printf(\"DEBUG [%v] %v\", frame.Function, fmt.Sprintln(m...))\n\t}\n}", "func SetDebug() {\n\tglobalDebug = true\n}", "func Debug(format string, args ...interface{}) {\n\tif os.Getenv(\"GHS_DEBUG\") != \"\" {\n\t\tlog.Printf(format, args...)\n\t}\n}", "func (c testCEEwriter) Debug(m string) error { return nil }", "func (l *Logger) Debug(v ...interface{}) { l.lprint(DEBUG, v...) }", "func (l *Logger) Debug(v ...interface{}) {\n\tif l.staticOptions.Debug {\n\t\t_ = l.Output(2, fmt.Sprint(v...))\n\t}\n}", "func (l Logger) Debug(msg ...interface{}) {\n\tif l.Level <= log.DebugLevel {\n\t\tl.logger.Print(append([]interface{}{\"[DEBUG] \"}, msg...)...)\n\t}\n}", "func (c *CLI) ExecDebug() error {\n\tpp.Fprintln(c.Stdout, c.Context)\n\tpp.Fprintln(c.Stdout, c.Config)\n\treturn nil\n}", "func errorLog(msg ...interface{}) {\n\tlogLocker.Lock()\n\tdefer logLocker.Unlock()\n\tif *confVerbose {\n\t\tcolor.Red(fmt.Sprint(time.Now().Format(\"02_01_06-15.04.05\"), \"[ERROR] ->\", msg))\n\t}\n}", "func Debug(format string, v ...interface{}) {\n\tif LogLevel() <= 0 {\n\t\tlog.Printf(\"DEBUG: \"+format, v...)\n\t}\n}", "func StdDebug(ctx context.Context, metadata interface{}, err error, message string) {\n\tdebugLogger.StdDebug(GetCtxRequestID(ctx), GetCtxID(ctx), err, metadata, message)\n}", "func (l *Logger) Debug(message string) {\n\tstdLog.Debug(message)\n}", "func Debug(format string, v ...interface{}) {\n\tif logger.Debug {\n\t\tdoLog(\"DEBUG\", format, v...)\n\t}\n}", "func SetDebugMode(b bool) { env.SetDebugMode(b) }", "func (l *Logger) Debug(v ...interface{}) {\n\tif l.loglevel <= sDebug {\n\t\tl.output(sDebug, 0, fmt.Sprint(v...))\n\t} else {\n\t\treturn\n\t}\n}", "func SetDebug(dbg bool) {\n\tlogger.Debug = dbg\n}", "func Debug(args ...interface{}) {\n\tlog.Debug(args...)\n}", "func Debug(args ...interface{}) {\n\tlog.Debug(args...)\n}", "func Debug(msg string) {\n\tif lvl <= deb {\n\t\tl.Print(\"[DEBUG]: \" + msg)\n\t}\n}", "func (std STDLogger) Debug(format string, args ...interface{}) {\n\tfmt.Printf(format, args...)\n\tfmt.Printf(\"\\n\")\n\n}", "func (slog stdLogger) Debug(s string) {\n\tif logger.Logger != nil {\n\t\tlogger.Write([]byte(\" DEBUG \" + s))\n\t} else {\n\t\tlog.Printf(\" DEBUG \" + s)\n\t}\n}", "func Debug(s string) {\n\tif os.Getenv(\"DEBUG\") == \"Y\" {\n\t\tfmt.Print(\"\\u001b[33m\")\n\t\tfmt.Println(\"DEBUG:\", s, \"\\u001b[0m\")\n\t}\t\n}", "func (v *MultiLogger) Debug(args ...interface{}) {\n\tv.Self().Log(logrus.DebugLevel, args...)\n}", "func Debug() <-chan error{\n\tvar err chan error\n\terr <- fmt.Errorf(\"Create an error\")\n\treturn err\n}", "func Debug(ctx context.Context, args ...interface{}) {\n\tGetLogger().Log(ctx, loggers.DebugLevel, 1, args...)\n}", "func LogDebug(text string) {\n\tLog(text, DebugLog)\n}", "func (l *Logger) Debug(args ...interface{}) {\n\tif l.IsEnabledFor(DebugLevel) {\n\t\tfile, line := Caller(1) // deeper caller will be more expensive\n\t\tl.Log(DebugLevel, file, line, \"\", args...)\n\t}\n}", "func (l *Logger) Debug(v ...interface{}) {\n\tif l.debugEnabled {\n\t\tl.NewEntry().Print(DEBUG, v...)\n\t}\n}", "func LogDebug(format string, a ...interface{}) {\n\tif LogLevel <= LogLevelDebug {\n\t\tfmt.Printf(debugColor+\"[~] \"+format+\"\\n\"+noColor, a...)\n\t}\n}", "func (l *logHandler) Debug(args ...interface{}) {\n\tl.Log(LogDebug, 3, args...)\n}", "func (l *MessageLogger) Debug(msg string) { l.logger.Debug(msg) }", "func debugLogPath(path string, info os.FileInfo, err error) error {\n\tif err != nil {\n\t\tklog.Error(err)\n\t\treturn err\n\t}\n\tklog.V(4).Infof(\"found path %s\", path)\n\treturn nil\n}", "func Debug(args ...interface{}) {\n\tLog(logrus.DebugLevel, args...)\n}", "func (sle *SystemLogWriter) Debug(msg string, args ...interface{}) error {\n\treturn sle.out.WriteEvent(context.Background(), sle.gen.Debug(msg, args...))\n}", "func Debug(a ...interface{}) {\n\tcolor.Set(color.FgMagenta)\n\tdefer color.Unset()\n\tdebugLogger.Println(a...)\n}", "func (e *Env) DebugEnabled() bool {\n\treturn true\n}", "func (p *tubePool) logDebug(opt RequestOptions, logString string) {\n\tif opt.Logger != nil && opt.LogLevel.AtLeast(aws.LogDebug) {\n\t\topt.Logger.Log(logString)\n\t}\n}", "func (sl *SysLogger) Debug(info, msg string) {\n\tlog.Println(\"[DEBUG]\", sl.tag, info, msg)\n}", "func Debug(msg string, args ...interface{}) {\n\tif level&DEBUG != 0 {\n\t\twriteMessage(\"DBG\", msg, args...)\n\t}\n}", "func (ctx *Context) Debug(level int) {\n\tif level < logNone {\n\t\tlevel = logNone\n\t} else if level > logDebug {\n\t\tlevel = logDebug\n\t}\n\n\tctx.logLevel = level\n\n\t// If the log level is set to debug, then add the file info to the flags\n\tvar flags = log.LstdFlags | log.Lmsgprefix\n\tif level == logDebug {\n\t\tflags |= log.Lshortfile\n\t}\n\tctx.logger.SetFlags(flags)\n}", "func (l *Logger) Debugln(v ...interface{}) { l.lprintln(DEBUG, v...) }", "func (l *Logger) Debug(values ...interface{}) {\n\tif l.loggingLevel > DebugLevel {\n\t\treturn\n\t}\n\tl.log(l.debugPrefix, fmt.Sprint(values...))\n}", "func EnableDebugLogging(logger logFunc) {\n\tdebugLogger = logger\n}", "func (l *Logger) Debug(message string) {\n\tl.printLogMessage(keptnLogMessage{Timestamp: time.Now(), Message: message, LogLevel: \"DEBUG\"})\n}", "func (l *Logger) Debug(a ...interface{}) {\n\tif l.Verbosity < VerbosityLevelVerbose {\n\t\treturn\n\t}\n\n\tl.logInStyle(debugString, cyan, a...)\n}", "func Debug(args ...interface{}) {\n\tDefaultLogger.Debug(args...)\n}", "func (testLog TestLog) Debug(msg ...interface{}) {\n\ttestLog.T.Log(\"[Debug]\", msg)\n}", "func (CryptoMachineLogger) Debug(message string, args ...interface{}) {\n\tlog.Debugf(message, args...)\n}" ]
[ "0.71186876", "0.6873359", "0.6740789", "0.6731206", "0.66628754", "0.66362834", "0.65750813", "0.6462784", "0.6460342", "0.64532936", "0.6423005", "0.6422269", "0.63407636", "0.63320094", "0.632745", "0.6321187", "0.6297259", "0.62850803", "0.6251222", "0.62383026", "0.6230234", "0.62295395", "0.62178814", "0.6217413", "0.62076277", "0.6207028", "0.62047017", "0.62019336", "0.6185602", "0.61647063", "0.61436605", "0.6137362", "0.6117908", "0.61017865", "0.6084214", "0.60773623", "0.6074396", "0.6072729", "0.6071282", "0.60674894", "0.6059133", "0.6058532", "0.60431254", "0.6042573", "0.60396093", "0.60313404", "0.60313404", "0.6027855", "0.6021138", "0.6010745", "0.6005649", "0.60033226", "0.6000846", "0.59985626", "0.59919375", "0.599145", "0.598866", "0.59863687", "0.598198", "0.59818494", "0.59778225", "0.5974525", "0.5974304", "0.597135", "0.5967653", "0.59673953", "0.59659946", "0.5964543", "0.5964353", "0.5960745", "0.5960745", "0.5959591", "0.5956691", "0.5955398", "0.59449226", "0.59448844", "0.594356", "0.59433514", "0.5941775", "0.5941644", "0.5940081", "0.59400505", "0.59399015", "0.5933183", "0.59310305", "0.59285855", "0.59282255", "0.5926177", "0.5916693", "0.5910438", "0.5903835", "0.5902538", "0.58990526", "0.5898913", "0.58985853", "0.58821124", "0.58779377", "0.5875454", "0.5871947", "0.5871063", "0.5869931" ]
0.0
-1
RegisterAction registers a go function so it can be used as an action in a flow stage
func RegisterAction(actionFunc interface{}) { if reflect.TypeOf(actionFunc).Kind() != reflect.Func { panic("Action must be a function!") } actions[getActionKey(actionFunc)] = actionFunc }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Controller) RegisterAction(a *Action) {\n\tc.Actions = append(c.Actions, a)\n}", "func Register(name string, initFunc InitFunc) error {\n\tif _, exists := actions[name]; exists {\n\t\treturn fmt.Errorf(\"action name already registered %s\", name)\n\t}\n\tactions[name] = initFunc\n\n\treturn nil\n}", "func RegisterAction() {\n\tengine.RegisterAction(\"cron\", NewCron)\n}", "func NewRegisterAction(dispatch Dispatch, executor cf.Executor) *HTTPRegisterAction {\n\treturn &HTTPRegisterAction{dispatch, executor}\n}", "func (bar *ActionBar) RegisterAction(action *Action) {\n\tbar.Actions = append(bar.Actions, action)\n}", "func (w *Widget) Register(name string, action IAction) {\n\tw.actions[name] = action\n}", "func RegulatedAction() {\n\t// Some expensive action goes on here\n}", "func (c *MockClient) RegisterActionEvent(actions chan<- service.DIDCommAction) error {\n\tif c.ActionEventFunc != nil {\n\t\treturn c.ActionEventFunc(actions)\n\t}\n\n\treturn nil\n}", "func Register(actionType string, action Action) {\n\tactionsMu.Lock()\n\tdefer actionsMu.Unlock()\n\n\tif actionType == \"\" {\n\t\tpanic(\"action.Register: actionType is empty\")\n\t}\n\n\tif action == nil {\n\t\tpanic(\"action.Register: action is nil\")\n\t}\n\n\tif _, dup := actions[actionType]; dup {\n\t\tpanic(\"action.Register: action already registered for action type: \" + actionType)\n\t}\n\n\t// copy on write to avoid synchronization on access\n\tnewActions := make(map[string]Action, len(actions))\n\n\tfor k, v := range actions {\n\t\tnewActions[k] = v\n\t}\n\n\tnewActions[actionType] = action\n\tactions = newActions\n\n\tlog.Debugf(\"Registerd Action: %s\", actionType)\n}", "func (server *Server) Register(action INetworkAction) {\n\n}", "func (client *Client) Register(action INetworkAction) {\n\tclient.actions = append(client.actions, action)\n}", "func AddActionAction(c *gin.Context) {\n\tresult := render.NewResult()\n\tdefer c.JSON(http.StatusOK, result)\n\n\taction := &model.Action{}\n\tif err := c.BindJSON(action); nil != err {\n\t\tresult.Error(err)\n\n\t\treturn\n\t}\n\n\tsrv := service.FromContext(c)\n\tif err := srv.Actions.Create(c, action); nil != err {\n\t\tresult.Error(err)\n\t}\n}", "func (o *Observer) RegisterAction(topic string, ch <-chan service.DIDCommAction) {\n\tgo func() {\n\t\tfor action := range ch {\n\t\t\to.notify(topic, toAction(action))\n\t\t}\n\t}()\n}", "func NewAction(name string, arg interface{}) {\n\tDefaultActionRegistry.Post(name, arg)\n}", "func (ar *ActionRepository) Register(matchingPath string, name string, method actionMethod) {\n\tar.actions[name] = method\n\t_, ok := ar.actionsForPath[matchingPath]\n\tif !ok {\n\t\tar.actionsForPath[matchingPath] = make(map[string]actionMethod)\n\t}\n\tar.actionsForPath[matchingPath][name] = method\n}", "func (action HTTPRegisterAction) RegisterService(sourcename string, route string) error {\n\n\tfmt.Printf(\"Registering source %q to route %q... \\n\", sourcename, route)\n\n\t//create the source\n\terr := action.Dispatch.CreateSource(sourcename, route)\n\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: could not create source \", err)\n\t\tos.Exit(1)\n\t}\n\n\terr = action.Executor.PauseUntilCreateFinished(sourcename)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR: could not create source \", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn nil\n}", "func Register(kind Kind, create CreateFn) error {\n\tif !kind.Validate() {\n\t\treturn errors.Errorf(\"invalid kind: %s\", kind)\n\t}\n\tif _, ok := Factory[kind]; ok {\n\t\treturn errors.Errorf(\"duplicate to register action executor: %s\", kind)\n\t}\n\tFactory[kind] = create\n\treturn nil\n}", "func (f *Flame) Action(h Handler) {\n\tf.action = validateAndWrapHandler(h, nil)\n}", "func init() {\n\tRegisterAction(\"json\", newJsonAction)\n}", "func (io *IO) AddActionHandler(action string, handler func(*Socket, *Action), credentials []string) {\n\tio.actions[action] = []ActionHandler{ActionHandler{Handler: handler, Credentials: credentials}}\n}", "func (tqsc *Controller) Register() {\n}", "func SetAction(name string, action func()) {\n\tif name == \"\" {\n\t\tpanic(\"daemonigo.SetAction(): name cannot be empty\")\n\t}\n\tif action == nil {\n\t\tpanic(\"daemonigo.SetAction(): action cannot be nil\")\n\t}\n\tactions[name] = action\n}", "func RegisterEventFilterAction(svc *graphql.Service) {\n\tsvc.RegisterEnum(_EnumTypeEventFilterActionDesc)\n}", "func (node *Node) action(action ActionOnNodeFunc) error {\n\tnode.mutex.Lock()\n\tdefer node.mutex.Unlock()\n\n\treturn action(node)\n}", "func (r *Resolver) Action() generated.ActionResolver { return &actionResolver{r} }", "func (m *Bigo) Action(handler Handler) {\n\tvalidateHandler(handler)\n\tm.action = handler\n}", "func (a *Agent) InjectAction(actionID string) (loadtest.Status, error) {\n\tvar status loadtest.Status\n\tresp, err := a.apiPost(a.apiURL+a.id+\"/inject?action=\"+actionID, nil)\n\tif err != nil {\n\t\treturn status, err\n\t}\n\tstatus = *resp.Status\n\treturn status, nil\n}", "func (dp *dispatcher) AddAction(ctx context.Context, action Action) error {\n\tif !dp.bk.running {\n\t\treturn fmt.Errorf(\"[err] AddAction (dispatcher not running)\")\n\t}\n\n\tif ctx == nil || action == nil {\n\t\treturn fmt.Errorf(\"[err] AddAction (empty params)\")\n\t}\n\n\tif action.GetIndex() == \"\" {\n\t\treturn fmt.Errorf(\"[err] AddAction (required index)\")\n\t}\n\n\tif action.GetOperation() == ES_CREATE && action.GetID() == \"\" {\n\t\treturn fmt.Errorf(\"[err] AddAction (if an operation is a create, it is required id)\")\n\t}\n\n\tif action.GetOperation() == ES_UPDATE {\n\t\tif _, ok := action.GetDoc()[\"doc\"]; !ok {\n\t\t\treturn fmt.Errorf(\"[err] AddAction (if an operation is a update, it is required doc key)\")\n\t\t}\n\t}\n\n\tselect {\n\tcase dp.bk.queue <- action:\n\tcase <-ctx.Done():\n\t\treturn fmt.Errorf(\"[err] AddAction timeout\")\n\t}\n\treturn nil\n}", "func Action(c *cli.Context) {\n\texec := c.String(\"exec\")\n\tfmt.Printf(\"Action: %v\\n\", exec)\n}", "func (c *ChoiceImpl) AddAction(name, description string, callback func()) error {\n\tif c.getActionByName(name) == nil {\n\t\ta := newAction(name, description, callback)\n\t\tc.actions = append(c.actions, a)\n\t\treturn nil\n\t}\n\treturn errors.New(\"An action with this name already exists\")\n}", "func addAction(s string) error {\n\tvar mutex = &sync.Mutex{}\n\tvar actionInput models.ActionInput\n\n\t// decode the input (string s)\n\terr := json.Unmarshal([]byte(s), &actionInput)\n\tif err != nil {\n\t\treturn ErrJSONMalformed\n\t}\n\n\t// validate the input fields\n\terr = actionInput.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\t//using mutex to protect critical section and prevent race conditions.\n\t// NOTE: for future consideration: we could save the map in database.\n\tmutex.Lock()\n\tac := actionMap[actionInput.Action]\n\tactionMap[actionInput.Action] = models.ActionCounter{\n\t\tTotalTime: actionInput.Time + ac.TotalTime,\n\t\tCounter: ac.Counter + 1,\n\t}\n\tmutex.Unlock()\n\n\treturn nil\n\n}", "func (cli *CLI) RegisterAny(action any) *CLI {\n\tcli.actionAnyRegister = action\n\t// check if cmd dist\n\trv := reflect.ValueOf(action)\n\tif rv.Kind() == reflect.Ptr && rv.Elem().Kind() == reflect.Struct {\n\t\trt := reflect.TypeOf(action)\n\t\tdefMth := []string{actionRunConstruct, actionRunHelp, actionRunIndex, actionRunUnmatched}\n\t\tfor i := 0; i < rv.NumMethod(); i++ {\n\t\t\tvMth := rt.Method(i)\n\t\t\tname := vMth.Name\n\t\t\tif util.ListIndex(defMth, name) > -1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcli.registerCmdList = append(cli.registerCmdList, strings.ToLower(name))\n\t\t}\n\t}\n\treturn cli\n}", "func (cli *CLI) Register(fun Function, name string, params []string, help string) {\n\tcli.commands = append(cli.commands, Command{fun, name, params, help})\n}", "func (alias *Alias) AddAction(operation, index, name string) *Alias {\n\tif alias.dict[ACTIONS] == nil {\n\t\talias.dict[ACTIONS] = []Dict{}\n\t}\n\taction := make(Dict)\n\taction[operation] = Dict{\"index\": index, \"alias\": name}\n\talias.dict[ACTIONS] = append(alias.dict[ACTIONS].([]Dict), action)\n\treturn alias\n}", "func (res *Resource) Action(actionName string, storage store.Get) {\n\tmatcher := path.Join(patID, actionName)\n\n\tres.HandleFuncC(\n\t\tpat.Get(matcher),\n\t\tfunc(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\t\t\tres.actionHandler(ctx, w, r, storage)\n\t\t},\n\t)\n\n\tres.addRoute(patch, matcher)\n}", "func Register(key string, f RunnerFunc) {\n\trunners.Store(key, f)\n}", "func (i *Irc) sendAction(channel, message string, args ...any) (string, error) {\n\tmessage = actionPrefix + \" \" + message + \"\\x01\"\n\n\treturn i.sendMessage(channel, message, args...)\n}", "func (h *Handlers) ActionAdd(w http.ResponseWriter, r *http.Request) {\n\tshort := r.FormValue(\"short\")\n\tlong := r.FormValue(\"url\")\n\tsecret := r.FormValue(\"secret\")\n\tLog.Println(short, long, secret)\n\trespStr := h.storage.AddAlias(long, short, secret)\n\tfmt.Fprint(w, respStr)\n}", "func registerAction(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method == \"POST\" {\n\n\t\tdb, err := config.GetMongoDB()\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Gagal menghubungkan ke database!\")\n\t\t\tos.Exit(2)\n\t\t}\n\n\t\tif r.FormValue(\"fullname\") == \"\" {\n\n\t\t\tmsg := []byte(\"full_name_empty\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\n\t\t} else if r.FormValue(\"email\") == \"\" {\n\t\t\tmsg := []byte(\"email_empty\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else if r.FormValue(\"password\") == \"\" {\n\t\t\tmsg := []byte(\"password_empty\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else if components.ValidateFullName(r.FormValue(\"fullname\")) == false {\n\t\t\tmsg := []byte(\"full_name_error_regex\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else if components.ValidateEmail(r.FormValue(\"email\")) == false {\n\t\t\tmsg := []byte(\"email_error_regex\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else if components.ValidatePassword(r.FormValue(\"password\")) == false {\n\t\t\tmsg := []byte(\"password_error_regex\")\n\n\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t} else {\n\n\t\t\tvar userRepository repository.UserRepository\n\n\t\t\tuserRepository = repository.NewUserRepositoryMongo(db, \"pengguna\")\n\n\t\t\tmakeID := uuid.NewV1()\n\n\t\t\thashedPassword, _ := components.HashPassword(r.FormValue(\"password\"))\n\n\t\t\tvar userModel model.User\n\n\t\t\tuserModel.ID = makeID.String()\n\n\t\t\tuserModel.FullName = r.FormValue(\"fullname\")\n\n\t\t\tuserModel.Email = r.FormValue(\"email\")\n\n\t\t\tuserModel.Password = hashedPassword\n\n\t\t\terr = userRepository.Insert(&userModel)\n\n\t\t\tif err != nil {\n\t\t\t\tmsg := []byte(\"register_error\")\n\n\t\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t\t} else {\n\t\t\t\tmsg := []byte(\"register_success\")\n\n\t\t\t\tcomponents.SetFlashMessage(w, \"message\", msg)\n\n\t\t\t\thttp.Redirect(w, r, \"/register\", 301)\n\t\t\t}\n\t\t}\n\t} else {\n\t\terrorHandler(w, r, http.StatusNotFound)\n\t}\n}", "func CreateAction(action func(*cli.Context) error) func(*cli.Context) error {\n\treturn func(c *cli.Context) error {\n\t\terr := action(c)\n\t\tif err != nil {\n\t\t\tiocli.Error(\"%s\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n}", "func (api *API) RegisterFunc(path string, fn http.HandlerFunc) {\n\tapi.hasHandlers = true\n\thttp.HandleFunc(path, api.RequireToken(fn))\n}", "func (pr *replica) addAction(act action) {\n\tif err := pr.actions.Put(act); err != nil {\n\t\treturn\n\t}\n\tpr.notifyWorker()\n}", "func (p *peer) register(send mesh.Gossip) {\n\tp.actionCh <- func() {\n\t\tp.send = send\n\t}\n}", "func (b *Bot) Register(event string, handler interface{}) int {\n\treturn b.dispatcher.Register(event, handler)\n}", "func (a *App) Action(handler Handler) {\n\tvalidateHandler(handler)\n\ta.action = handler\n}", "func Action(action string) Timer {\n\treturn defaultActions.TimerFor(action)\n}", "func (x *opBot) Register(cmd string, desc string, adminOnly bool, pvtOnly bool, enabled bool, handler func(tgbotInterface, tgbotapi.Update) error) {\n\tif x.commands == nil {\n\t\tx.commands = map[string]botCommand{}\n\t}\n\n\tx.commands[cmd] = botCommand{\n\t\tdesc: desc,\n\t\tadminOnly: adminOnly,\n\t\tpvtOnly: pvtOnly,\n\t\tenabled: enabled,\n\t\thandler: handler,\n\t}\n\tlog.Printf(\"Registered command %q, %q\", cmd, desc)\n}", "func SendAction(conn client.Connection, action *Action) (string, error) {\n\tuuid, err := utils.NewUUID()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnode := actionPath(action.HostID, uuid)\n\tif err := conn.Create(node, action); err != nil {\n\t\treturn \"\", err\n\t} else if err := conn.Set(node, action); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn uuid, nil\n}", "func (l *PluginLayer) Register(mw *layer.Layer) {\n\tmw.Use(\"error\", l.Run)\n\tmw.Use(\"request\", l.Run)\n}", "func PostAction(name string, arg interface{}) {\n\tactions.Post(name, arg)\n}", "func (mr *MockOobServiceMockRecorder) RegisterActionEvent(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"RegisterActionEvent\", reflect.TypeOf((*MockOobService)(nil).RegisterActionEvent), arg0)\n}", "func (agent *ActionAgent) dispatchAction(actionPath, data string) error {\n\tagent.actionMutex.Lock()\n\tdefer agent.actionMutex.Unlock()\n\n\tlog.Infof(\"action dispatch %v\", actionPath)\n\tactionNode, err := actionnode.ActionNodeFromJson(data, actionPath)\n\tif err != nil {\n\t\tlog.Errorf(\"action decode failed: %v %v\", actionPath, err)\n\t\treturn nil\n\t}\n\n\tcmd := []string{\n\t\tagent.vtActionBinFile,\n\t\t\"-action\", actionNode.Action,\n\t\t\"-action-node\", actionPath,\n\t\t\"-action-guid\", actionNode.ActionGuid,\n\t}\n\tcmd = append(cmd, logutil.GetSubprocessFlags()...)\n\tcmd = append(cmd, topo.GetSubprocessFlags()...)\n\tcmd = append(cmd, dbconfigs.GetSubprocessFlags()...)\n\tcmd = append(cmd, mysqlctl.GetSubprocessFlags()...)\n\tlog.Infof(\"action launch %v\", cmd)\n\tvtActionCmd := exec.Command(cmd[0], cmd[1:]...)\n\n\tstdOut, vtActionErr := vtActionCmd.CombinedOutput()\n\tif vtActionErr != nil {\n\t\tlog.Errorf(\"agent action failed: %v %v\\n%s\", actionPath, vtActionErr, stdOut)\n\t\t// If the action failed, preserve single execution path semantics.\n\t\treturn vtActionErr\n\t}\n\n\tlog.Infof(\"Agent action completed %v %s\", actionPath, stdOut)\n\tagent.afterAction(actionPath, actionNode.Action == actionnode.TABLET_ACTION_APPLY_SCHEMA)\n\treturn nil\n}", "func (f *Func) Register(vendor string, functionName string, contentType StoreContentType, handler FuncHandler) error {\n\n\tif _, ok := f.registeredFuncHandler[functionName]; ok {\n\t\t//we have already registered this function\n\t\treturn errors.New(\"Unable to register function, already exists \")\n\t}\n\n\t//register function\n\tmetadata := DataSourceMetadata{\n\t\tContentType: contentType,\n\t\tVendor: vendor,\n\t\tDataSourceType: vendor + \":func:\" + functionName,\n\t\tDataSourceID: functionName,\n\t\tStoreType: StoreTypeFunc,\n\t\tDescription: \"A function\",\n\t\tIsFunc: true,\n\t}\n\n\terr := f.csc.RegisterDatasource(metadata)\n\tif err != nil {\n\t\treturn errors.New(\"Unable to register function. \" + err.Error())\n\t}\n\n\t//register the FuncHandler\n\tf.registeredFuncHandler[functionName] = handler\n\n\t//create FuncRequestChan by observing /notification/request/functionName/*\n\t//start go routine to process events, if we have not started one already.\n\tif f.funcRequestChan == nil {\n\t\trawRequestChan, err := f.csc.observe(\"/notification/request/*\", ContentTypeJSON, zest.ObserveModeNotification)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Could not observe /notification/request/* you will not receive any requests\")\n\t\t}\n\t\tDebug(\"[Notifications] Setting up Observe on /notification/request/*\")\n\t\tgo f.parseRawFuncRequest(rawRequestChan)\n\t}\n\treturn nil\n}", "func NewAction(fn ActionFn) *Action {\n\treturn &Action{\n\t\tfn: fn,\n\t\tdoneCh: make(chan struct{}),\n\t}\n}", "func (dg *App) Register(name string, fn interface{}) (err error) {\n\tif err = dg.trans.Register(name, fn); err != nil {\n\t\treturn\n\t}\n\n\tif err = dg.b.ProducerHook(ProducerEvent.DeclareTask, name); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (L *State) Register(name string, f LuaGoFunction) {\n\tL.PushGoFunction(f)\n\tL.SetGlobal(name)\n}", "func (command *Command) Register(shell sfinterfaces.IShell) {\n\n}", "func (qiuo *QueueItemUpdateOne) AddAction(i int) *QueueItemUpdateOne {\n\tqiuo.mutation.AddAction(i)\n\treturn qiuo\n}", "func (sf *ShardFixer) Action(ctx context.Context, name string) error {\n\tif name == \"Create\" {\n\t\treturn sf.ts.CreateShard(ctx, sf.keyspace, sf.shard)\n\t}\n\tif name == \"Delete\" {\n\t\treturn sf.ts.DeleteShard(ctx, sf.keyspace, sf.shard)\n\t}\n\treturn fmt.Errorf(\"unknown ShardFixer action: %v\", name)\n}", "func (sc *ServiceController) Action(action map[string]interface{}) (bool, string) {\n\turl := urlServiceAction(sc.ID)\n\n\treturn sc.c.boolResponse(\"POST\", url, action)\n}", "func (c *GRPCClient) HandleAction(ctx context.Context, payload action.Payload) error {\n\terr := c.run(func() error {\n\t\tdata, err := json.Marshal(&payload)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treq := &dashboard.HandleActionRequest{\n\t\t\tPayload: data,\n\t\t}\n\n\t\t_, err = c.client.HandleAction(ctx, req)\n\t\tif err != nil {\n\t\t\tif s, isStatus := status.FromError(err); isStatus {\n\t\t\t\treturn errors.Errorf(\"grpc error: %s\", s.Message())\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn err\n}", "func (tc *STemplateController) action(action map[string]interface{}) error {\n\turl := urlTemplateAction(tc.ID)\n\n\treturn tc.c.boolResponse(\"POST\", url, action)\n}", "func (sh *StepHandlerState) Register(r *mango.Router) {\n\tr.Get(\"/api/simulation/{sim_id}/step/{step_id}\", sh.Get)\n\tr.Put(\"/api/simulation/{sim_id}/step/{step_id}\", sh.Put)\n}", "func importActionHandler(w http.ResponseWriter, r *http.Request, db *gorp.DbMap, c *businesscontext.Ctx) error {\n\tvar a *sdk.Action\n\turl := r.Form.Get(\"url\")\n\t//Load action from url\n\tif url != \"\" {\n\t\tvar errnew error\n\t\ta, errnew = sdk.NewActionFromRemoteScript(url, nil)\n\t\tif errnew != nil {\n\t\t\treturn errnew\n\t\t}\n\t} else if r.Header.Get(\"content-type\") == \"multipart/form-data\" {\n\t\t//Try to load from the file\n\t\tr.ParseMultipartForm(64 << 20)\n\t\tfile, _, errUpload := r.FormFile(\"UploadFile\")\n\t\tif errUpload != nil {\n\t\t\treturn sdk.WrapError(sdk.ErrWrongRequest, \"importActionHandler> Cannot load file uploaded: %s\", errUpload)\n\t\t}\n\t\tbtes, errRead := ioutil.ReadAll(file)\n\t\tif errRead != nil {\n\t\t\treturn errRead\n\t\t}\n\n\t\tvar errnew error\n\t\ta, errnew = sdk.NewActionFromScript(btes)\n\t\tif errnew != nil {\n\t\t\treturn errnew\n\t\t}\n\t} else { // a jsonified action is posted in body\n\t\tif err := UnmarshalBody(r, &a); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif a == nil {\n\t\treturn sdk.ErrWrongRequest\n\t}\n\n\ttx, errbegin := db.Begin()\n\tif errbegin != nil {\n\t\treturn errbegin\n\t}\n\n\tdefer tx.Rollback()\n\n\t//Check if action exists\n\texist := false\n\texistingAction, errload := action.LoadPublicAction(tx, a.Name)\n\tif errload == nil {\n\t\texist = true\n\t\ta.ID = existingAction.ID\n\t}\n\n\t//http code status\n\tvar code int\n\n\t//Update or Insert the action\n\tif exist {\n\t\tif err := action.UpdateActionDB(tx, a, c.User.ID); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcode = 200\n\t} else {\n\t\ta.Enabled = true\n\t\ta.Type = sdk.DefaultAction\n\t\tif err := action.InsertAction(tx, a, true); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcode = 201\n\t}\n\n\tif err := tx.Commit(); err != nil {\n\t\treturn err\n\t}\n\n\treturn WriteJSON(w, r, a, code)\n}", "func (cb *CommandBus) RegisterFunc(k string, chf cqrs.CommandHandlerFunc) {\n\tcb.handler[k] = append(cb.handler[k], chf)\n}", "func (bot *Bot) RegisterActorActions(actionsHandler *actors.ActionsHandler) {\n\tactionsHandler.RegisterAction(\"Update\", bot.update)\n}", "func Register(controller controller.Controller) {\n\tregistry.Register(controller)\n}", "func (qiu *QueueItemUpdate) AddAction(i int) *QueueItemUpdate {\n\tqiu.mutation.AddAction(i)\n\treturn qiu\n}", "func (core *coreService) SendAction(ctx context.Context, in *iotextypes.Action) (string, error) {\n\tlog.Logger(\"api\").Debug(\"receive send action request\")\n\tselp, err := (&action.Deserializer{}).SetEvmNetworkID(core.EVMNetworkID()).ActionToSealedEnvelope(in)\n\tif err != nil {\n\t\treturn \"\", status.Error(codes.InvalidArgument, err.Error())\n\t}\n\n\t// reject action if chainID is not matched at KamchatkaHeight\n\tif err := core.validateChainID(in.GetCore().GetChainID()); err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Add to local actpool\n\tctx = protocol.WithRegistry(ctx, core.registry)\n\thash, err := selp.Hash()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tl := log.Logger(\"api\").With(zap.String(\"actionHash\", hex.EncodeToString(hash[:])))\n\tif err = core.ap.Add(ctx, selp); err != nil {\n\t\ttxBytes, serErr := proto.Marshal(in)\n\t\tif serErr != nil {\n\t\t\tl.Error(\"Data corruption\", zap.Error(serErr))\n\t\t} else {\n\t\t\tl.With(zap.String(\"txBytes\", hex.EncodeToString(txBytes))).Error(\"Failed to accept action\", zap.Error(err))\n\t\t}\n\t\tst := status.New(codes.Internal, err.Error())\n\t\tbr := &errdetails.BadRequest{\n\t\t\tFieldViolations: []*errdetails.BadRequest_FieldViolation{\n\t\t\t\t{\n\t\t\t\t\tField: \"Action rejected\",\n\t\t\t\t\tDescription: action.LoadErrorDescription(err),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tst, err := st.WithDetails(br)\n\t\tif err != nil {\n\t\t\tlog.Logger(\"api\").Panic(\"Unexpected error attaching metadata\", zap.Error(err))\n\t\t}\n\t\treturn \"\", st.Err()\n\t}\n\t// If there is no error putting into local actpool,\n\t// Broadcast it to the network\n\tmsg := in\n\tif ge := core.bc.Genesis(); ge.IsQuebec(core.bc.TipHeight()) {\n\t\terr = core.messageBatcher.Put(&batch.Message{\n\t\t\tChainID: core.bc.ChainID(),\n\t\t\tTarget: nil,\n\t\t\tData: msg,\n\t\t})\n\t} else {\n\t\t//TODO: remove height check after activated\n\t\terr = core.broadcastHandler(ctx, core.bc.ChainID(), msg)\n\t}\n\tif err != nil {\n\t\tl.Warn(\"Failed to broadcast SendAction request.\", zap.Error(err))\n\t}\n\treturn hex.EncodeToString(hash[:]), nil\n}", "func (g *Game) PlayerAction(action string) {\n\tcurrPlace := g.CurrentLocation.GetHeroPlace(g.Hero)\n\n\tmaxStep := g.CurrentLocation.Size - 1\n\thero := currPlace.GetHero()\n\tmonster := currPlace.GetMonster()\n\n\tif isSkillAction(action) {\n\t\tif currPlace.IsOccupied() {\n\t\t\tres, err := fight(hero, monster, action)\n\t\t\tif err != nil {\n\t\t\t\t_ = fmt.Errorf(\"fight error: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !monster.IsAlive() {\n\t\t\t\tg.countKill(monster)\n\n\t\t\t\tcurrPlace.RemoveMonster()\n\t\t\t\tif hero.IsAlive() {\n\t\t\t\t\tres += hero.GainExperience(monster.GetExperienceValue())\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tg.View.UpdateCombatLog(res)\n\t\t} else {\n\t\t\tif action == Heal {\n\t\t\t\tres := g.Hero.UseSkill(Heal, nil)\n\t\t\t\tg.View.UpdateCombatLog(res.Message)\n\t\t\t}\n\t\t}\n\n\t\tg.checkHeroStatus()\n\t\treturn\n\t}\n\n\tif isMovement(action) {\n\t\tswitch action {\n\t\tcase MoveUp:\n\t\t\tg.Hero.MoveUp()\n\t\tcase MoveDown:\n\t\t\tg.Hero.MoveDown(maxStep)\n\t\tcase MoveLeft:\n\t\t\tg.Hero.MoveLeft()\n\t\tcase MoveRight:\n\t\t\tg.Hero.MoveRight(maxStep)\n\t\t}\n\n\t\tif currPlace.IsOccupied() {\n\t\t\tres := fightBack(hero, monster)\n\t\t\tg.View.UpdateCombatLog(res)\n\t\t}\n\t}\n\n\tg.checkHeroStatus()\n\n\tcurrPlace.RemoveHero()\n\tg.CurrentLocation.PlaceHero(g.Hero)\n}", "func (api *API) AddFlatcarAction(action *FlatcarAction) (*FlatcarAction, error) {\n\tquery, _, err := goqu.Insert(\"flatcar_action\").\n\t\tCols(\"event\", \"chromeos_version\", \"sha256\", \"needs_admin\", \"is_delta\", \"disable_payload_backoff\", \"metadata_signature_rsa\", \"metadata_size\", \"deadline\", \"package_id\").\n\t\tVals(goqu.Vals{\n\t\t\taction.Event,\n\t\t\taction.ChromeOSVersion,\n\t\t\taction.Sha256,\n\t\t\taction.NeedsAdmin,\n\t\t\taction.IsDelta,\n\t\t\taction.DisablePayloadBackoff,\n\t\t\taction.MetadataSignatureRsa,\n\t\t\taction.MetadataSize,\n\t\t\taction.Deadline,\n\t\t\taction.PackageID,\n\t\t}).\n\t\tReturning(goqu.T(\"flatcar_action\").All()).\n\t\tToSQL()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = api.db.QueryRowx(query).StructScan(action)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn action, err\n}", "func (this *actionHandler) Install(http.Handler) {}", "func (s *spec) SetAction(state Index, signal Signal, action Action) error {\n\tst, has := s.states[state]\n\tif !has {\n\t\treturn fmt.Errorf(\"no such state %v\", state)\n\t}\n\tif st.Actions == nil {\n\t\tst.Actions = map[Signal]Action{}\n\t}\n\tst.Actions[signal] = action\n\ts.states[state] = st // Update the map because the map returned a copy of the state.\n\treturn nil\n}", "func MakeAction(expr string, functor ActionFn) *Action {\n\treturn &Action{exprBase: makeExprBase(expr), functor: functor}\n}", "func CreateAction(\n\tcmd, keyB, id, secretKey string,\n\targs ...interface{}) *types.Action {\n\n\tmac := hmac.New(sha1.New, []byte(secretKey))\n\tmac.Write([]byte(cmd))\n\tmac.Write([]byte(keyB))\n\tmac.Write([]byte(id))\n\tsum := mac.Sum(nil)\n\tsumhex := hex.EncodeToString(sum)\n\n\treturn &types.Action{\n\t\tCommand: cmd,\n\t\tStorageKey: keyB,\n\t\tArgs: args,\n\t\tId: id,\n\t\tSecret: sumhex,\n\t}\n}", "func init() {\n\tRegisterAction(\"set_field\", newSetFieldAction)\n\tRegisterAction(\"unset_field\", newUnsetFieldAction)\n}", "func Action(message string) string {\n\treturn Encode(ACTION, message)\n}", "func AddAction(c *gin.Context) {\n\tvar action = models.Action{}.MapRequestToAction(c)\n\n\tvar user models.User\n\tresult := models.DB.First(&user, action.CreatedBy)\n\n\tif result.RowsAffected == 0 {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"data\": \"created_by is not a valid user id\"})\n\t\treturn\n\t}\n\n\tresult = models.DB.Create(&action)\n\n\tif result.Error != nil {\n\t\tc.JSON(http.StatusBadRequest, helpers.BadRequest())\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"data\": helpers.Results{\n\t\tCount: 1,\n\t\tResults: action,\n\t}})\n}", "func CreateAction(req *http.Request) (interface{}, error) {\n\tparam, err := newCreateParam4Create(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn createActionProcess(req, param)\n}", "func Register(name string, fc func(request *http.Request, user interface{}) bool) {\n\trole.Register(name, fc)\n}", "func (cb *CommandBus) Register(k string, h cqrs.CommandHandler) {\n\tcb.RegisterFunc(k, h.Handle)\n}", "func MustRegister(kind Kind, create CreateFn) {\n\terr := Register(kind, create)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"failed to register action executor, kind: %s, err: %v\", kind, err))\n\t}\n}", "func (m *MockOobService) RegisterActionEvent(arg0 chan<- service.DIDCommAction) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RegisterActionEvent\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (c *Controller) AfterAction(action string) {\n}", "func (c *Controller) AfterAction(action string) {\n}", "func EventAction(val string) zap.Field {\n\treturn zap.String(FieldEventAction, val)\n}", "func RegisterFunction(command string, funcItem func(*model.RequestObject, IClient, *playerModel.Player) *model.ResponseObject) {\n\tif _, exists := funcMap[command]; exists {\n\t\tpanic(fmt.Sprintf(\"%s:Function:%s has been registered.\", serverModuleName, command))\n\t}\n\n\tfuncMap[command] = funcItem\n}", "func (_ EventFilterAliases) Action(p graphql.ResolveParams) (EventFilterAction, error) {\n\tval, err := graphql.DefaultResolver(p.Source, p.Info.FieldName)\n\tret, ok := EventFilterAction(val.(string)), true\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tif !ok {\n\t\treturn ret, errors.New(\"unable to coerce value for field 'action'\")\n\t}\n\treturn ret, err\n}", "func (ctx *PluginHTTP) ExecAction(action models.Action, extraText map[string]string) {\n\tif action.DeviceName == \"\" {\n\t\tlog.Log.Debug(\"no device\")\n\t\tgo httpHandler(action, extraText)\n\t\treturn\n\t}\n\n\tdevice, err := config.GetDevice(action.DeviceName)\n\tif err != nil {\n\t\tlog.Log.Error(err.Error())\n\t\treturn\n\t}\n\tlog.Log.Debugf(\"Interacting with device '%s' doing '%s'\", device.Name, action.Name)\n\tgo httpHandlerDevice(action, device, extraText)\n}", "func (c *OrganizationsDevelopersAppsGenerateKeyPairOrUpdateDeveloperAppStatusCall) Action(action string) *OrganizationsDevelopersAppsGenerateKeyPairOrUpdateDeveloperAppStatusCall {\n\tc.urlParams_.Set(\"action\", action)\n\treturn c\n}", "func (g *Game) HandleAction(action gamework.Action) gamework.GameState {\n\n}", "func NewAction(payload interface{}) Action {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error: %v\\n\", r)\n\t\t\tfmt.Fprintf(os.Stderr, \"Payload: %v\\n\", payload)\n\t\t}\n\t}()\n\n\tvar a Action\n\ta.payload = payload\n\ta.headers = make(map[string]string)\n\n\tfor k, v := range payload.(map[interface{}]interface{}) {\n\t\tswitch k {\n\t\tcase \"catch\":\n\t\t\ta.catch = v.(string)\n\t\tcase \"warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"allowed_warnings\":\n\t\t\t// TODO\n\t\t\tcontinue\n\t\tcase \"node_selector\":\n\t\t\tcontinue\n\t\tcase \"headers\":\n\t\t\tfor kk, vv := range v.(map[interface{}]interface{}) {\n\t\t\t\ta.headers[kk.(string)] = vv.(string)\n\t\t\t}\n\t\tdefault:\n\t\t\ta.method = k.(string)\n\t\t\ta.params = v.(map[interface{}]interface{})\n\t\t}\n\t}\n\n\treturn a\n}", "func (r *Registry) RegisterHTTP(name string, fn func(http.ResponseWriter, *http.Request)) error {\n\tif _, ok := r.functions[name]; ok {\n\t\treturn fmt.Errorf(\"function name already registered: %s\", name)\n\t}\n\tr.functions[name] = RegisteredFunction{\n\t\tName: name,\n\t\tCloudEventFn: nil,\n\t\tHTTPFn: fn,\n\t}\n\treturn nil\n}", "func (_PlasmaFramework *PlasmaFrameworkTransactor) RegisterVault(opts *bind.TransactOpts, _vaultId *big.Int, _vaultAddress common.Address) (*types.Transaction, error) {\n\treturn _PlasmaFramework.contract.Transact(opts, \"registerVault\", _vaultId, _vaultAddress)\n}", "func Register(name string, action caddy.SetupFunc) {\n\tcaddy.RegisterPlugin(name, caddy.Plugin{\n\t\tServerType: \"dns\",\n\t\tAction: action,\n\t})\n}", "func (wfw *impl) Register(p ComponentInterface) {\n\tif p == nil {\n\t\tif singleton.debug {\n\t\t\tlog.Debugf(\"Register workflow application nil component. Action missed\")\n\t\t}\n\t\treturn\n\t}\n\tif singleton.debug {\n\t\tlog.Debugf(\"Register workflow application component %q\", packageName(p))\n\t}\n\twfw.Components = append(wfw.Components, p)\n}", "func (ctx *PluginsManager) ExecAction(action models.Action, extraText map[string]string) {\n\tplugin := ctx.Plugins[action.Plugin].Plugin.(pluginI)\n\tplugin.ExecAction(action, extraText)\n}", "func Register(c client.Client, logger logr.Logger) {\n\trsh := &appPipelineHandler{\n\t\tclient: c,\n\t\tlogger: logger.WithName(\"appPipelineHandler\"),\n\t}\n\n\twebhook.Register(\"appPipeline\", rsh.filter, rsh.operation)\n}", "func (c *OrganizationsSharedflowsCreateCall) Action(action string) *OrganizationsSharedflowsCreateCall {\n\tc.urlParams_.Set(\"action\", action)\n\treturn c\n}", "func Register(registerFunc RegisterFunc) {\n\t_ = registerFunc(&model.Command{\n\t\tTrigger: config.CommandTrigger,\n\t\tDisplayName: \"TODO display name\",\n\t\tDescription: \"TODO description\",\n\t\tAutoComplete: true,\n\t\tAutoCompleteDesc: \"TODO autocomplete desc\",\n\t\tAutoCompleteHint: \"TODO autocomplete hint\",\n\t})\n}" ]
[ "0.6698025", "0.6472137", "0.6467746", "0.63274443", "0.6133895", "0.61160654", "0.6039291", "0.5966115", "0.5854066", "0.57691675", "0.5761604", "0.56988126", "0.55745447", "0.5440735", "0.54097164", "0.5360043", "0.5345845", "0.525743", "0.52016634", "0.52012056", "0.5175921", "0.5175918", "0.517013", "0.5112663", "0.5108741", "0.51006794", "0.5096656", "0.5093", "0.5088257", "0.5074827", "0.50747406", "0.50561947", "0.50544167", "0.5048997", "0.50189346", "0.5012228", "0.49873695", "0.4959263", "0.49535197", "0.49507377", "0.4948253", "0.49482232", "0.49277002", "0.49242413", "0.4918827", "0.49175733", "0.4910076", "0.4909585", "0.48858672", "0.4882434", "0.48801136", "0.48782405", "0.48739854", "0.48719174", "0.48706028", "0.48630038", "0.48593584", "0.48571435", "0.4849854", "0.4844711", "0.4828413", "0.48189214", "0.48174137", "0.48164427", "0.47942308", "0.47764638", "0.4776367", "0.4773244", "0.4767595", "0.47648746", "0.47619855", "0.4760983", "0.47457758", "0.4743368", "0.47362328", "0.4731384", "0.47279537", "0.47270736", "0.47262734", "0.47243014", "0.46962377", "0.46956965", "0.4694717", "0.4684087", "0.4684087", "0.46792176", "0.46778068", "0.4675396", "0.46717054", "0.4669399", "0.46534038", "0.4652822", "0.46510413", "0.4644211", "0.46394923", "0.46364328", "0.46361855", "0.46334752", "0.4630972", "0.46292415" ]
0.75820374
0
/It is possible to return named values from a function. If a return value is named, it can be considered as being declared as a variable in the first line of the function.
func main() { fmt.Println("Named Return Values") lenght := 4 width := 4 aa := getArea(lenght, width) fmt.Println(aa) // lets say we receive aa from the function but we dont want to print it, we can use a blank identifier to // ignore the aa to get rid of "not used" error }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func functionWithnamedReturnValues(aName, aCity string, anAge int) (returnVal1 string, returnVal2 error) {\n\n\t// The returnvalues are initialised+declared for us, by the function itself\n\t// since they are part of the function's definition.\n\tfmt.Println(reflect.TypeOf(returnVal1)) // string\n\tfmt.Println(reflect.TypeOf(returnVal2)) // <nil>\n\n\tfmt.Println(\"'name' is set to:\", aName)\n\tfmt.Println(\"'city' is set to:\", aCity)\n\tfmt.Println(\"'age' is set to:\", anAge)\n\n\t// we have to create these variables as part of this function\n\t// since they have been\n\treturnVal1 = \"Villain\"\n\treturnVal2 = errors.New(\"Thanos is not an Avenger\")\n\n\t// Notice we don't have to specify what we are returning.\n\treturn\n}", "func NamedReturn() (res string) {\n\tres = \"name res\"\n\treturn\n}", "func dumbfunc() (string, int) {\n return \"Alex Herrmann\", 19\n}", "func returnMulti2() (n int, s string) {\n\tn = 42\n\ts = \"foobar\"\n\t// n and s will be returned\n\treturn\n}", "func returnMulti() (int, string) {\n\treturn 42, \"foobar\"\n}", "func LenAndUpperReturnVariable(name string) (length int, upper string) { // naked return\n\tdefer fmt.Println(\"lenAndUpperReturnVariable is Done.\") // after the function, defer clause trigger.\n\tlength = len(name)\n\tupper = strings.ToUpper(name)\n\treturn\n}", "func test1() {\r\n\t// name := \"namaei\"\r\n\treturn \"namaei\"\r\n}", "func (*UnresolvedName) Variable() {}", "func bar() (int, string) {\n\ta := 77\n\tb := \"Sunandan\"\n\treturn a, b\n}", "func DeclareVariables() {\r\n // OK\r\n word := 1\r\n multipleWords := 2\r\n // Not OK\r\n multiplewords\r\n multiple_words\r\n}", "func sommeNameReturned(x, y, z int) (somme int) {\n\tsomme = x + y + z\n\treturn somme\n}", "func (UnqualifiedStar) Variable() {}", "func returnDoses(x, y string) (x, y string) {\n return\n}", "func doubleReturn(fn, ln string) (string, bool) {\n\tformalName := fmt.Sprint(fn, \" \", ln)\n\tvar isAdmin bool\n\tif strings.Contains(strings.ToLower(fn), \"hanming\") {\n\t\tisAdmin = true\n\t}\n\treturn formalName, isAdmin\n}", "func getNamedColonValue(defaultValue, data, name string) string {\n\tval := defaultValue\n\tword := strings.Index(data, name)\n\tif word != -1 {\n\t\tstart := word + len(name) + 2\n\t\tlength := strings.Index(data[start:], \"\\n\")\n\t\tif length != -1 {\n\t\t\tval = data[start : start+length]\n\t\t}\n\t}\n\treturn val\n}", "func TestFieldWithMultipleReturnValues(t *testing.T) {\n\ttester := newCheckerTestUtil(t, `\n\t\tint x = test()\n\n\t\tfunction (int, int) test() {\n\t\t\treturn 1, 2\n\t\t}\n\t`, false)\n\n\ttester.assertErrorAt(0, \"expected 1 return value(s), but function returns 2\")\n}", "func ReturnId_Named() (id int, err error) {\n\tid = 20\n\treturn id, err\n}", "func (checker *CheckerType) VarNames() (obtained, expected string) {\n return \"obtained\", \"expected\"\n}", "func get_three_things() (string, string, string) {\n return \"thing 1\", \"thing 2\", \"thing 3\"\n}", "func AnotherThing(random string, second string) (testName string, err error) {\n\treturn \"asdf\", nil\n}", "func main() {\n\tfooValue := foo()\n\tbarValueInt, barValueString := bar()\n\n\tfmt.Printf(\"Foo stores %v, barValue stores an int which is %v, and also a string which is %v\\n\", fooValue, barValueInt, barValueString)\n}", "func ReturnValue(fn ExportedFunction) string {\n\t/*\n\t\tGiven a Go function:\n\n\t\t//export DoubleIt\n\t\tfunc DoubleIt(x int) int {\n\t\t\treturn x * 2\n\t\t}\n\n\t\tWe want C like this:\n\n\t\tSEXP DoubleIt_cstub(SEXP x){\n\t\t return Rf_ScalarInteger( DoubleIt( INTEGER(x)[0] ) ) ;\n\t\t}\n\t\tThe job of this function is to return everything after the\n\t\t\"return \" in the C code above, up-to (but not including) the semi-colon,\n\t\tso in this case:\n\t\tRf_ScalarInteger( DoubleIt( INTEGER(x)[0] ) )\n\n\t*/\n\n\treturn (\"bla bla bla\")\n}", "func (s *state) varValue(name string) reflect.Value {\n\tfor i := s.mark() - 1; i >= 0; i-- {\n\t\tif s.vars[i].name == name {\n\t\t\treturn s.vars[i].value\n\t\t}\n\t}\n\ts.errorf(\"undefined variable: %s\", name)\n\treturn zero\n}", "func getFullName()(string, string) {\n\treturn \"Ninja\", \"Coder\"\n}", "func withReturnValue() string {\n\n\treturn \"hello\"\n}", "func myFunc(x int, y int) (int, int) {\n\treturn y, x\n}", "func Function() {\n\n\t// a simple function\n\tfunctionName1()\n\n\t// function with parameters (again, types go after identifiers)\n\tfunctionName2(\"Salehin Rafi\", 26)\n\n\t// multiple parameters of the same type\n\tfunctionName3(1, 2)\n\n\t// return type declaration\n\tvar i = functionName4()\n\tfmt.Println(i)\n\n\t// return multiple values at once\n\tvar a, b = returnMulti()\n\tfmt.Println(a, b)\n\n\t// return multiple named results simply by return\n\tvar c, d = returnMulti2()\n\tfmt.Println(c, d)\n\n\t// assign a function to a name as a value\n\tadd := func(a, b int) int {\n\t\treturn a + b\n\t}\n\t// use the name to call the function\n\tfmt.Println(add(3, 4))\n\n}", "func returnArgs(a, b string ){\n\tfmt.Println(a + \" \" + b)\n}", "func main() {\n\taFunc := func(x int) (int, bool) {\n\t\treturn x / 2, x%2 == 0\n\t}\n\tvar h, e = aFunc(10)\n\tfmt.Println(h, e)\n}", "func transformReturn(rs *ir.ReturnStmt) {\n\ttransformArgs(rs)\n\tnl := rs.Results\n\tif ir.HasNamedResults(ir.CurFunc) && len(nl) == 0 {\n\t\treturn\n\t}\n\n\ttypecheckaste(ir.ORETURN, nil, false, ir.CurFunc.Type().Results(), nl)\n}", "func myFunc (nonHighlightedPrimitiveArg string, foo bar) {\n//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.function\n//^^^^^^^^^ meta.function.declaration\n// ^ - meta.function.declaration\n// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.function.parameters\n// ^ - meta.function.parameters\n// ^ storage.type\n// ^ entity.name.function\n// ^ variable.parameter\n// ^ storage.type - variable\n// ^ punctuation.separator - variable\n// ^ variable.parameter\n// ^ - variable\n// ^ meta.block punctuation.definition.block\n\treturn \"test string\"\n// ^ meta.function meta.block keyword.control\n// ^ string.quoted.double\n}", "func walkReturn(n *ir.ReturnStmt) ir.Node {\n\tfn := ir.CurFunc\n\n\tfn.NumReturns++\n\tif len(n.Results) == 0 {\n\t\treturn n\n\t}\n\n\tresults := fn.Type().Results().FieldSlice()\n\tdsts := make([]ir.Node, len(results))\n\tfor i, v := range results {\n\t\t// TODO(mdempsky): typecheck should have already checked the result variables.\n\t\tdsts[i] = typecheck.AssignExpr(v.Nname.(*ir.Name))\n\t}\n\n\tn.Results = ascompatee(n.Op(), dsts, n.Results)\n\treturn n\n}", "func main() {\r\n out := test1.DoubleValue(8) // call function in package\r\n fmt.Printf(\"Double, out = %d\\n\", out) // should print \"..out = 16\"\r\n// out := test1.TripleVariable(8), call function in package\r\n// fmt.Printf(\"Triple, out = %d\\n, out\") // should print \"..out = 16\"\r\n}", "func (result *Result) Named() *NamedResult {\n\treturn ToNamedResult(result)\n}", "func (p ByName) ValueName() string { return p.valueName }", "func main() {\n\tid, err := ReturnId()\n\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: %s\", err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Id: %d\\n\", id)\n\n\tid2, _ := ReturnId_Named()\n\tfmt.Printf(\"Id: %d\\n\", id2)\n\n\tid3, _ := ReturnId_Naked()\n\tfmt.Printf(\"Id: %d\\n\", id3)\n}", "func FullNameNakedReturn(f, l string) (full string, length int) {\n full = f + \" \" + l;\n length = len(full)\n return \n}", "func getvarname(s string) (string, string) {\n\tif strings.Contains(s, \"=\") {\n\t\t// int a = 0; or void(*aaa)() = 0;\n\t\ts = strings.Split(s, \"=\")[0] + \";\"\n\t}\n\tfields := strings.Split(s, \";\")\n\tif len(fields) == 1 && strings.Contains(s, \"(\") {\n\t\t// function pointer\n\t\tfields = strings.Split(s, \"(\")\n\t\tfields = strings.Split(fields[1], \")\")\n\t\treturn strings.Trim(fields[0], \"*\"), \"void*\"\n\t}\n\tfor {\n\t\tif fields[0] == \"static\" || fields[0] == \"__thread\" {\n\t\t\tfields = fields[1:]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tgopp.Assert(len(fields) > 1, \"wtfff\", len(fields), s)\n\tfields2 := strings.Split(strings.TrimSpace(fields[0]), \" \")\n\tfields3 := []string{}\n\tfor _, fld := range fields2 {\n\t\tif fld == \"extern\" || fld == \"const\" {\n\t\t\tcontinue\n\t\t}\n\t\tfields3 = append(fields3, fld)\n\t}\n\tfields2 = fields3\n\t//log.Println(s, len(fields2), fields2)\n\n\ttyname := strings.Join(fields2[0:len(fields2)-1], \" \")\n\tfuncname := fields2[len(fields2)-1]\n\tfor {\n\t\tif strings.HasPrefix(funcname, \"*\") {\n\t\t\ttyname += \"*\"\n\t\t\tfuncname = funcname[1:]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn funcname, tyname\n}", "func GiveName(m map[string]string) (string, bool) {\n\tval, exist := m[FirstName]\n\treturn val, exist\n}", "func (p *FuncInfo) Return(out ...exec.Var) exec.FuncInfo {\n\tp.out = out\n\treturn p\n}", "func _return(i Instruction, ls *LuaState) {\n\ta, b, _ := i.ABC()\n\ta += 1\n\n\tif b == 1 {\n\t\t// no return values\n\t} else if b > 1 {\n\t\t// b-1 return values\n\t\tluaCheckStack(ls, b-1)\n\t\tfor i := a; i <= a+b-2; i++ {\n\t\t\tluaPushValue(ls, i)\n\t\t}\n\t} else {\n\t\t_fixStack(a, ls)\n\t}\n}", "func test6() (int, s string, e error) {\n\n\treturn \"\", \"s\", nil\n}", "func (nvp *nameValParser) next() (*symval, *symval, error) {\n\n\tvar name *symval\n\n\tif nvp.name == nil {\n\t\ttoken, s, err := nvp.t.next()\n\t\tif token == tokenError {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tswitch token {\n\t\tcase tokenEnd:\n\t\t\treturn nil, nil, nil\n\t\tcase tokenEqual:\n\t\t\treturn nil, nil, fmt.Errorf(`at \"%s\": \"%c\" unexpected`, nvp.t.errorContext(), nvp.t.config.GetSpecial(SpecSeparator))\n\t\tcase tokenString:\n\t\t\tname = s\n\t\t}\n\t} else {\n\t\tname, nvp.name = nvp.name, nil\n\t}\n\n\t// got a name so far, if next token is a string, it's in fact a standalone value\n\ttoken, s, err := nvp.t.next()\n\tif token == tokenError {\n\t\treturn nil, nil, decorate(err, name.s)\n\t}\n\n\tswitch token {\n\tcase tokenEnd:\n\t\t// single string: by convention put it in the value\n\t\treturn nil, name, nil\n\tcase tokenEqual:\n\t\t// expect now a value\n\tcase tokenString:\n\t\t// standalone value, swap and save\n\t\tnvp.name = s\n\t\treturn nil, name, nil\n\t}\n\n\t// after name and separator, expect value (string)\n\n\ttoken, s, err = nvp.t.next()\n\tif token == tokenError {\n\t\treturn nil, nil, decorate(err, name.s)\n\t}\n\tswitch token {\n\tcase tokenEnd:\n\t\treturn nil, nil, fmt.Errorf(`at \"%s\": premature end of input`, nvp.t.errorContext())\n\tcase tokenEqual:\n\t\treturn nil, nil, fmt.Errorf(`at \"%s\": \"%c\" unexpected`, nvp.t.errorContext(), nvp.t.config.GetSpecial(SpecSeparator))\n\tcase tokenString:\n\t\treturn name, s, nil\n\t}\n\tpanic(\"unreachable\")\n}", "func (args *Args) value(name string) interface{} {\n\tfor _, arg := range args.items {\n\t\tif arg.name == name {\n\t\t\treturn arg.value\n\t\t}\n\t}\n\treturn nil\n}", "func getValues() (interface{}, interface{}) {\n\t//return 23, 23\n\treturn \"Raja\", \"Lekkala\" // ERROR : cannot convert \"Raja\" (untyped string constant) to int\n}", "func main() {\n\ta := foo(24)\n\tb, c := bar(18, \"erlangga\")\n\n\tfmt.Println(a)\n\tfmt.Println(b, c)\n}", "func (r *reflex) valueByName(value reflect.Value, name string) any {\n\tif fieldValue := value.FieldByName(name); !fieldValue.IsNil() {\n\t\treturn fieldValue.Elem().Interface()\n\t}\n\treturn nil\n}", "func multipleReturn() (int, int) {\n\treturn 61, 19\n}", "func (fn *formulaFuncs) VAR(argsList *list.List) formulaArg {\n\treturn fn.vars(\"VAR\", argsList)\n}", "func main() {\n\ts:=foo()\n\tfmt.Println(s)\n}", "func (m *RegistryKeyState) GetValueName()(*string) {\n return m.valueName\n}", "func (state *State) FetchVariable(name string) (val *Value) {\n\tdefer func(){\n\t\tif x := recover(); x != nil {\n\t\t\tval = nil\n\t\t}\n\t}()\n\t\n\tparts := strings.Split(name, \":\")\n\tif len(parts) < 2 {\n\t\treturn nil\n\t}\n\tmod := state.FetchModule(parts[0])\n\tfor i := range parts[1:len(parts) - 1] {\n\t\tmod = mod.FetchModule(parts[i+1])\n\t}\n\tif mod == nil {\n\t\treturn nil\n\t}\n\tvalI := mod.vars.lookup(parts[len(parts) - 1])\n\treturn mod.vars.get(valI)\n}", "func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {\n\tdargs := make([]driver.Value, len(named))\n\tfor n, param := range named {\n\t\tif len(param.Name) > 0 {\n\t\t\treturn nil, errors.New(\"sql: driver does not support the use of Named Parameters\")\n\t\t}\n\t\tdargs[n] = param.Value\n\t}\n\treturn dargs, nil\n}", "func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {\n\tdargs := make([]driver.Value, len(named))\n\tfor n, param := range named {\n\t\tif len(param.Name) > 0 {\n\t\t\treturn nil, errors.New(\"sql: driver does not support the use of Named Parameters\")\n\t\t}\n\t\tdargs[n] = param.Value\n\t}\n\treturn dargs, nil\n}", "func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {\n\tdargs := make([]driver.Value, len(named))\n\tfor n, param := range named {\n\t\tif len(param.Name) > 0 {\n\t\t\treturn nil, errors.New(\"sql: driver does not support the use of Named Parameters\")\n\t\t}\n\t\tdargs[n] = param.Value\n\t}\n\treturn dargs, nil\n}", "func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error) {\n\tdargs := make([]driver.Value, len(named))\n\tfor n, param := range named {\n\t\tif len(param.Name) > 0 {\n\t\t\treturn nil, errors.New(\"sql: driver does not support the use of Named Parameters\")\n\t\t}\n\t\tdargs[n] = param.Value\n\t}\n\treturn dargs, nil\n}", "func FuncInferred(arg1, arg2 int) (ret1, ret2 bool) {}", "func findValue(token Token) (interface{}, error) {\n\t// TODO - more types\n\tswitch token.Kind {\n\tcase Floating:\n\t\tf, err := strconv.ParseFloat(token.name, 64)\n\t\tif err != nil {\n\t\t\treturn nil, e(`could not convert to float → \"` + err.Error() + `\"`)\n\t\t}\n\n\t\treturn f, nil\n\n\tcase Integral:\n\t\tn, err := strconv.ParseInt(token.name, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, e(`could not convert to number → \"` + err.Error() + `\"`)\n\t\t}\n\n\t\treturn n, nil\n\n\tcase Procedure:\n\t\t// TODO - Do we need to look this up twice? Might be redundant with map initialization\n\t\tswitch token.name {\n\t\tcase \"+\":\n\t\t\treturn symbols[\"+\"].Contents, nil\n\t\tcase \"-\":\n\t\t\treturn symbols[\"-\"].Contents, nil\n\t\tdefault:\n\t\t\treturn nil, e(`unknown procedure \"` + token.name + `\"`)\n\t\t}\n\n\tdefault:\n\t\treturn nil, e(`unknown type, cannot determine value of \"` + token.Kind.String() + `\"`)\n\t}\n\n\t// Unreachable\n\n}", "func (p *Parser) parseAssignedNames() ([]*ast.NameWithPos, int, []*ast.Expression, *ast.VariableType, error) {\n\tnames, err := p.parseNameList()\n\tif err != nil {\n\t\treturn nil, 0, nil, nil, err\n\t}\n\t//trying to parse type\n\tvar variableType *ast.VariableType\n\tif p.token.Type != lex.TOKEN_ASSIGN && p.token.Type != lex.TOKEN_COLON_ASSIGN {\n\t\tvariableType, err = p.parseType()\n\t\tif err != nil {\n\t\t\tp.errs = append(p.errs, err)\n\t\t}\n\t\treturn nil, 0, nil, nil, err\n\t}\n\tif p.token.Type != lex.TOKEN_ASSIGN && p.token.Type != lex.TOKEN_COLON_ASSIGN {\n\t\terr = fmt.Errorf(\"%s missing = or := after a name list\", p.errorMsgPrefix())\n\t\tp.errs = append(p.errs, err)\n\t\treturn nil, 0, nil, nil, err\n\t}\n\ttyp := p.token.Type\n\tp.Next()\n\tif p.eof {\n\t\terr = p.mkUnexpectedEofErr()\n\t\tp.errs = append(p.errs, err)\n\t\treturn names, typ, nil, variableType, err\n\t}\n\tes, err := p.ExpressionParser.parseExpressions()\n\tif err != nil {\n\t\treturn names, typ, nil, variableType, err\n\t}\n\tif len(es) != len(names) {\n\t\terr = fmt.Errorf(\"%s mame and value not match\", p.errorMsgPrefix())\n\t\tp.errs = append(p.errs, err)\n\t\treturn names, typ, es, variableType, err\n\t}\n\treturn names, typ, es, variableType, nil\n}", "func name(out *string) Parser {\r\n\treturn func(code string) (string, error) {\r\n\t\tcode, name, err := ParseName(code)\r\n\t\tif err == nil {\r\n\t\t\t*out = name\r\n\t\t}\r\n\t\treturn code, err\r\n\t}\r\n}", "func f(a int, b int, c string, d int) {\n x = 5\n func k(a int, b string) {\n\n }\n return\n}", "func (p *variables) Var(name string) interface{} {\n\n\tif k, ok := p.symtbl[name]; ok {\n\t\treturn p.vars[k]\n\t}\n\treturn qlang.Undefined\n}", "func parseNextVariable(pos int, value string, prefix string) (int, string, bool) {\n\n\tendSign := \"}\"\n\tposStart := strings.Index(value[pos:], prefix+\"{\")\n\tif posStart < 0 {\n\t\treturn -1, \"\", false\n\t}\n\tposStart += pos\n\n\tif string(value[posStart+2]) == \"{\" {\n\t\tendSign = \"}}\"\n\t}\n\n\tposEnd := strings.Index(value[posStart+2:], endSign)\n\tif posEnd < 0 {\n\t\t//bad value\n\t\treturn -1, \"\", false\n\t}\n\tposEnd += posStart + 1 + len(endSign)\n\twholeValue := posStart == 0 && posEnd == len(value)-1\n\n\treturn posStart, value[posStart+2 : posEnd], wholeValue\n}", "func ifelse () string {\n if name := \"Olivia\"; false {\n } else {\n return name\n }\n return \"Wrong\"\n}", "func main(){\n\n \n var (\n a = 5\n b = 10\n c = \"Helo World\"\n\n )\n\n fmt.Println(a, b, c)\n}", "func (fn *formulaFuncs) vars(name string, argsList *list.List) formulaArg {\n\tif argsList.Len() < 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf(\"%s requires at least 1 argument\", name))\n\t}\n\tsummerA, summerB, count := 0.0, 0.0, 0.0\n\tminimum := 0.0\n\tif name == \"VAR\" || name == \"VAR.S\" || name == \"VARA\" {\n\t\tminimum = 1.0\n\t}\n\tfor arg := argsList.Front(); arg != nil; arg = arg.Next() {\n\t\tfor _, token := range arg.Value.(formulaArg).ToList() {\n\t\t\tif token.Value() == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnum := token.ToNumber()\n\t\t\tif token.Value() != \"TRUE\" && num.Type == ArgNumber {\n\t\t\t\tsummerA += num.Number * num.Number\n\t\t\t\tsummerB += num.Number\n\t\t\t\tcount++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnum = token.ToBool()\n\t\t\tif num.Type == ArgNumber {\n\t\t\t\tsummerA += num.Number * num.Number\n\t\t\t\tsummerB += num.Number\n\t\t\t\tcount++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif name == \"VARA\" || name == \"VARPA\" {\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t}\n\tif count > minimum {\n\t\tsummerA *= count\n\t\tsummerB *= summerB\n\t\treturn newNumberFormulaArg((summerA - summerB) / (count * (count - minimum)))\n\t}\n\treturn newErrorFormulaArg(formulaErrorDIV, formulaErrorDIV)\n}", "func getNamedQuotedValue(defaultValue, data, name string) string {\n\tval := defaultValue\n\n\tword := strings.Index(data, name)\n\tif word != -1 {\n\t\tfirstQuote := strings.Index(data[word:], \"\\\"\")\n\n\t\tif firstQuote != -1 {\n\t\t\tsecondQuote := strings.Index(data[word+firstQuote+1:], \"\\\"\")\n\n\t\t\tif secondQuote != -1 {\n\t\t\t\tval = data[word+firstQuote+1 : word+firstQuote+1+secondQuote]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn val\n}", "func NamedValue(name string, value interface{}) interface{} {\n\treturn &namedValue{\n\t\tname: name,\n\t\tvalue: value,\n\t}\n}", "func (_f12 *FakeInterfacer) NamedInterfaceResultsForCall(a interface{}) (z interface{}, found bool) {\n\tfor _, call := range _f12.NamedInterfaceCalls {\n\t\tif reflect.DeepEqual(call.Parameters.A, a) {\n\t\t\tz = call.Results.Z\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}", "func typeOfReturnValue(value interface{}) (t Type, className string, err error) {\n\tif v, ok := value.(string); ok {\n\t\treturn typeOfValue(ObjectType(v))\n\t}\n\treturn typeOfValue(value)\n}", "func f1(arg int) (int, error) {\n if arg == 1 {\n return -1, errors.New(\"no 1!\")\n }\n return arg + 3, nil\n}", "func ( b *binIoRoundtripTestBuilder ) getVal( nm string ) interface{} {\n if val, ok := b.nmCheck[ nm ]; ok { return val }\n panic( libErrorf( \"valMap[ %q ]: no value\", nm ) )\n}", "func (lscript *Scripting) returnFromScripting(n int) *ScriptingReturnValues {\n\tvalues := make([]lua.LValue, n)\n\ti, j := n, -1\n\tfor ; i > 0; i-- {\n\t\tlv := lscript.Get(j)\n\t\tvalues[-(j + 1)] = lv\n\t\tT().Debugf(\"return value %d = %v\", -(j + 1), lv)\n\t\tj--\n\t}\n\tlscript.Pop(n)\n\trv := &ScriptingReturnValues{values: values}\n\treturn rv\n}", "func getFullName() (firstName, middleName, lastName string) {\n\tfirstName = \"tegar\"\n\tmiddleName = \"akmal\"\n\tlastName = \"2\"\n\treturn\n\n}", "func (p *Parser) parseVarDefinition(ispublic ...bool) (vs []*ast.VariableDefinition, err error) {\n\tp.Next()\n\tif p.eof {\n\t\terr = p.mkUnexpectedEofErr()\n\t\tp.errs = append(p.errs, err)\n\t\treturn\n\t}\n\tnames, err := p.parseNameList()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif p.eof {\n\t\terr = p.mkUnexpectedEofErr()\n\t\tp.errs = append(p.errs, err)\n\t\treturn\n\t}\n\tt, err := p.parseType()\n\tif t == nil {\n\t\terr = fmt.Errorf(\"%s no variable type found or defined wrong\", p.errorMsgPrefix())\n\t\tp.errs = append(p.errs, err)\n\t\treturn nil, err\n\t}\n\tvar expressions []*ast.Expression\n\t//value , no default value definition\n\tif lex.TOKEN_ASSIGN == p.token.Type {\n\t\t//assign\n\t\tp.Next() // skip =\n\t\texpressions, err = p.ExpressionParser.parseExpressions()\n\t\tif err != nil {\n\t\t\tp.errs = append(p.errs, err)\n\t\t}\n\t}\n\tif p.token.Type != lex.TOKEN_SEMICOLON {\n\t\terr = fmt.Errorf(\"%s not a \\\";\\\" after a variable declare \", p.errorMsgPrefix())\n\t\tp.errs = append(p.errs, err)\n\t\treturn\n\t}\n\tp.Next() // look next\n\tif len(expressions) > 0 && len(names) != len(expressions) {\n\t\terr = fmt.Errorf(\"%s name list and value list has no same length\", p.errorMsgPrefix())\n\t\tp.errs = append(p.errs, err)\n\t\treturn\n\t}\n\tvs = make([]*ast.VariableDefinition, len(names))\n\tfor k, v := range names {\n\t\tvd := &ast.VariableDefinition{}\n\t\tvd.Name = v.Name\n\t\tvt := &ast.VariableType{} // new a type\n\t\t*vt = *t\n\t\tvd.Typ = vt\n\t\tif len(ispublic) > 0 && ispublic[0] {\n\t\t\tvd.AccessFlags |= cg.ACC_FIELD_PUBLIC\n\t\t} else {\n\t\t\tvd.AccessFlags |= cg.ACC_FIELD_PRIVATE\n\t\t}\n\t\tvd.Pos = v.Pos\n\t\tvs[k] = vd\n\t}\n\treturn vs, nil\n}", "func getFullName() (string, string, string) {\n\treturn \"Nabil\", \"Fawwaz\", \"Elqayyim\"\n}", "func swap(x, y string) (string, string) { // type of returned variables can be written in bracket\n\treturn y, x\n}", "func functionReturningBasicError(arg int) (int, error) {\n\tif arg == 42 {\n\t\treturn -1, errors.New(\"cant' work with 42\")\n\t}\n\treturn arg + 3, nil\n}", "func functionName4() int {\n\treturn 42\n}", "func (i definitionsIndex) get(name, definitionFrom string) (*statusVariableDefinition, error) {\n\t// If no variable with this name exists return an error.\n\tif _, ok := i[name]; !ok {\n\t\treturn nil, errors.Errorf(\"no definitions found for variable %q\", name)\n\t}\n\n\t// If the definition exists for the specific definitionFrom, return it.\n\tif def, ok := i[name][definitionFrom]; ok {\n\t\treturn def, nil\n\t}\n\n\t// If definitionFrom is empty and there are no conflicts return a definition with an emptyDefinitionFrom.\n\tif definitionFrom == emptyDefinitionFrom {\n\t\tfor _, def := range i[name] {\n\t\t\tif !def.Conflicts {\n\t\t\t\treturn &statusVariableDefinition{\n\t\t\t\t\tName: def.Name,\n\t\t\t\t\tConflicts: def.Conflicts,\n\t\t\t\t\tClusterClassStatusVariableDefinition: &clusterv1.ClusterClassStatusVariableDefinition{\n\t\t\t\t\t\t// Return the definition with an empty definitionFrom. This ensures when a user gets\n\t\t\t\t\t\t// a definition with an emptyDefinitionFrom, the return value also has emptyDefinitionFrom.\n\t\t\t\t\t\t// This is used in variable defaulting to ensure variables that only need one value for multiple\n\t\t\t\t\t\t// definitions have an emptyDefinitionFrom.\n\t\t\t\t\t\tFrom: emptyDefinitionFrom,\n\t\t\t\t\t\tRequired: def.Required,\n\t\t\t\t\t\tSchema: def.Schema,\n\t\t\t\t\t},\n\t\t\t\t}, nil\n\t\t\t}\n\t\t\treturn nil, errors.Errorf(\"variable %q has conflicting definitions. It requires a non-empty `definitionFrom`\", name)\n\t\t}\n\t}\n\treturn nil, errors.Errorf(\"no definitions found for variable %q from %q\", name, definitionFrom)\n}", "func returnthem(number int) (int, int){\n\treturn number + 1, number + 2\n}", "func (p *Parser) nextReturn() {\n\tp.enter()\n\tp.nextExpected(token.RETURN)\n\tp.nextExpression()\n\tp.exit()\n}", "func vals() (int, int) {\n\treturn 3, 7 // Return results\n}", "func valueResponse(name string, v interface{}) map[string]interface{} {\n\treturn map[string]interface{}{\"name\": name, \"data\": map[string]interface{}{\"value\": v}}\n}", "func getvariables(fn *Node) []*Node {\n\tresult := make([]*Node, 0, 0)\n\tfor ll := fn.Func.Dcl; ll != nil; ll = ll.Next {\n\t\tif ll.N.Op == ONAME {\n\t\t\t// In order for GODEBUG=gcdead=1 to work, each bitmap needs\n\t\t\t// to contain information about all variables covered by the bitmap.\n\t\t\t// For local variables, the bitmap only covers the stkptrsize\n\t\t\t// bytes in the frame where variables containing pointers live.\n\t\t\t// For arguments and results, the bitmap covers all variables,\n\t\t\t// so we must include all the variables, even the ones without\n\t\t\t// pointers.\n\t\t\t//\n\t\t\t// The Node.opt field is available for use by optimization passes.\n\t\t\t// We use it to hold the index of the node in the variables array, plus 1\n\t\t\t// (so that 0 means the Node is not in the variables array).\n\t\t\t// Each pass should clear opt when done, but you never know,\n\t\t\t// so clear them all ourselves too.\n\t\t\t// The Node.curfn field is supposed to be set to the current function\n\t\t\t// already, but for some compiler-introduced names it seems not to be,\n\t\t\t// so fix that here.\n\t\t\t// Later, when we want to find the index of a node in the variables list,\n\t\t\t// we will check that n->curfn == curfn and n->opt > 0. Then n->opt - 1\n\t\t\t// is the index in the variables list.\n\t\t\tll.N.Opt = nil\n\n\t\t\t// The compiler doesn't emit initializations for zero-width parameters or results.\n\t\t\tif ll.N.Type.Width == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tll.N.Curfn = Curfn\n\t\t\tswitch ll.N.Class {\n\t\t\tcase PAUTO:\n\t\t\t\tif haspointers(ll.N.Type) {\n\t\t\t\t\tll.N.Opt = int32(len(result))\n\t\t\t\t\tresult = append(result, ll.N)\n\t\t\t\t}\n\n\t\t\tcase PPARAM, PPARAMOUT:\n\t\t\t\tll.N.Opt = int32(len(result))\n\t\t\t\tresult = append(result, ll.N)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}", "func main() {\n\n\t// There is a function we called that shorthand but this we can prevent globally define value to call.\n\t// Always remember if value is declare but not used it will raise an error in Golang\n\t// This will print the output\n\tname := \"Gautam\"\n\tage := 34\n\tprice := 11.1\n\tcontact, email := 98765432, \"ambergautam1@gmail.com\"\n\tfmt.Println(value1)\n\tfmt.Println(age)\n\tfmt.Println(price)\n\tfmt.Println(name)\n\tfmt.Println(contact)\n\tfmt.Println(email)\n\n\n}", "func helper(k string) interface{} {\n\treturn k\n}", "func getfuncname(s string) (string, string) {\n\tfields := strings.Split(s, \"(\")\n\tgopp.Assert(len(fields) > 1, \"wtfff\", s)\n\tfields2 := strings.Split(strings.TrimSpace(fields[0]), \" \")\n\tfields3 := []string{}\n\tfor _, fld := range fields2 {\n\t\tif fld == \"extern\" || fld == \"const\" {\n\t\t\tcontinue\n\t\t}\n\t\tfields3 = append(fields3, fld)\n\t}\n\tfields2 = fields3\n\t//log.Println(s, len(fields2), fields2)\n\n\ttyname := strings.Join(fields2[0:len(fields2)-1], \" \")\n\tfuncname := fields2[len(fields2)-1]\n\tfor {\n\t\tif strings.HasPrefix(funcname, \"*\") {\n\t\t\ttyname += \"*\"\n\t\t\tfuncname = funcname[1:]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn funcname, tyname\n}", "func (args *Args) Value(label string) string {\n if val, ok := (*args)[label]; ok {\n return val\n }\n return \"\"\n}", "func GetVariables() (int, int, int) {\n\treturn 1, 2, 3\n}", "func bar() func() {\n\tfmt.Print(\"We are about to return foo\")\n\treturn foo\n}", "func functionFour(pronoun string) (success bool) {\n\tsuccess = false // always assign a default value to named return values\n\n\tfmt.Println(\"function #4\")\n\tfmt.Println(\"Hello, \", pronoun)\n\n\tsuccess = true\n\n\treturn\n}", "func (p *parser) parseReturnStmt() tree.Stmt {\n\tstmt := &tree.ReturnStmt{}\n\tstmt.ReturnToken = p.expectToken(token.RETURN)\n\tif p.isBlockFollow() || p.tok == token.SEMICOLON {\n\t\treturn stmt\n\t}\n\tstmt.Values = p.parseExprList()\n\treturn stmt\n}", "func (p *Parser) parseReturnStatement() *ast.ReturnStatement {\n\tstmt := &ast.ReturnStatement{Token: p.curToken}\n\tp.nextToken()\n\tstmt.ReturnValue = p.parseExpression(LOWEST)\n\tif p.peekTokenIs(token.SEMICOLON) {\n\t\tp.nextToken()\n\t}\n\treturn stmt\n}", "func main() {\n\toddOrEven(10)\n\toddOrEven(7)\n\tf.Println(\"Value from sumTheNumbers is \", sumTheNumbers(10, y))\n\tf.Println(\"Value from sumAndDiffOprationOnNumbers are:\")\n\tf.Println(sumAndDiffOprationsOnTwoNumbers(3, y))\n\t// https://stackoverflow.com/questions/52653779/how-to-parse-multiple-returns-in-golang\n\t// Check the above to print as the below\n\t//f.Printf(\"Value from sumAndDiffOprationsOnNumbers are:\\nSum = %v\\nDiff = %v\\n\", sumAndDiffOprationsOnTwoNumbers(3, y))\n\tf.Println(\"Value from variadicFunction is \", variadicFunction(1, 2, 3))\n\tf.Println(\"Value from variadicFunctionRecursion is \", variadicFunctionRecursion(1, 2, 3))\n\n\t// Example of an anonymous function\n\tfunc() {\n\t\tf.Println(\"Hi I'm an anonmous function. They call me that, because I don't have a name -- like lambda\")\n\t}()\n}", "func f1(arg int) (int, error) {\n\tif arg == 42 {\n\t\treturn -1, errors.New(\"Can't work with 42\")\n\t\t// errors.New connstructs a basic error with a message \n\t\t// returned back to the console (in this case)\n\t}\n\n\treturn arg + 3, nil\n\t// Here we are returning two values as well; however, the nil in place\n\t// of an actual error is used because there is no actual error value returned\n}", "func greet4(fname, lname string) (string, string) {\n\treturn fname, lname\n}", "func (fi *funcInfo) emitReturn(line, a, n int) {\r\n\tfi.emitABC(line, OP_RETURN, a, n+1, 0)\r\n}", "func varLookup(context interface{}, cmd, variable string, vars map[string]string, results map[string]interface{}) (interface{}, error) {\n\n\t// {\"field\": \"#cmd:variable\"}\n\t// Before: {\"field\": \"#number:variable_name\"} \t\tAfter: {\"field\": 1234}\n\t// Before: {\"field\": \"#string:variable_name\"} \t\tAfter: {\"field\": \"value\"}\n\t// Before: {\"field\": \"#date:variable_name\"} \t\tAfter: {\"field\": time.Time}\n\t// Before: {\"field\": \"#objid:variable_name\"} \t\tAfter: {\"field\": mgo.ObjectId}\n\t// Before: {\"field\": \"#regex:/pattern/<options>\"} After: {\"field\": bson.RegEx}\n\t// Before: {\"field\": \"#since:3600\"} \t\t\t\tAfter: {\"field\": time.Time}\n\t// Before: {\"field\": \"#data.0:doc.station_id\"} \tAfter: {\"field\": \"23453\"}\n\n\t// If the variable does not exist, use the variable straight up.\n\tparam, exists := vars[variable]\n\tif !exists {\n\t\tparam = variable\n\t}\n\n\t// Do we have a command that is not known.\n\tif len(cmd) < 4 {\n\t\terr := fmt.Errorf(\"Unknown command %q\", cmd)\n\t\tlog.Error(context, \"varLookup\", err, \"Checking cmd is proper length\")\n\t\treturn nil, err\n\t}\n\n\t// Let's perform the right action per command.\n\tswitch cmd[0:4] {\n\tcase \"numb\":\n\t\treturn number(context, param)\n\n\tcase \"stri\":\n\t\treturn param, nil\n\n\tcase \"date\":\n\t\treturn isoDate(context, param)\n\n\tcase \"obji\":\n\t\treturn objID(context, param)\n\n\tcase \"rege\":\n\t\treturn regExp(context, param)\n\n\tcase \"time\":\n\t\treturn adjTime(context, param)\n\n\tcase \"data\":\n\t\tif len(cmd) == 6 {\n\t\t\treturn dataLookup(context, cmd[5:6], param, results)\n\t\t}\n\n\t\terr := errors.New(\"Data command is missing the operator\")\n\t\tlog.Error(context, \"varLookup\", err, \"Checking cmd is data\")\n\t\treturn nil, err\n\n\tdefault:\n\t\terr := fmt.Errorf(\"Unknown command %q\", cmd)\n\t\tlog.Error(context, \"varLookup\", err, \"Checking cmd in default case\")\n\t\treturn nil, err\n\t}\n}", "func innerFunc() {\n meaning_of_life := 43\n fmt.Println(\"The Answer is\", meaning_of_life)\n}" ]
[ "0.75917506", "0.70015144", "0.6518298", "0.6429605", "0.6157334", "0.61043704", "0.60954314", "0.5995361", "0.58820856", "0.57189393", "0.5700473", "0.5678651", "0.5649994", "0.56494564", "0.56391245", "0.56049734", "0.5599004", "0.5586355", "0.5580948", "0.54909015", "0.5464651", "0.5459115", "0.5408224", "0.5380892", "0.5376526", "0.5363522", "0.53565526", "0.5351375", "0.53348416", "0.5331215", "0.5311302", "0.53005636", "0.5255909", "0.5241795", "0.5239745", "0.52342284", "0.52211195", "0.52091753", "0.5196601", "0.51514125", "0.5143698", "0.5126416", "0.5125678", "0.51069015", "0.50978124", "0.50963235", "0.50256324", "0.502223", "0.5004825", "0.49956003", "0.4989648", "0.49669623", "0.49650574", "0.49650574", "0.49650574", "0.49650574", "0.49556798", "0.4946046", "0.4936812", "0.492495", "0.49228093", "0.49198833", "0.49169108", "0.4906986", "0.4905149", "0.48933482", "0.4883935", "0.4877888", "0.4874757", "0.4859395", "0.4847095", "0.4844328", "0.48315668", "0.48292267", "0.48271257", "0.48195794", "0.48179257", "0.48178747", "0.47943312", "0.47812918", "0.47805673", "0.47803506", "0.47785714", "0.4773797", "0.47649953", "0.47617757", "0.47600704", "0.47547585", "0.4750356", "0.4746462", "0.47432017", "0.47390372", "0.4736764", "0.47341108", "0.47326103", "0.47314435", "0.47311834", "0.4729159", "0.47160593", "0.47129315" ]
0.6962891
2
go test v ./internal/go test v ./internal/imap
func init() { cDir, err := os.Getwd() appDir := filepath.Dir(filepath.Dir(cDir)) os.Setenv("IMAIL_WORK_DIR", appDir) os.Chdir(appDir) if tools.IsExist(appDir + "/custom/conf/app.conf") { err = conf.Init(appDir + "/custom/conf/app.conf") if err != nil { fmt.Println("test init config fail:", err.Error()) return } } else { err = conf.Init("") if err != nil { fmt.Println("test init config fail:", err.Error()) return } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestInmemTemplates(t *testing.T) {\n\tfor _, tt := range inmemTemplateTests {\n\t\tExecuteTestInmemTemplate(tt, t)\n\t}\n}", "func _TestMapTypes(t *testing.T) {\n\ttestEndToEnd(\"4-maps\", \"getmap\", t)\n}", "func TestInterfaces(t *testing.T) {\n\tvar verify = func(engine core.VirtualizationEngine) {}\n\n\tdummy := &core.MachineConfig{}\n\n\tverify(vmware.New(dummy))\n\tverify(virtualbox.New(dummy))\n\tverify(unknown.New(dummy))\n}", "func TestParseCacheFile_InterfacesFailes(t *testing.T) {\n\tt.Parallel()\n\n\t// Create temporary directory to write license file to.\n\td := tempDir()\n\tdefer os.RemoveAll(d)\n\n\t// Create a temporary file to write key / vals to.\n\tfilename := tempFile(d, \"TestReadWrite_\")\n\n\t// Create a mock net.Interfaces() func that always returns an error.\n\tinterfaces := func() ([]net.Interface, error) { return nil, errors.New(\"error\") }\n\n\t// Test when net.Interfaces() func returns an error.\n\tif _, err := parseCacheFile(filename, interfaces); err == nil {\n\t\tt.Fatal(err)\n\t}\n}", "func TestFileSourceInternalTestSuite(t *testing.T) {\n\tsuite.Run(t, new(FileSourceInternalTestSuite))\n}", "func TestMap() {\n\tm := NewMap(4, 3)\n\t\n\tm.Reset()\n\t\n\tif m.String() != `. . . \n. . . \n. . . \n. . . \n` {\n\t\tPanicf(\"map is wrong size, got `%s`\", m)\n\t}\n\t\n\tloc := m.FromRowCol(3, 2)\n\trow, col := m.FromLocation(loc)\n\t\n\tif row != 3 || col != 2 {\n\t\tPanicf(\"conversion broken, got (%v, %v), wanted (3, 2)\", row, col)\n\t}\n\t\n\tloc2 := m.FromRowCol(3, -1)\n\t\n\tif loc2 != loc {\n\t\tPanicf(\"from xy broken, got (%v), wanted (%v)\", loc2, loc)\n\t}\n\t\n\tn := m.FromRowCol(2, 2)\n\ts := m.FromRowCol(4, 2)\n\te := m.FromRowCol(3, 3)\n\tw := m.FromRowCol(3, 1)\n\t\n\tif n != m.Move(loc, North) {Panicf(\"Move north is broken\")}\n\tif s != m.Move(loc, South) {Panicf(\"Move south is broken\")}\n\tif e != m.Move(loc, East) {Panicf(\"Move east is broken\")}\n\tif w != m.Move(loc, West) {Panicf(\"Move west is broken\")}\n\t\n\tm.AddAnt(n, MY_ANT)\n\tm.AddAnt(s, MY_ANT)\n\t\n\tif m.String() != `. . a \n. . . \n. . a \n. . . \n` {\n\t\tPanicf(\"map put ants in wrong place, got `%s`\", m)\n\t}\n\t\n\tfmt.Println(\"TestMap PASS\")\n}", "func TestPrewriteMultiple4A(t *testing.T) {\n}", "func TestRestOfInternalCode(t *testing.T) {\n\n\t// In this case unit testing will not help as we need to actually corever\n\t// this package with test. Because real functions hide under internal structures\n\t// which we do not expose, so our previous approach will no longer works.\n\t// Well it works but coverage does not detect that we are testing actual\n\t// implementation\n\n\t// In order to cover this part we will need to either pretend that we are\n\t// testing something or create real integration tests and ensure that mongod\n\t// process is running. In my case I will just fake my testing and do not use\n\t// assert. This way my test will pass either way\n\n\t// Create database context. I use real database, but it is possible to mock\n\t// database and configuration through interfaces.\n\tconf := config.GetConfig()\n\tclient, _ := databases.NewClient(conf)\n\tclient.StartSession()\n\n\tdb := databases.NewDatabase(conf, client)\n\tclient.Connect()\n\tdb.Client()\n\tvar result interface{}\n\t// because we do not care for actual results, we just quickly timeout the\n\t// call and we use incorrect call method\n\ttimeoutCtx, _ := context.WithTimeout(context.Background(), 1*time.Microsecond)\n\tdb.Collection(\"non-fake-existing-collection\").FindOne(timeoutCtx, \"incorrect-value\").Decode(&result)\n\n\t// insert and delete functions seems to panic instead of returning and error.\n\t// I did not investigate anything in this case as this is not our main goal.\n\t// Just define assert panic function and use this panicing function in it.\n\tvar mongoPanics assert.PanicTestFunc\n\n\tmongoPanics = func() {\n\t\tdb.Collection(\"non-fake-existing-collection\").InsertOne(timeoutCtx, result)\n\t}\n\tassert.Panics(t, mongoPanics)\n\n\tmongoPanics = func() {\n\t\tdb.Collection(\"non-fake-existing-collection\").DeleteOne(timeoutCtx, result)\n\t}\n\tassert.Panics(t, mongoPanics)\n\n\t// And it is done. We do not need to have mongo running and our code is\n\t// covered 100%. Well the actual implementation is faked, but it should be\n\t// tested via integration tests, not unit tests.\n\n}", "func TestRecommitKey4A(t *testing.T) {\n}", "func TestIting2Map( t *testing.T ) {\n\tok := true\n\n\tit := mk_thing()\n\tfmt.Fprintf( os.Stderr, \"array_test: Inner AT_thing Testing\\n\" )\n\tm := transform.Struct_to_map( it, \"Bar\" )\n\tfor k, v := range m {\n\t\tfmt.Fprintf( os.Stderr, \"AT_thing map: %s (%v)\\n\", k, v )\t\t\t// uncomment to dump the map\n\t}\n\n\tif( len( m ) != 14 ) {\n\t\tfmt.Fprintf( os.Stderr, \"array_test: [FAIL] number of elements in the map not 14; found %d\\n\", len( m ) )\n\t\tt.Fail()\n\t} else {\n\t\tfmt.Fprintf( os.Stderr, \"array_test: [OK] number of elements in the map is correct\\n\" )\n\t}\n\n\tif( clike.Atoi( m[\"Itobj/Data.cap\"] ) != 10 ) {\n\t\tfmt.Fprintf( os.Stderr, \"array_test: [FAIL] number of inner elements in the map not 10; found %s\\n\", m[\"Itobj/Data.cap\"] )\n\t\tt.Fail()\n\t\tok = false\n\t} else {\n\t\tfmt.Fprintf( os.Stderr, \"array_test: [OK] number of inner elements in the map is correct\\n\" )\n\t}\n\n\tfmt.Fprintf( os.Stderr, \"\\n\" )\n\tnit := &AT_thing{}\t\t\t\t\t\t\t\t\t\t// empty struct to populate\n\ttransform.Map_to_struct( m, nit, \"Bar\" )\t\t\t\t// fill it in \n\n\ta, ok := nit.Itobj.Data.( []string )\n\tif ok {\n\t\tif( len( a ) != 10 ) {\n\t\t\tfmt.Fprintf( os.Stderr, \"array_test: [FAIL] len of populated inner data array is not 10: %d\\n\", len( a ) )\n\t\t\tt.Fail()\n\t\t\tok = false\n\t\t} else {\n\t\t\tfmt.Fprintf( os.Stderr, \"array_test: [OK] len of populated inner data array is correct\\n\" )\n\t\n\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\tif i > 3 && a[i] != \"\" {\n\t\t\t\t\tok = false\n\t\t\t\t\tfmt.Fprintf( os.Stderr, \"array_test: [FAIL] data[4+] should be empty and isn't @i=%d\\n\", i )\n\t\t\t\t\tt.Fail()\n\t\t\t\t}\n\t\t\t\tfmt.Fprintf( os.Stderr, \"array_test: [INFO] data[%d] = (%s)\\n\", i, a[i] )\n\t\t\t}\n\t\t}\n\t} else {\n\t\tok = false\n\t\tfmt.Fprintf( os.Stderr, \"array_test: [FAIL] data didn't produce an array of strings\\n\" )\n\t\tt.Fail()\n\t}\n\n\tif ok {\n\t\tfmt.Fprintf( os.Stderr, \"PASS: array_test: done\\n\\n\" )\n\t} else {\n\t\tfmt.Fprintf( os.Stderr, \"FAIL: array_test: done\\n\\n\" )\n\t}\n\n}", "func TestPrewriteWritten4A(t *testing.T) {\n}", "func TestMap() {\n\txs := []a{1, 2, 3, 4, 5}\n\tbs := gunc.Map(func(x a) b { return x.(int) + 2 }, xs)\n\tfmt.Printf(\"mapped:: %s\", bs)\n\tfor i := range bs {\n\t\tif bs[i].(int) != xs[i].(int)+2 {\n\t\t\tlog.Fatalf(\"mapping failed:: expected %d got %d\", (xs[i].(int) + 2), bs[i].(int))\n\t\t}\n\t}\n\tlog.Println(\"Map succeeded...\")\n}", "func TestPrewriteLocked4A(t *testing.T) {\n}", "func TestSinglePrewrite4A(t *testing.T) {\n}", "func TestMap(t *testing.T) {\n\tbx := NewTestDB()\n\tdefer bx.Close()\n\n\t// Create a new bucket.\n\tletters, err := bx.New([]byte(\"letters\"))\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Setup items to insert.\n\titems := []struct {\n\t\tKey, Value []byte\n\t}{\n\t\t{[]byte(\"A\"), []byte(\"alpha\")},\n\t\t{[]byte(\"B\"), []byte(\"beta\")},\n\t\t{[]byte(\"C\"), []byte(\"gamma\")},\n\t}\n\n\t// Insert items into `letters` bucket.\n\tif err := letters.Insert(items); err != nil {\n\t\tfmt.Println(\"could not insert items!\")\n\t}\n\n\t// Setup slice of items to collect results.\n\ttype item struct {\n\t\tKey, Value []byte\n\t}\n\tresults := []item{}\n\n\t// Anon func to apply to each item in bucket.\n\t// Here, we're just going to collect the items just inserted.\n\tdo := func(k, v []byte) error {\n\t\tresults = append(results, item{k, v})\n\t\treturn nil\n\t}\n\n\t// Now map the `do` function over each item.\n\tif err := letters.Map(do); err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Finally, check to see if our results match the originally\n\t// inserted items.\n\tfor i, want := range items {\n\t\tgot := results[i]\n\t\tif !bytes.Equal(got.Key, want.Key) {\n\t\t\tt.Errorf(\"got %v, want %v\", got.Key, want.Key)\n\t\t}\n\t\tif !bytes.Equal(got.Value, want.Value) {\n\t\t\tt.Errorf(\"got %v, want %v\", got.Value, want.Value)\n\t\t}\n\t}\n}", "func TestInterfaces(t *testing.T) {\n\tvar apiCA ca.FabricCAClient\n\tvar ca FabricCA\n\n\tapiCA = &ca\n\tif apiCA == nil {\n\t\tt.Fatalf(\"this shouldn't happen.\")\n\t}\n}", "func TestMapList(t *testing.T) {\n\t// inpath := \"/Users/vanilla/Downloads/けんけんぱ(けんけ) fantia 2020.03-2021.08\"\n\tbasePath := \"/Users/vanilla/Downloads/けんけんぱ(けんけ) fantia 2020.03-2021.08\"\n\n\tdata := GetFileMapList(basePath, map[string][]string{})\n\t// t.Log(ijson.Pretty(data))\n\tDoPutImage(basePath, data, 1)\n}", "func TestCommitMultipleKeys4A(t *testing.T) {\n}", "func SKIPPEDTestAccessAfterUnmap(t *testing.T) {\n\ttmpDir, _ := ioutil.TempDir(\"\", \"mossMMap\")\n\tdefer os.RemoveAll(tmpDir)\n\n\tf, err := os.Create(tmpDir + string(os.PathSeparator) + \"test.file\")\n\tif err != nil {\n\t\tt.Errorf(\"expected open file to work, err: %v\", err)\n\t}\n\n\tdefer f.Close()\n\n\toffset := 1024 * 1024 * 1024 // 1 GB.\n\n\tf.WriteAt([]byte(\"hello\"), int64(offset))\n\n\tvar mm mmap.MMap\n\n\tmm, err = mmap.Map(f, mmap.RDONLY, 0)\n\tif err != nil {\n\t\tt.Errorf(\"expected mmap to work, err: %v\", err)\n\t}\n\n\tx := mm[offset : offset+5]\n\n\tif string(x) != \"hello\" {\n\t\tt.Errorf(\"expected hello\")\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Println(\"Recovered in f\", r)\n\t\t} else {\n\t\t\tt.Errorf(\"expected recover from panic\")\n\t\t}\n\t}()\n\n\tmm.Unmap()\n\n\t/*\n\t\t\tThe following access of x results in a segfault, like...\n\n\t\t\t\tunexpected fault address 0x4060c000\n\t\t\t\tfatal error: fault\n\t\t\t\t[signal 0xb code=0x1 addr=0x4060c000 pc=0xb193f]\n\n\t\t The recover() machinery doesn't handle this situation, however,\n\t\t as it's not a normal kind of panic()\n\t*/\n\tif x[0] != 'h' {\n\t\tt.Errorf(\"expected h, but actually expected a segfault\")\n\t}\n\n\tt.Errorf(\"expected segfault, but instead unmmapped mem access worked\")\n}", "func TestSIFTLib2(t *testing.T) { TestingT(t) }", "func TestMain(m *testing.M) {\n\tfields := []FieldOffset{\n\t\t{\n\t\t\tName: \"Batch.Measurments\",\n\t\t\tOffset: unsafe.Offsetof(Batch{}.Measurements),\n\t\t},\n\t\t{\n\t\t\tName: \"Measurement.Number\",\n\t\t\tOffset: unsafe.Offsetof(Measurement{}.Number),\n\t\t},\n\t}\n\tif !Aligned8Byte(fields, os.Stderr) {\n\t\tos.Exit(1)\n\t}\n\n\tos.Exit(m.Run())\n}", "func TestFuncMaps(t *testing.T) {\n\n\t// Test FuncValue map\n\tfor fName, fValue := range goHamlib.FuncValue {\n\t\t_, ok := goHamlib.FuncName[fValue]\n\t\tif !ok {\n\t\t\tt.Fatalf(\"Func %d does not exist in FuncName map\", fValue)\n\t\t}\n\t\tif fName != goHamlib.FuncName[fValue] {\n\t\t\tt.Fatalf(\"Name of Func inconsisted: %s\", fName)\n\t\t}\n\t}\n\n\t// Test FuncName map\n\tfor fValue, fName := range goHamlib.FuncName {\n\t\t_, ok := goHamlib.FuncValue[fName]\n\t\tif !ok {\n\t\t\tt.Fatalf(\"Func %s does not exist in FuncValue map\", fName)\n\t\t}\n\t\tif fValue != goHamlib.FuncValue[fName] {\n\t\t\tt.Fatalf(\"Value of Func inconsisted: %s\", fName)\n\t\t}\n\t}\n}", "func TestInMemory(t *testing.T) { TestingT(t) }", "func TestInMemory(t *testing.T) { TestingT(t) }", "func TestIpfs(t *testing.T) {\n\thash, err := AddStringToIpfs(\"Hello, this is a test from ipfs to see if it works\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tlog.Println(\"HASH: \", hash)\n\tstring1, err := GetStringFromIpfs(hash)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif string1 == \"Hellox, this is a test from ipfs to see if it works\" {\n\t\tt.Fatal(\"DEcrypted string does not match with original, exiting!\")\n\t}\n\t_, err = GetStringFromIpfs(\"blah\")\n\tif err == nil {\n\t\tt.Fatal(\"Can retrieve non existing hash, quitting!\")\n\t}\n\terr = GetFileFromIpfs(\"/ipfs/\"+hash, \"pdf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = GetFileFromIpfs(\"blah\", \"pdf\")\n\tif err == nil {\n\t\tt.Fatalf(\"Can retrieve non existing hash, quitting!\")\n\t}\n\t_, err = ReadfromPdf(\"files/test.pdf\") // get the data from the pdf as a datastream\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = ReadfromPdf(\"blah\") // get the data from the pdf as a datastream\n\tif err == nil {\n\t\tt.Fatal(\"Can read from non existing pdf.\")\n\t}\n\thash, err = IpfsHashPdf(\"files/test.pdf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, err = IpfsHashPdf(\"blah\")\n\tif err == nil {\n\t\tt.Fatal(\"Can retrieve non existing pdf file\")\n\t}\n\terr = GetFileFromIpfs(hash, \"pdf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = GetFileFromIpfs(\"blah\", \"pdf\")\n\tif err == nil {\n\t\tt.Fatal(\"CAn retrieve non exiting file, quitting\")\n\t}\n}", "func TestTrunkENI_getBranchInterfaceMap(t *testing.T) {\n\ttrunkENI := getMockTrunk()\n\n\tbranchENIsMap := trunkENI.getBranchInterfaceMap([]*ENIDetails{EniDetails1})\n\tassert.Equal(t, EniDetails1, branchENIsMap[EniDetails1.ID])\n}", "func TestIndexi(t *testing.T) {\n\tt.Parallel()\n\tvar tests = []struct {\n\t\thaystack []string\n\t\tneedle string\n\t\texpected int\n\t}{\n\t\t{[]string{\"FOO\", \"bar\"}, \"bar\", 1},\n\t\t{[]string{\"FoO\", \"bar\"}, \"foo\", 0},\n\t\t{[]string{\"foo\", \"bar\"}, \"blah\", -1},\n\t}\n\tfor _, test := range tests {\n\t\tactual := primitives.Indexi(test.haystack, test.needle)\n\t\tassert.Equal(t, test.expected, actual, \"expected value '%v' | actual : '%v'\", test.expected, actual)\n\t}\n}", "func Test_Client_MapByCallingCode(t *testing.T) {\n\tret := mockClient.MapByCallingCode(\"65\")\n\tassert.Equal(t, ret[0].Name, \"Singapore\")\n}", "func TestTheTest(t *testing.T) {\n\ttestenv.NeedsTool(t, \"go\")\n\n\t// We'll simulate a partly failing test of the findcall analysis,\n\t// which (by default) reports calls to functions named 'println'.\n\tfindcall.Analyzer.Flags.Set(\"name\", \"println\")\n\n\tfilemap := map[string]string{\n\t\t\"a/b.go\": `package main // want package:\"found\"\n\nfunc main() {\n\t// The expectation is ill-formed:\n\tprint() // want: \"diagnostic\"\n\tprint() // want foo\"fact\"\n\tprint() // want foo:\n\tprint() // want \"\\xZZ scan error\"\n\n\t// A diagnostic is reported at this line, but the expectation doesn't match:\n\tprintln(\"hello, world\") // want \"wrong expectation text\"\n\n\t// An unexpected diagnostic is reported at this line:\n\tprintln() // trigger an unexpected diagnostic\n\n\t// No diagnostic is reported at this line:\n\tprint()\t// want \"unsatisfied expectation\"\n\n\t// OK\n\tprintln(\"hello, world\") // want \"call of println\"\n\n\t// OK /* */-form.\n\tprintln(\"안녕, 세계\") /* want \"call of println\" */\n\n\t// OK (nested comment)\n\tprintln(\"Γειά σου, Κόσμε\") // some comment // want \"call of println\"\n\n\t// OK (nested comment in /**/)\n\tprintln(\"你好,世界\") /* some comment // want \"call of println\" */\n\n\t// OK (multiple expectations on same line)\n\tprintln(); println() // want \"call of println(...)\" \"call of println(...)\"\n}\n\n// OK (facts and diagnostics on same line)\nfunc println(...interface{}) { println() } // want println:\"found\" \"call of println(...)\"\n\n`,\n\t\t\"a/b.go.golden\": `package main // want package:\"found\"\n\nfunc main() {\n\t// The expectation is ill-formed:\n\tprint() // want: \"diagnostic\"\n\tprint() // want foo\"fact\"\n\tprint() // want foo:\n\tprint() // want \"\\xZZ scan error\"\n\n\t// A diagnostic is reported at this line, but the expectation doesn't match:\n\tprintln_TEST_(\"hello, world\") // want \"wrong expectation text\"\n\n\t// An unexpected diagnostic is reported at this line:\n\tprintln_TEST_() // trigger an unexpected diagnostic\n\n\t// No diagnostic is reported at this line:\n\tprint() // want \"unsatisfied expectation\"\n\n\t// OK\n\tprintln_TEST_(\"hello, world\") // want \"call of println\"\n\n\t// OK /* */-form.\n\tprintln_TEST_(\"안녕, 세계\") /* want \"call of println\" */\n\n\t// OK (nested comment)\n\tprintln_TEST_(\"Γειά σου, Κόσμε\") // some comment // want \"call of println\"\n\n\t// OK (nested comment in /**/)\n\tprintln_TEST_(\"你好,世界\") /* some comment // want \"call of println\" */\n\n\t// OK (multiple expectations on same line)\n\tprintln_TEST_()\n\tprintln_TEST_() // want \"call of println(...)\" \"call of println(...)\"\n}\n\n// OK (facts and diagnostics on same line)\nfunc println(...interface{}) { println_TEST_() } // want println:\"found\" \"call of println(...)\"\n`,\n\t\t\"a/b_test.go\": `package main\n\n// Test file shouldn't mess with things (issue #40574)\n`,\n\t}\n\tdir, cleanup, err := analysistest.WriteFiles(filemap)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer cleanup()\n\n\tvar got []string\n\tt2 := errorfunc(func(s string) { got = append(got, s) }) // a fake *testing.T\n\tanalysistest.RunWithSuggestedFixes(t2, dir, findcall.Analyzer, \"a\")\n\n\twant := []string{\n\t\t`a/b.go:5: in 'want' comment: unexpected \":\"`,\n\t\t`a/b.go:6: in 'want' comment: got String after foo, want ':'`,\n\t\t`a/b.go:7: in 'want' comment: got EOF, want regular expression`,\n\t\t`a/b.go:8: in 'want' comment: invalid char escape`,\n\t\t\"a/b.go:11:9: diagnostic \\\"call of println(...)\\\" does not match pattern `wrong expectation text`\",\n\t\t`a/b.go:14:9: unexpected diagnostic: call of println(...)`,\n\t\t\"a/b.go:11: no diagnostic was reported matching `wrong expectation text`\",\n\t\t\"a/b.go:17: no diagnostic was reported matching `unsatisfied expectation`\",\n\t\t// duplicate copies of each message from the test package (see issue #40574)\n\t\t`a/b.go:5: in 'want' comment: unexpected \":\"`,\n\t\t`a/b.go:6: in 'want' comment: got String after foo, want ':'`,\n\t\t`a/b.go:7: in 'want' comment: got EOF, want regular expression`,\n\t\t`a/b.go:8: in 'want' comment: invalid char escape`,\n\t\t\"a/b.go:11:9: diagnostic \\\"call of println(...)\\\" does not match pattern `wrong expectation text`\",\n\t\t`a/b.go:14:9: unexpected diagnostic: call of println(...)`,\n\t\t\"a/b.go:11: no diagnostic was reported matching `wrong expectation text`\",\n\t\t\"a/b.go:17: no diagnostic was reported matching `unsatisfied expectation`\",\n\t}\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got:\\n%s\\nwant:\\n%s\",\n\t\t\tstrings.Join(got, \"\\n\"),\n\t\t\tstrings.Join(want, \"\\n\"))\n\t}\n}", "func TestMapGet(t *testing.T) {\n\tm := map[Key]interface{}{}\n\ttestMapGetN(testN, m)\n}", "func TestSingleCommit4A(t *testing.T) {\n}", "func TestCache(t *testing.T) {\n\terrorOut := func(err error) {\n\t\tos.RemoveAll(flags.CacheDir)\n\t\tt.Fatal(err)\n\t}\n\n\t// The client and all servers will run as the same user.\n\tcfg := config.New()\n\tcfg = config.SetUserName(cfg, upspin.UserName(\"tester@google.com\"))\n\tcfg = config.SetPacking(cfg, upspin.EEPack)\n\n\t// Use an inprocess key server.\n\tcfg = config.SetKeyEndpoint(cfg, inprocessEndpoint)\n\tbind.RegisterKeyServer(upspin.InProcess, inprocesskeyserver.New())\n\n\tcfg = setCertPool(cfg)\n\n\tvar err error\n\tcfg, err = setUpFactotum(cfg)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcfg, err = putUserToKeyServer(cfg, &inprocessEndpoint)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsep, err := startCombinedServer(cfg)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcfg, err = putUserToKeyServer(cfg, sep)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcep, err := startCacheServer(cfg)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcfg, cl := newClient(cfg, sep, cep)\n\n\t// Create a root directory.\n\troot := upspin.PathName(cfg.UserName())\n\tif _, err := cl.MakeDirectory(root); err != nil {\n\t\terrorOut(err)\n\t}\n\n\t// Put something and read it back.\n\tfn := path.Join(root, \"quux\")\n\tstr := \"tada\"\n\tif _, err := cl.Put(fn, []byte(str)); err != nil {\n\t\terrorOut(err)\n\t}\n\tdata, err := cl.Get(fn)\n\tif err != nil {\n\t\terrorOut(err)\n\t}\n\tif string(data) != str {\n\t\terrorOut(fmt.Errorf(\"expected %q got %q\", str, data))\n\t}\n\n\t// Make sure we can remove it.\n\tif err := cl.Delete(fn); err != nil {\n\t\terrorOut(err)\n\t}\n\tif _, err := cl.Get(fn); err == nil {\n\t\terrorOut(fmt.Errorf(\"file persisted beyond delete\"))\n\t}\n\n\t// Force a cache flush and make sure we get the expected response.\n\t// This doesn't check functionality of the flush.\n\tloc := upspin.Location{\n\t\tEndpoint: *sep,\n\t\tReference: upspin.FlushWritebacksMetadata,\n\t}\n\tdata, err = clientutil.ReadLocation(cfg, loc)\n\tif err != nil {\n\t\terrorOut(err)\n\t}\n\tflushReply := \"cache flushed\"\n\tif string(data) != flushReply {\n\t\terrorOut(fmt.Errorf(\"expected %q got %q\", flushReply, string(data)))\n\t}\n\n\t// Remove the cache files and logs.\n\tos.RemoveAll(flags.CacheDir)\n}", "func Test_sampe002(t *testing.T) {\n\n}", "func TestInterface(t *testing.T) {\n\ttype Sample struct {\n\t\tDummy int64\n\t\tStr string\n\t}\n\n\ttype Test struct {\n\t\tvalue interface{}\n\t}\n\ttests := []Test{\n\t\t{[]int{1, 2, 3}},\n\t\t{Sample{10, \"MyString\"}},\n\t}\n\n\tInterfaceMap[\"[]int\"] = reflect.TypeOf([]int{})\n\tInterfaceMap[\"sexpr.Sample\"] = reflect.TypeOf(Sample{0, \"\"})\n\n\tfor _, test := range tests {\n\t\ttype Struct struct {\n\t\t\tI interface{}\n\t\t}\n\t\ts := Struct{test.value}\n\t\t// Encode it\n\t\tdata, err := Marshal(s)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Marshal failed: %v\", err)\n\t\t}\n\t\t// Decode it\n\t\tvar value Struct\n\t\terr = Unmarshal(data, &value)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unmarshal failed: %v\", err)\n\t\t}\n\t\t// Check equality.\n\t\tif !reflect.DeepEqual(value, s) {\n\t\t\tt.Fatalf(\"not equal: %v/%v\", value, s)\n\t\t}\n\t\tt.Logf(\"Unmarshal() = %+v\\n\", value)\n\t}\n}", "func TestLmapOffsets(t *testing.T) {\n\tif lname_offset() >= lnext_offset() {\n\t\tt.Fatalf(\"lname offset (%d) should be l.t. lnext offset (%d)\",\n\t\t\tlname_offset(), lnext_offset())\n\t}\n}", "func TestCount64(t *testing.T) {\n\thm, _ := NewHashMap(64)\n\ttestCountN(testN, hm)\n}", "func TestEmptyPrewrite4A(t *testing.T) {\n}", "func TestMapCount(t *testing.T) {\n\tm := map[Key]interface{}{}\n\ttestMapCountN(testN, m)\n}", "func TestNewHashMap(t *testing.T) {\n\ttests := []struct {\n\t\tBlockSize int\n\t\tExpectedError bool\n\t}{\n\t\t{128, false},\n\t\t{0, true},\n\t\t{-100, true},\n\t}\n\tfor _, test := range tests {\n\t\t_, err := NewHashMap(test.BlockSize)\n\t\tif (err != nil && !test.ExpectedError) || (err == nil && test.ExpectedError) {\n\t\t\tt.Errorf(\"Expected error: %t, received: %v\", test.ExpectedError, err)\n\t\t}\n\t}\n}", "func TestConcurrentWalk(t *testing.T) {\n\treturn // Currently deadlocks on MAXPROCS > 1, and is not used so we skip it.\n\tbuiltinWalkMap := map[string]error{}\n\tconcurrentWalkMap := map[string]error{}\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// TODO(mg): Should use some standard test directories/files.\n\terr = filepath.Walk(wd, testWalkFuncBuilder(builtinWalkMap))\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\terr = ConcurrentWalk(wd, testWalkFuncBuilder(concurrentWalkMap))\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tfor key, err := range builtinWalkMap {\n\t\te, ok := concurrentWalkMap[key]\n\t\tif !ok || e != err {\n\t\t\tt.FailNow()\n\t\t}\n\t}\n\n\tfor key, err := range concurrentWalkMap {\n\t\te, ok := builtinWalkMap[key]\n\t\tif !ok || e != err {\n\t\t\tt.FailNow()\n\t\t}\n\t}\n}", "func main() {\n\n mainTests{}.mainTests117SortFileMgrsCaseSensitive()\n\n}", "func main() {\n\ttest32()\n\ttest64()\n}", "func TestGetVersions4A(t *testing.T) {\n}", "func TestBase64Decode(t *testing.T) {\n\twant := \"Hello World\"\n\tg, _ := phpfuncs.Base64Decode(\"SGVsbG8gV29ybGQ=\")\n\tCoverCheck(t, g, want)\n}", "func TestAstarSearch(t *testing.T) {\n\tm := buildMap()\n\tAstarSearch(2, 3, 6, 3, m)\n}", "func testIndexIcon(t *testing.T, s *Service) {\n\tres, err := s.IndexIcon(context.TODO())\n\tif err != nil {\n\t\tt.Logf(\"testIndexIcon error(%v) \\n\", err)\n\t\treturn\n\t}\n\tt.Logf(\"testIndexIcon res: %+v \\n\", res)\n}", "func testAgi(sess *agi.Session) {\n\tvar tests, pass int\n\tvar err error\n\tvar r agi.Reply\n\n\t// For each test we Diesplay a message on the asterisk console with verbose,\n\t// send an AGI command and store the return values in r.\n\tsess.Verbose(\"Testing answer...\")\n\tr, err = sess.Answer()\n\t// We check if there was an error or if the return values were not the expected ones.\n\tif err != nil || r.Res != 0 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing channelstatus...\")\n\tr, err = sess.ChannelStatus()\n\tif err != nil || r.Res != 6 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing databaseput...\")\n\tr, err = sess.DatabasePut(\"test\", \"my_key\", \"true\")\n\tif err != nil || r.Res != 1 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing databaseget...\")\n\tr, err = sess.DatabaseGet(\"test\", \"my_key\")\n\tif err != nil || r.Res != 1 || r.Dat != \"true\" {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing databasedel...\")\n\tr, err = sess.DatabaseDel(\"test\", \"my_key\")\n\tif err != nil || r.Res != 1 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing databasedeltree...\")\n\tr, err = sess.DatabaseDelTree(\"test\")\n\tif err != nil || r.Res != 1 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing streamfile...\")\n\tr, err = sess.StreamFile(\"beep\", \"\")\n\tif err != nil || r.Res != 0 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing sendtext...\")\n\tr, err = sess.SendText(\"Hello World\")\n\tif err != nil || r.Res != 0 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing sendimage...\")\n\tr, err = sess.SendImage(\"asterisk-image\")\n\tif err != nil || r.Res != 0 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing saynumber...\")\n\tr, err = sess.SayNumber(192837465, \"\")\n\tif err != nil || r.Res != 0 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing wait for digit...\")\n\tr, err = sess.WaitForDigit(3000)\n\tif err != nil || r.Res == -1 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing record...\")\n\tr, err = sess.RecordFile(\"/tmp/testagi\", \"alaw\", \"1234567890*#\", 3000)\n\tif err != nil || r.Res == -1 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing record playback...\")\n\tr, err = sess.StreamFile(\"/tmp/testagi\", \"\")\n\tif err != nil || r.Res != 0 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing set variable...\")\n\tr, err = sess.SetVariable(\"testagi\", \"foo\")\n\tif err != nil || r.Res != 1 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing get variable...\")\n\tr, err = sess.GetVariable(\"testagi\")\n\tif err != nil || r.Res != 1 || r.Dat != \"foo\" {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing get full variable...\")\n\tr, err = sess.GetFullVariable(\"${testagi}\")\n\tif err != nil || r.Res != 1 || r.Dat != \"foo\" {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"Testing exec...\")\n\tr, err = sess.Exec(\"Wait\", \"3\")\n\tif err != nil || r.Res != 0 {\n\t\tsess.Verbose(\"Failed.\")\n\t} else {\n\t\tpass++\n\t}\n\ttests++\n\n\tsess.Verbose(\"================== Complete ======================\")\n\tsess.Verbose(fmt.Sprintf(\"%d tests completed, %d passed, %d failed\", tests, pass, tests-pass))\n\tsess.Verbose(\"==================================================\")\n\n\tif tests-pass != 0 {\n\t\tsess.Failure()\n\t}\n\treturn\n}", "func TestGet64(t *testing.T) {\n\thm, _ := NewHashMap(64)\n\ttestGetN(testN, hm)\n}", "func TestExternalIP(t *testing.T) {\n\t_, err := ExternalIP()\n\tif err != nil {\n\t\tt.Errorf(\"ExternalIP failed : %w\", err)\n\t}\n}", "func TestIfAddUserInfoToMapChangesInfo(t *testing.T) {\n\tsuite := testsuite.NewTestSuite(t)\n\tMockUserItemStorage := MockUserItemStorage()\n\tMockUserSubmissionData := MockUserSubmissionData()\n\tmongoDB.AddUserInfoToMap(MockUserItemStorage, MockUserSubmissionData)\n\n\t// We need to generate what the result would look like\n\tResultUserItemStorage := mongoDB.UserItemStorage{\n\t\tUserID: \"Test\",\n\t\t// These are the important things that need info\n\t\tPrices: make(map[string]models.UserPrices),\n\t\tProfits: make(map[string]models.UserProfits),\n\t}\n\n\t// If it changes, then that should mean that we're editing info\n\tsuite.AssertNotEqual(ResultUserItemStorage, *MockUserItemStorage)\n}", "func Map02() {\n\twc.Test(WordCount)\n}", "func TestMapSet(t *testing.T) {\n\tm := map[Key]interface{}{}\n\ttestMapSetN(testN, m)\n}", "func TestCommitMissingPrewrite4a(t *testing.T) {\n}", "func TestMemIdmAll(t *testing.T) {\n\tidm := memidm.New()\n\tsidm := test.NewSuiteIdm(t, idm)\n\tsidm.TestAll(t)\n}", "func TestHashMap(t *testing.T) {\n\tm := rhh.NewHashMap(rhh.DefaultOptions)\n\tm.Put([]byte(\"foo\"), []byte(\"bar\"))\n\tm.Put([]byte(\"baz\"), []byte(\"bat\"))\n\n\t// Verify values can be retrieved.\n\tif v := m.Get([]byte(\"foo\")); !bytes.Equal(v.([]byte), []byte(\"bar\")) {\n\t\tt.Fatalf(\"unexpected value: %s\", v)\n\t}\n\tif v := m.Get([]byte(\"baz\")); !bytes.Equal(v.([]byte), []byte(\"bat\")) {\n\t\tt.Fatalf(\"unexpected value: %s\", v)\n\t}\n\n\t// Overwrite field & verify.\n\tm.Put([]byte(\"foo\"), []byte(\"XXX\"))\n\tif v := m.Get([]byte(\"foo\")); !bytes.Equal(v.([]byte), []byte(\"XXX\")) {\n\t\tt.Fatalf(\"unexpected value: %s\", v)\n\t}\n}", "func TestEmptyCommit4A(t *testing.T) {\n}", "func TestDumpInterfacesMemif(t *testing.T) {\n\tctx := vppcallmock.SetupTestCtx(t)\n\tdefer ctx.TeardownTestCtx()\n\n\tctx.MockVpp.MockReplyHandler(vppMockHandler(ctx.MockVpp, []*vppReplyMock{\n\t\t{\n\t\t\tId: 200,\n\t\t\tPing: true,\n\t\t\tMessage: &interfaces.SwInterfaceDetails{\n\t\t\t\tInterfaceName: []byte(\"memif1\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tId: 1001,\n\t\t\tPing: false,\n\t\t\tMessage: &interfaces.SwInterfaceGetTableReply{},\n\t\t},\n\t\t{\n\t\t\tId: 1004,\n\t\t\tPing: true,\n\t\t\tMessage: &ip.IPAddressDetails{},\n\t\t},\n\t\t{\n\t\t\tId: 1005,\n\t\t\tPing: true,\n\t\t\tMessage: &memif.MemifSocketFilenameDetails{\n\t\t\t\tSocketID: 1,\n\t\t\t\tSocketFilename: []byte(\"test\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tId: 1007,\n\t\t\tPing: true,\n\t\t\tMessage: &memif.MemifDetails{\n\t\t\t\tID: 2,\n\t\t\t\tSwIfIndex: 0,\n\t\t\t\tRole: 1, // Slave\n\t\t\t\tMode: 1, // IP\n\t\t\t\tSocketID: 1,\n\t\t\t\tRingSize: 0,\n\t\t\t\tBufferSize: 0,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tId: 1009,\n\t\t\tPing: true,\n\t\t\tMessage: &tap.SwInterfaceTapDetails{},\n\t\t},\n\t\t{\n\t\t\tId: 1011,\n\t\t\tPing: true,\n\t\t\tMessage: &tapv2.SwInterfaceTapV2Details{},\n\t\t},\n\t\t{\n\t\t\tId: 1013,\n\t\t\tPing: true,\n\t\t\tMessage: &vxlan.VxlanTunnelDetails{},\n\t\t},\n\t}))\n\n\tintfs, err := DumpInterfaces(logrus.DefaultLogger(), ctx.MockChannel, nil)\n\tExpect(err).To(BeNil())\n\tExpect(intfs).To(HaveLen(1))\n\tintface := intfs[0]\n\n\t// Check memif\n\tExpect(intface.Memif.SocketFilename).To(Equal(\"test\"))\n\tExpect(intface.Memif.Id).To(Equal(uint32(2)))\n\tExpect(intface.Memif.Mode).To(Equal(interfaces2.Interfaces_Interface_Memif_IP))\n\tExpect(intface.Memif.Master).To(BeFalse())\n}", "func TestInternalFritzAPI(t *testing.T) {\n\ttestCases := []struct {\n\t\ttc func(t *testing.T, internal Internal)\n\t}{\n\t\t{testListLanDevices},\n\t\t{testListLogs},\n\t\t{testInetStats},\n\t\t{testBoxInfo},\n\t}\n\tfor _, testCase := range testCases {\n\t\tt.Run(fmt.Sprintf(\"Test aha api %s\", runtime.FuncForPC(reflect.ValueOf(testCase.tc).Pointer()).Name()), func(t *testing.T) {\n\t\t\tsrv := mock.New().Start()\n\t\t\tdefer srv.Close()\n\t\t\tinternal := setUpClient(t, srv)\n\t\t\tassert.NotNil(t, internal)\n\t\t\ttestCase.tc(t, internal)\n\t\t})\n\t}\n}", "func main() {\n\t// TODO:\n\tfmt.Println(\"NOT IMPLEMENTED\")\n}", "func TestLookupByIP(t *testing.T) {\n\t// Constants\n\tconst (\n\t\tifName0 = \"if0\"\n\t\tifName1 = \"if1\"\n\t\tifName2 = \"if2\"\n\t\tipAddr0 = \"192.168.0.1/24\"\n\t\tipAddr1 = \"192.168.1.1/24\"\n\t\tipAddr2 = \"192.168.2.1/24\"\n\t\tipAddr3 = \"192.168.3.1/24\"\n\t)\n\n\t// defines 3 interfaces\n\t_, index, interfaces := testInitialization(t, map[string][]string{\n\t\tifName0: {ipAddr0, ipAddr1},\n\t\tifName1: {ipAddr2},\n\t\tifName2: {ipAddr3},\n\t})\n\n\t// register all interfaces\n\tfor i, iface := range interfaces {\n\t\tindex.RegisterName(iface.Name, uint32(i), iface)\n\t}\n\n\t// try to lookup each interface by each ip adress\n\tifaces := index.LookupNameByIP(ipAddr0)\n\tExpect(ifaces).To(ContainElement(ifName0))\n\n\tifaces = index.LookupNameByIP(ipAddr1)\n\tExpect(ifaces).To(ContainElement(ifName0))\n\n\tifaces = index.LookupNameByIP(ipAddr2)\n\tExpect(ifaces).To(ContainElement(ifName1))\n\n\tifaces = index.LookupNameByIP(ipAddr3)\n\tExpect(ifaces).To(ContainElement(ifName2))\n\n\t// try empty lookup, should return nothing\n\tifaces = index.LookupNameByIP(\"\")\n\tExpect(ifaces).To(BeEmpty())\n}", "func TestIsInternal(t *testing.T) {\n\tf, err := os.Open(\"internal_names.txt\")\n\tif err != nil {\n\t\tt.Fatal(\"could not read test data\")\n\t}\n\tdefer f.Close()\n\tfor input := bufio.NewScanner(f); input.Scan(); {\n\t\tif name := input.Text(); !isInternal(name) {\n\t\t\tt.Logf(\"name '%s' should be internal but was not recognized\", name)\n\t\t\tt.Fail()\n\t\t}\n\t}\n\tf, err = os.Open(\"internal_notnames.txt\")\n\tif err != nil {\n\t\tt.Fatal(\"could not read test data\")\n\t}\n\tdefer f.Close()\n\tfor input := bufio.NewScanner(f); input.Scan(); {\n\t\tif name := input.Text(); isInternal(name) {\n\t\t\tt.Logf(\"name '%s' should not be internal but was recognized\", name)\n\t\t\tt.Fail()\n\t\t}\n\t}\n}", "func TestPttMaps(t *testing.T) {\n\n\t// Test PttValue map\n\tfor pName, pValue := range goHamlib.PttValue {\n\t\t_, ok := goHamlib.PttName[pValue]\n\t\tif !ok {\n\t\t\tt.Fatalf(\"Ptt %d does not exist in PttName map\", pValue)\n\t\t}\n\t\tif pName != goHamlib.PttName[pValue] {\n\t\t\tt.Fatalf(\"Name of Ptt inconsisted: %s\", pName)\n\t\t}\n\t}\n\n\t// Test PttName map\n\tfor pValue, pName := range goHamlib.PttName {\n\t\t_, ok := goHamlib.PttValue[pName]\n\t\tif !ok {\n\t\t\tt.Fatalf(\"Ptt %s does not exist in PttValue map\", pName)\n\t\t}\n\t\tif pValue != goHamlib.PttValue[pName] {\n\t\t\tt.Fatalf(\"Value of Ptt inconsisted: %s\", pName)\n\t\t}\n\t}\n}", "func Test_interface001(t *testing.T) {\n\ts1 := make([]int, 10, 20)\n\ttest1(&s1)\n\tfmt.Println(s1)\n\n\tfmt.Println(len(s1))\n\n\ts2 := make(map[string]int)\n\ttest2(s2)\n\tfmt.Println(s2)\n\tfmt.Println(s2[\"aaaaa\"])\n\n\ts3 := make(map[string]sample1)\n\ttest2(s3)\n\tfmt.Println(s3)\n\n\ttype1 := reflect.MapOf(reflect.TypeOf(\"\"), reflect.TypeOf(1))\n\tfmt.Println(type1)\n\tfmt.Println(type1.Elem().Kind())\n\ts4 := reflect.MakeMap(type1)\n\tfmt.Println(s4.Kind())\n\tfmt.Println(s4.Type().Key().Kind())\n\tfmt.Println(s4.Type().Elem().Kind())\n\n\ts4.SetMapIndex(reflect.ValueOf(\"ccccc\"), reflect.ValueOf(3333))\n\n\tfmt.Println(s4)\n\n}", "func TestUpdateLookup(t *testing.T) {\n\t//minerva := NewTester()\n\tvar b [32]byte\n\tfor i := 0; i < 32; i++ {\n\t\tb[i] = RandUint() % 255\n\t}\n\t//dataset:= make([]uint64, TBLSIZE*DATALENGTH*PMTSIZE*32)\n\t//flag,dataset := minerva.updateLookupTBL(22250,dataset)\n\t//if flag {\n\t//\tt.Log(\"dataset:\",dataset)\n\t//}else {\n\t//\tt.Error(\"======update-err=====\",flag)\n\t//}\n}", "func TestMapString(t *testing.T) {\n\tt.Parallel()\n\tvar tests = []struct {\n\t\ts []string\n\t\texpected []string\n\t}{\n\t\t{[]string{\"foo\", \"bar\"}, []string{\"FOO\", \"BAR\"}},\n\t\t{[]string{\"foo\", \"\\u0062\\u0061\\u0072\"}, []string{\"FOO\", \"BAR\"}},\n\t\t{[]string{}, []string{}},\n\t}\n\tfor _, test := range tests {\n\t\tactual := primitives.MapString(test.s, strings.ToUpper)\n\t\tassert.True(t, primitives.EqSlices(&actual, &test.expected), \"Expected MapString(%q, fn) to be %q, got %v\", test.s, test.expected, actual)\n\t}\n}", "func TestCount1024(t *testing.T) {\n\thm, _ := NewHashMap(1024)\n\ttestCountN(testN, hm)\n}", "func TestPrewriteWrittenNoConflict4A(t *testing.T) {\n}", "func TestPCall(t *testing.T){\n\tfilename := \"main.lua\"\n\tls := golua.NewLuaState()\n\tls.LoadFile(filename)\n\tif err := ls.PCall(0, 0, 0); err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func TestGet1024(t *testing.T) {\n\thm, _ := NewHashMap(1024)\n\ttestGetN(testN, hm)\n}", "func test(i Instruction, ls *LuaState) {\n\ta, _, c := i.ABC()\n\ta += 1\n\n\tif luaToBoolean(ls, a) != (c != 0) {\n\t\tls.addPC(1)\n\t}\n}", "func TestIpfsAdd(t *testing.T) {\n\tvar (\n\t\texpect = \"QmPZ9gcCEpqKTo6aq61g2nXGUhM4iCL3ewB6LDXZCtioEB\"\n\t)\n\tgot, err := IpfsAdd(testConfig, \"testdata/ipfs/readme\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif got != expect {\n\t\tt.Errorf(\"expect %s got %s\", expect, got)\n\t}\n\n}", "func TestClientInternal(t *testing.T) {\n\t// TODO: make these tests parallized\n\ttestCases := []struct {\n\t\tname string\n\t\tf func(t *testing.T)\n\t}{\n\t\t{name: \"ClusterConnectionConfigRetryTime\", f: clientClusterConnectionConfigRetryTimeTest},\n\t\t{name: \"ClusterID\", f: clientInternalClusterIDTest},\n\t\t{name: \"ClusterID_2\", f: clientInternalClusterID_2Test},\n\t\t{name: \"ConnectedToMember\", f: clientInternalConnectedToMemberTest},\n\t\t{name: \"EncodeData\", f: clientInternalEncodeDataTest},\n\t\t{name: \"InfiniteRestart\", f: infiniteReconnectTest},\n\t\t{name: \"InternalInvokeOnKey\", f: clientInternalInvokeOnKeyTest},\n\t\t{name: \"InternalListenersAfterClientDisconnected\", f: clientInternalListenersAfterClientDisconnectedTest},\n\t\t{name: \"InvokeOnMember\", f: clientInternalInvokeOnMemberTest},\n\t\t{name: \"InvokeOnPartition\", f: clientInternalInvokeOnPartitionTest},\n\t\t{name: \"InvokeOnRandomTarget\", f: clientInternalInvokeOnRandomTargetTest},\n\t\t{name: \"NoReconnect\", f: noReconnectTest},\n\t\t{name: \"NotReceivedInvocation\", f: clientInternalNotReceivedInvocationTest},\n\t\t{name: \"OrderedMembers\", f: clientInternalOrderedMembersTest},\n\t\t{name: \"ProxyManagerShutdown\", f: proxyManagerShutdownTest},\n\t}\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, tc.f)\n\t}\n}", "func TestFetchMirrorNameIdMapInternal(t *testing.T) {\n\tfor _, json := range []string{\n\t\t`{\"data\":[[\"m0018\",[\"uuid\",\"d5dfa2a6-7633-4f13-89d9-ecfa2b161bda\"],[\"uuid\",\"62208f49-cf74-4275-8db9-34a023a686c9\"]],[\"m0017\",[\"uuid\",\"5ab854d3-b050-48de-9d60-3f5791478d1c\"],[\"set\",[]]]],\"headings\":[\"name\",\"_uuid\",\"output_port\"]}`,\n\t\t`{\"data\":[[\"m0018\",[\"uuid\",\"518561f0-2b69-46c3-9455-dd04d01dc5f5\"],[\"uuid\",\"62208f49-cf74-4275-8db9-34a023a686c9\"]]],\"headings\":[\"name\",\"_uuid\",\"output_port\"]}`,\n\t} {\n\t\tret, err := fetchMirrorNameIdMapInternal([]byte(json))\n\t\tif err != nil {\n\t\t\tt.Errorf(\"fetchMirrorNameIdMapInternal fail %s\", err)\n\t\t} else {\n\t\t\tt.Logf(\"%s\", jsonutils.Marshal(ret))\n\t\t}\n\t}\n}", "func testAddrIndexOperations(t *testing.T, db database.Db, newestBlock *dcrutil.Block, newestSha *chainhash.Hash, newestBlockIdx int64) {\n\t// Metadata about the current addr index state should be unset.\n\tsha, height, err := db.FetchAddrIndexTip()\n\tif err != database.ErrAddrIndexDoesNotExist {\n\t\tt.Fatalf(\"Address index metadata shouldn't be in db, hasn't been built up yet.\")\n\t}\n\n\tvar zeroHash chainhash.Hash\n\tif !sha.IsEqual(&zeroHash) {\n\t\tt.Fatalf(\"AddrIndexTip wrong hash got: %s, want %s\", sha, &zeroHash)\n\n\t}\n\n\tif height != -1 {\n\t\tt.Fatalf(\"Addrindex not built up, yet a block index tip has been set to: %d.\", height)\n\t}\n\n\t// Test enforcement of constraints for \"limit\" and \"skip\"\n\tvar fakeAddr dcrutil.Address\n\t_, _, err = db.FetchTxsForAddr(fakeAddr, -1, 0, false)\n\tif err == nil {\n\t\tt.Fatalf(\"Negative value for skip passed, should return an error\")\n\t}\n\n\t_, _, err = db.FetchTxsForAddr(fakeAddr, 0, -1, false)\n\tif err == nil {\n\t\tt.Fatalf(\"Negative value for limit passed, should return an error\")\n\t}\n\n\t// Simple test to index outputs(s) of the first tx.\n\ttestIndex := make(database.BlockAddrIndex, database.AddrIndexKeySize)\n\ttestTx, err := newestBlock.Tx(0)\n\tif err != nil {\n\t\tt.Fatalf(\"Block has no transactions, unable to test addr \"+\n\t\t\t\"indexing, err %v\", err)\n\t}\n\n\t// Extract the dest addr from the tx.\n\t_, testAddrs, _, err := txscript.ExtractPkScriptAddrs(testTx.MsgTx().TxOut[0].Version, testTx.MsgTx().TxOut[0].PkScript, &chaincfg.MainNetParams)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to decode tx output, err %v\", err)\n\t}\n\n\t// Extract the hash160 from the output script.\n\tvar hash160Bytes [ripemd160.Size]byte\n\ttestHash160 := testAddrs[0].(*dcrutil.AddressScriptHash).Hash160()\n\tcopy(hash160Bytes[:], testHash160[:])\n\n\t// Create a fake index.\n\tblktxLoc, _, _ := newestBlock.TxLoc()\n\ttestIndex = []*database.TxAddrIndex{\n\t\t&database.TxAddrIndex{\n\t\t\tHash160: hash160Bytes,\n\t\t\tHeight: uint32(newestBlockIdx),\n\t\t\tTxOffset: uint32(blktxLoc[0].TxStart),\n\t\t\tTxLen: uint32(blktxLoc[0].TxLen),\n\t\t},\n\t}\n\n\t// Insert our test addr index into the DB.\n\terr = db.UpdateAddrIndexForBlock(newestSha, newestBlockIdx, testIndex)\n\tif err != nil {\n\t\tt.Fatalf(\"UpdateAddrIndexForBlock: failed to index\"+\n\t\t\t\" addrs for block #%d (%s) \"+\n\t\t\t\"err %v\", newestBlockIdx, newestSha, err)\n\t}\n\n\t// Chain Tip of address should've been updated.\n\tassertAddrIndexTipIsUpdated(db, t, newestSha, newestBlockIdx)\n\n\t// Check index retrieval.\n\ttxReplies, _, err := db.FetchTxsForAddr(testAddrs[0], 0, 1000, false)\n\tif err != nil {\n\t\tt.Fatalf(\"FetchTxsForAddr failed to correctly fetch txs for an \"+\n\t\t\t\"address, err %v\", err)\n\t}\n\t// Should have one reply.\n\tif len(txReplies) != 1 {\n\t\tt.Fatalf(\"Failed to properly index tx by address.\")\n\t}\n\n\t// Our test tx and indexed tx should have the same sha.\n\tindexedTx := txReplies[0]\n\tif !bytes.Equal(indexedTx.Sha.Bytes(), testTx.Sha().Bytes()) {\n\t\tt.Fatalf(\"Failed to fetch proper indexed tx. Expected sha %v, \"+\n\t\t\t\"fetched %v\", testTx.Sha(), indexedTx.Sha)\n\t}\n\n\t// Shut down DB.\n\tdb.Sync()\n\tdb.Close()\n\n\t// Re-Open, tip still should be updated to current height and sha.\n\tdb, err = database.OpenDB(\"leveldb\", \"tstdbopmode\")\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to re-open created db, err %v\", err)\n\t}\n\tassertAddrIndexTipIsUpdated(db, t, newestSha, newestBlockIdx)\n\n\t// Delete the entire index.\n\terr = db.PurgeAddrIndex()\n\tif err != nil {\n\t\tt.Fatalf(\"Couldn't delete address index, err %v\", err)\n\t}\n\n\t// Former index should no longer exist.\n\ttxReplies, _, err = db.FetchTxsForAddr(testAddrs[0], 0, 1000, false)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to fetch transactions for address: %v\", err)\n\t}\n\tif len(txReplies) != 0 {\n\t\tt.Fatalf(\"Address index was not successfully deleted. \"+\n\t\t\t\"Should have 0 tx's indexed, %v were returned.\",\n\t\t\tlen(txReplies))\n\t}\n\n\t// Tip should be blanked out.\n\tif _, _, err := db.FetchAddrIndexTip(); err != database.ErrAddrIndexDoesNotExist {\n\t\tt.Fatalf(\"Address index was not fully deleted.\")\n\t}\n\n}", "func TestMine(t *testing.T) {\n\ttest := tests[4] // only one we have complete data for\n\n\t// note that this has no MerkleRoot, as above ..\n\tserverData := coin.InComing{\n\t\tVersion: test.v,\n\t\tPrevBlock: test.pb,\n\t\tTimeStamp: test.tme,\n\t\tBits: test.bits,\n\t\tCoinBase: txHashes[0], // but refers to txn hash list\n\t\tTxHashes: txHashes[1:],\n\t\tShare: 3,\n\t}\n\ttask := server.SetTask(serverData) // we get this data from the server\n\n\t// for success, you need to make Cls == 856192328 (Mod N)\n\tif (test.nce)%N != Cls {\n\t\tfmt.Printf(\"\\n** Note you will not find a solution! needs Cls == %d (Mod N)\\n\", test.nce)\n\t}\n\tSearch(task)\n}", "func TestGetNone4A(t *testing.T) {\n}", "func TestPrewriteOverwrite4A(t *testing.T) {\n}", "func TestGetEmpty4A(t *testing.T) {\n}", "func testConcurrentMap(t *testing.T, datas map[interface{}]interface{}) {\n\tvar firstKey, firstVal interface{}\n\tvar secondaryKey, secondaryVal interface{}\n\ti := 0\n\tfor k, v := range datas {\n\t\tif i == 0 {\n\t\t\tfirstKey, firstVal = k, v\n\t\t} else if i == 1 {\n\t\t\tsecondaryKey, secondaryVal = k, v\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t}\n\n\tm := NewConcurrentMap()\n\n\t//test Put first key-value pair\n\tpreviou, err := m.Put(firstKey, firstVal)\n\tif previou != nil || err != nil {\n\t\tt.Errorf(\"Put %v, %v firstly, return %v, %v, want nil, nil\", firstKey, firstVal, previou, err)\n\t}\n\n\t//test Put again\n\tpreviou, err = m.Put(firstKey, firstVal)\n\tif previou != firstVal || err != nil {\n\t\tt.Errorf(\"Put %v, %v second time, return %v, %v, want %v, nil\", firstKey, firstVal, previou, err, firstVal)\n\t}\n\n\t//test PutIfAbsent, if value is incorrect, PutIfAbsent will be ignored\n\tv := rand.Float32()\n\tpreviou, err = m.PutIfAbsent(firstKey, v)\n\tif previou != firstVal || err != nil {\n\t\tt.Errorf(\"PutIfAbsent %v, %v three time, return %v, %v, want %v, nil\", firstKey, v, previou, err, firstVal)\n\t}\n\n\t//test Get\n\tval, err := m.Get(firstKey)\n\tif val != firstVal || err != nil {\n\t\tt.Errorf(\"Get %v, return %v, %v, want %v, nil\", firstKey, val, err, firstVal)\n\t}\n\n\t//test Size\n\ts := m.Size()\n\tif s != 1 {\n\t\tt.Errorf(\"Get size of m, return %v, want 1\", s)\n\t}\n\n\t//test PutAll\n\tm.PutAll(datas)\n\ts = m.Size()\n\tif s != int32(len(datas)) {\n\t\tt.Errorf(\"Get size of m, return %v, want %v\", s, len(datas))\n\t}\n\n\t//test remove a key-value pair, if value is incorrect, RemoveKV will return be ignored and return false\n\tok, err := m.RemoveEntry(secondaryKey, v)\n\tif ok != false || err != nil {\n\t\tt.Errorf(\"RemoveKV %v, %v, return %v, %v, want false, nil\", secondaryKey, v, ok, err)\n\t}\n\n\t//test replace a value for a key\n\tpreviou, err = m.Replace(secondaryKey, v)\n\tif previou != secondaryVal || err != nil {\n\t\tt.Errorf(\"Replace %v, %v, return %v, %v, want %v, nil\", secondaryKey, v, previou, err, secondaryVal)\n\t}\n\n\t//test replace a value for a key-value pair, if value is incorrect, replace will ignored and return false\n\tok, err = m.CompareAndReplace(secondaryKey, secondaryVal, v)\n\tif ok != false || err != nil {\n\t\tt.Errorf(\"ReplaceWithOld %v, %v, %v, return %v, %v, want false, nil\", secondaryKey, secondaryVal, v, ok, err)\n\t}\n\n\t//test replace a value for a key-value pair, if value is correct, replace will success\n\tok, err = m.CompareAndReplace(secondaryKey, v, secondaryVal)\n\tif ok != true || err != nil {\n\t\tt.Errorf(\"ReplaceWithOld %v, %v, %v, return %v, %v, want true, nil\", secondaryKey, v, secondaryVal, ok, err)\n\t}\n\n\t//test remove a key\n\tpreviou, err = m.Remove(secondaryKey)\n\tif previou != secondaryVal || err != nil {\n\t\tt.Errorf(\"Remove %v, return %v, %v, want %v, nil\", secondaryKey, previou, err, secondaryVal)\n\t}\n\n\t//test clear\n\tm.Clear()\n\tif m.Size() != 0 {\n\t\tt.Errorf(\"Get size of m after calling Clear(), return %v, want 0\", val)\n\t}\n}", "func TestCommitConflictRepeat4A(t *testing.T) {\n}", "func TestMapInt(t *testing.T) {\n\tt.Parallel()\n\tvar tests = []struct {\n\t\ts []int\n\t\texpected []int\n\t}{\n\t\t{[]int{0, 1, 2}, []int{0, 2, 4}},\n\t\t{[]int{-1}, []int{-2}},\n\t\t{[]int{}, []int{}},\n\t}\n\tfor _, test := range tests {\n\t\tactual := primitives.MapInt(test.s, func(i int) int {\n\t\t\treturn i * 2\n\t\t})\n\t\tassert.True(t, primitives.EqSlices(&actual, &test.expected), \"Expected MapInt(%q, fn) to be %q, got %v\", test.s, test.expected, actual)\n\t}\n}", "func testItrWithoutClose(t *testing.T, itr ledger.QueryResultsIterator, expectedKeys []string) {\n\tfor _, expectedKey := range expectedKeys {\n\t\tqueryResult, err := itr.Next()\n\t\trequire.NoError(t, err, \"An unexpected error was thrown during iterator Next()\")\n\t\tvkv := queryResult.(*queryresult.KV)\n\t\tkey := vkv.Key\n\t\trequire.Equal(t, expectedKey, key)\n\t}\n\tqueryResult, err := itr.Next()\n\trequire.NoError(t, err, \"An unexpected error was thrown during iterator Next()\")\n\trequire.Nil(t, queryResult)\n}", "func TestMultiplePrewrites4A(t *testing.T) {\n}", "func TestOperationMaps(t *testing.T) {\n\n\t// Test OperationValue map\n\tfor opName, opValue := range goHamlib.VFOOperationValue {\n\t\t_, ok := goHamlib.VFOOperationName[opValue]\n\t\tif !ok {\n\t\t\tt.Fatalf(\"Operation %d does not exist in OperationName map\", opValue)\n\t\t}\n\t\tif opName != goHamlib.VFOOperationName[opValue] {\n\t\t\tt.Fatalf(\"Name of Operation inconsisted: %s\", opName)\n\t\t}\n\t}\n\n\t// Test OperationName map\n\tfor opValue, opName := range goHamlib.VFOOperationName {\n\t\t_, ok := goHamlib.VFOOperationValue[opName]\n\t\tif !ok {\n\t\t\tt.Fatalf(\"Operation %s does not exist in OperationValue map\", opName)\n\t\t}\n\t\tif opValue != goHamlib.VFOOperationValue[opName] {\n\t\t\tt.Fatalf(\"Value of Operation inconsisted: %s\", opName)\n\t\t}\n\t}\n}", "func TestFindian(t *testing.T) {\n\tfor i, each := range inputs {\n\t\tresult := findian(strings.ToLower(each))\n\t\tif outputs[i] == result {\n\t\t\tcontinue\n\t\t} else {\n\t\t\tfmt.Println(\"tests failed\")\n\t\t}\n\t}\n\tfmt.Println(\"tests passed\")\n}", "func TestBuildAcctMap(t *testing.T) {\n\tacctMapExpect := map[string]string{\n\t\t\"000000000001\": \"Test Team 1\",\n\t\t\"000000000011\": \"Test Team 1\",\n\t\t\"000000000002\": \"Test Team 2\",\n\t\t\"000000000022\": \"Test Team 2\",\n\t}\n\n\tgeneratedMap := BuildAcctMap(exampleTeamMap)\n\n\tfor _, acct := range generatedMap {\n\t\tif acctMapExpect[acct] != generatedMap[acct] {\n\t\t\tt.Errorf(\"ERROR: Incorrect map created for %v\", acct)\n\t\t}\n\t}\n}", "func TestIntegrationRun(t *testing.T) {\n\tconst authToken = \"gina:foo\"\n\tconst attrKey = \"key\"\n\tconst attrValue = \"value\"\n\n\tresponder := httputil.FileResponder(\"testdata/batchresponse.json\")\n\ttransport, err := httputil.NewRegexpFakeTransport([]*httputil.Matcher{\n\t\t&httputil.Matcher{`^https\\://api\\.pinboard\\.in/v1/posts/all\\?auth_token=gina:foo&format=json&results=10000&todt=\\d\\d\\d\\d.*`, responder},\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\timptest.ImporterTest(t, \"pinboard\", transport, func(rc *importer.RunContext) {\n\t\terr = rc.AccountNode().SetAttrs(attrAuthToken, authToken)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\ttestee := imp{}\n\t\tif err := testee.Run(rc); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tpostsNode, err := imptest.GetRequiredChildPathObj(rc.RootNode(), \"posts\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tchildRefs, err := imptest.FindChildRefs(postsNode)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\texpectedPosts := map[string]string{\n\t\t\t`https://wiki.archlinux.org/index.php/xorg#Display_size_and_DPI`: \"Xorg - ArchWiki\",\n\t\t\t`http://www.harihareswara.net/sumana/2014/08/17/0`: \"One Way Confidence Will Look\",\n\t\t\t`http://www.wikiart.org/en/marcus-larson/fishing-near-the-fjord-by-moonlight-1862`: \"Fishing Near The Fjord By Moonlight - Marcus Larson - WikiArt.org\",\n\t\t}\n\n\t\tif len(childRefs) != len(expectedPosts) {\n\t\t\tt.Fatalf(\"After import, found %d child refs, want %d: %v\", len(childRefs), len(expectedPosts), childRefs)\n\t\t}\n\n\t\tfor _, ref := range childRefs {\n\t\t\tchildNode, err := rc.Host.ObjectFromRef(ref)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tfoundURL := childNode.Attr(nodeattr.URL)\n\t\t\texpectedTitle, ok := expectedPosts[foundURL]\n\t\t\tif !ok {\n\t\t\t\tt.Fatalf(\"Found unexpected child node %v with url %q\", childNode, foundURL)\n\t\t\t}\n\t\t\tfoundTitle := childNode.Attr(nodeattr.Title)\n\t\t\tif foundTitle != expectedTitle {\n\t\t\t\tt.Fatalf(\"Found unexpected child node %v with title %q when we want %q\", childNode, foundTitle, expectedTitle)\n\t\t\t}\n\t\t\tdelete(expectedPosts, foundURL)\n\t\t}\n\t\tif len(expectedPosts) != 0 {\n\t\t\tt.Fatalf(\"The following entries were expected but not found: %#v\", expectedPosts)\n\t\t}\n\t})\n}", "func (*mapTests) TestCheckDatabaseAccessible(ctx context.Context, t *testing.T, s storage.MapStorage, _ storage.AdminStorage) {\n\tif err := s.CheckDatabaseAccessible(ctx); err != nil {\n\t\tt.Errorf(\"CheckDatabaseAccessible() = %v, want = nil\", err)\n\t}\n}", "func TestGetTuplesCmd(t *testing.T) {\n\tbaseArgs := []string{debugCmdString, getTuplesCmdString}\n\tstandardArgs := concatArgs(baseArgs, srcFlag, testIP1, dstFlag, testIP2)\n\n\ttests := []*testCases{\n\t\t{\n\t\t\tname: \"no src or dst\",\n\t\t\targs: baseArgs,\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"no src\",\n\t\t\targs: concatArgs(baseArgs, dstFlag, testIP2),\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"no dst\",\n\t\t\targs: concatArgs(baseArgs, srcFlag, testIP1),\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"unknown shorthand flag\",\n\t\t\targs: concatArgs(standardArgs, unknownShorthandFlag),\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"iptables save file but no cache file\",\n\t\t\targs: concatArgs(standardArgs, iptablesSaveFileFlag, iptableSaveFile),\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"iptables save file but bad cache file\",\n\t\t\targs: concatArgs(standardArgs, iptablesSaveFileFlag, iptableSaveFile, npmCacheFlag, nonExistingFile),\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"cache file but no iptables save file\",\n\t\t\targs: concatArgs(standardArgs, npmCacheFlag, npmCacheFile),\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"cache file but bad iptables save file\",\n\t\t\targs: concatArgs(standardArgs, iptablesSaveFileFlag, nonExistingFile, npmCacheFlag, npmCacheFile),\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"correct files\",\n\t\t\targs: concatArgs(standardArgs, iptablesSaveFileFlag, iptableSaveFile, npmCacheFlag, npmCacheFile),\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"correct files with file order switched\",\n\t\t\targs: concatArgs(standardArgs, npmCacheFlag, npmCacheFile, iptablesSaveFileFlag, iptableSaveFile),\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"src/dst after files\",\n\t\t\targs: concatArgs(baseArgs, npmCacheFlag, npmCacheFile, iptablesSaveFileFlag, iptableSaveFile, srcFlag, testIP1, dstFlag, testIP2),\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"shorthand flags before command\",\n\t\t\targs: []string{debugCmdString, srcFlag, testIP1, dstFlag, testIP2, iptablesSaveFileFlag, iptableSaveFile, npmCacheFlag, npmCacheFile, getTuplesCmdString},\n\t\t\twantErr: false,\n\t\t},\n\t}\n\n\ttestCommand(t, tests)\n}", "func TestKeys(t *testing.T) {\n\tvar db_filename string = \"test.gdbm\" // pending the test_cleanup merge\n\n\tos.Remove(db_filename) // pending the test_cleanup merge\n\tdb, err := Open(db_filename, \"c\")\n\tif err != nil {\n\t\tt.Error(\"Couldn't create new database\")\n\t}\n\tdefer db.Close()\n\tdefer os.Remove(db_filename)\n\n\terr = db.Insert(\"foo\", \"bar\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\terr = db.Insert(\"baz\", \"bax\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\terr = db.Insert(\"biff\", \"bixx\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\n\texpected_keys := []string{\n\t\t\"foo\",\n\t\t\"baz\",\n\t\t\"biff\",\n\t}\n\n\tk, err := db.FirstKey()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !ListContains(expected_keys, k) {\n\t\tt.Errorf(\"FirstKey() expected: %s\", expected_keys)\n\t}\n\n\tfor i := 1; i < len(expected_keys); i++ {\n\t\tn, err := db.NextKey(k)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif !ListContains(expected_keys, n) {\n\t\t\tt.Errorf(\"NextKey() expected: %s\", expected_keys)\n\t\t}\n\t}\n\n}", "func TestUpdateMetadata(t *testing.T) {\n\t// Constants\n\tconst (\n\t\tifName0 = \"if0\"\n\t\tipAddr0 = \"192.168.0.1/24\"\n\t\tipAddr1 = \"192.168.1.1/24\"\n\t\tipAddr2 = \"192.168.2.1/24\"\n\t\tipAddr3 = \"192.168.3.1/24\"\n\t\tidx0 uint32 = 0\n\t)\n\n\tmapping, index, interfaces := testInitialization(t, map[string][]string{\n\t\tifName0: {ipAddr0, ipAddr1},\n\t})\n\n\t// Prepare some data\n\tif0 := interfaces[0]\n\n\tifUpdate1 := &intf.Interfaces_Interface{\n\t\tName: ifName0,\n\t\tIpAddresses: []string{ipAddr2},\n\t}\n\n\tifUpdate2 := &intf.Interfaces_Interface{\n\t\tName: ifName0,\n\t\tIpAddresses: []string{ipAddr3},\n\t}\n\n\t// Update before registration (no entry created)\n\tsuccess := index.UpdateMetadata(if0.Name, if0)\n\tExpect(success).To(BeFalse())\n\n\t_, metadata, found := mapping.LookupIdx(if0.Name)\n\tExpect(found).To(BeFalse())\n\tExpect(metadata).To(BeNil())\n\n\t// Register interface name\n\tindex.RegisterName(if0.Name, idx0, if0)\n\tnames := mapping.ListNames()\n\tExpect(names).To(HaveLen(1))\n\tExpect(names).To(ContainElement(if0.Name))\n\n\t// Evaluate entry metadata\n\t_, metadata, found = mapping.LookupIdx(if0.Name)\n\tExpect(found).To(BeTrue())\n\tExpect(metadata).ToNot(BeNil())\n\n\tdata, ok := metadata.(*intf.Interfaces_Interface)\n\tExpect(ok).To(BeTrue())\n\tExpect(data.IpAddresses).To(HaveLen(2))\n\n\tipaddrs := data.IpAddresses\n\tExpect(ipaddrs).To(ContainElement(ipAddr0))\n\tExpect(ipaddrs).To(ContainElement(ipAddr1))\n\n\t// Update metadata (same name, different data)\n\tsuccess = index.UpdateMetadata(ifUpdate1.Name, ifUpdate1)\n\tExpect(success).To(BeTrue())\n\n\t// Evaluate updated metadata\n\t_, metadata, found = index.LookupIdx(if0.Name)\n\tExpect(found).To(BeTrue())\n\tExpect(metadata).ToNot(BeNil())\n\n\tdata, ok = metadata.(*intf.Interfaces_Interface)\n\tExpect(ok).To(BeTrue())\n\tExpect(data.IpAddresses).To(HaveLen(1))\n\n\tipaddrs = data.IpAddresses\n\tExpect(ipaddrs).To(ContainElement(ipAddr2))\n\n\t// Update metadata again\n\tsuccess = index.UpdateMetadata(ifUpdate2.Name, ifUpdate2)\n\tExpect(success).To(BeTrue())\n\n\t// Evaluate updated metadata\n\t_, metadata, found = mapping.LookupIdx(if0.Name)\n\tExpect(found).To(BeTrue())\n\tExpect(metadata).ToNot(BeNil())\n\n\tdata, ok = metadata.(*intf.Interfaces_Interface)\n\tExpect(ok).To(BeTrue())\n\tExpect(data.IpAddresses).To(HaveLen(1))\n\n\tipaddrs = data.IpAddresses\n\tExpect(ipaddrs).To(ContainElement(ipAddr3))\n\n\t// Unregister\n\tindex.UnregisterName(if0.Name)\n\n\t// Evaluate unregistration\n\tnames = mapping.ListNames()\n\tExpect(names).To(BeEmpty())\n}", "func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample)", "func TestIGMPHeader(t *testing.T) {\n\tconst maxRespTimeTenthSec = 0xF0\n\tb := []byte{\n\t\t0x11, // IGMP Type, Membership Query\n\t\tmaxRespTimeTenthSec, // Maximum Response Time\n\t\t0xC0, 0xC0, // Checksum\n\t\t0x01, 0x02, 0x03, 0x04, // Group Address\n\t}\n\n\tigmpHeader := header.IGMP(b)\n\n\tif got, want := igmpHeader.Type(), header.IGMPMembershipQuery; got != want {\n\t\tt.Errorf(\"got igmpHeader.Type() = %x, want = %x\", got, want)\n\t}\n\n\tif got, want := igmpHeader.MaxRespTime(), header.DecisecondToDuration(maxRespTimeTenthSec); got != want {\n\t\tt.Errorf(\"got igmpHeader.MaxRespTime() = %s, want = %s\", got, want)\n\t}\n\n\tif got, want := igmpHeader.Checksum(), uint16(0xC0C0); got != want {\n\t\tt.Errorf(\"got igmpHeader.Checksum() = %x, want = %x\", got, want)\n\t}\n\n\tif got, want := igmpHeader.GroupAddress(), testutil.MustParse4(\"1.2.3.4\"); got != want {\n\t\tt.Errorf(\"got igmpHeader.GroupAddress() = %s, want = %s\", got, want)\n\t}\n\n\tigmpType := header.IGMPv2MembershipReport\n\tigmpHeader.SetType(igmpType)\n\tif got := igmpHeader.Type(); got != igmpType {\n\t\tt.Errorf(\"got igmpHeader.Type() = %x, want = %x\", got, igmpType)\n\t}\n\tif got := header.IGMPType(b[0]); got != igmpType {\n\t\tt.Errorf(\"got IGMPtype in backing buffer = %x, want %x\", got, igmpType)\n\t}\n\n\trespTime := byte(0x02)\n\tigmpHeader.SetMaxRespTime(respTime)\n\tif got, want := igmpHeader.MaxRespTime(), header.DecisecondToDuration(uint16(respTime)); got != want {\n\t\tt.Errorf(\"got igmpHeader.MaxRespTime() = %s, want = %s\", got, want)\n\t}\n\n\tchecksum := uint16(0x0102)\n\tigmpHeader.SetChecksum(checksum)\n\tif got := igmpHeader.Checksum(); got != checksum {\n\t\tt.Errorf(\"got igmpHeader.Checksum() = %x, want = %x\", got, checksum)\n\t}\n\n\tgroupAddress := testutil.MustParse4(\"4.3.2.1\")\n\tigmpHeader.SetGroupAddress(groupAddress)\n\tif got := igmpHeader.GroupAddress(); got != groupAddress {\n\t\tt.Errorf(\"got igmpHeader.GroupAddress() = %s, want = %s\", got, groupAddress)\n\t}\n}", "func TestTrunkENI_getBranchInterfaceMap_EmptyList(t *testing.T) {\n\ttrunkENI := getMockTrunk()\n\n\tbranchENIsMap := trunkENI.getBranchInterfaceMap([]*ENIDetails{})\n\tassert.NotNil(t, branchENIsMap)\n\tassert.Zero(t, len(branchENIsMap))\n}", "func TestIterate(t *testing.T) {\n\tbuffer := bytes.NewBufferString(s19TestFile)\n\treader := Open(buffer)\n\tif reader != nil {\n\t\tdata := make([]byte, 0)\n\t\texpectedAddress := uint32(0x400)\n\t\tfor it := range reader.Records() {\n\t\t\trec := it.Record\n\t\t\terr := it.Error\n\t\t\tif err == io.EOF {\n\t\t\t\tt.Fatal(\"EOF not handled properly\")\n\t\t\t}\n\t\t\tif rec.Address() != expectedAddress {\n\t\t\t\tt.Fatalf(\"Address mismatch expected: %v got: %v\", expectedAddress, rec.Address())\n\t\t\t}\n\t\t\texpectedAddress += uint32(len(rec.Data()))\n\t\t\tdata = append(data, rec.Data()...)\n\t\t}\n\t\tif bytes.Compare(data, binaryTestFile[:]) != 0 {\n\t\t\tt.Error(\"Data read did not match reference values\")\n\t\t}\n\t} else {\n\t\tt.Fatal(\"Open call failed\")\n\t}\n}", "func runStringToIntMap() {\n\tvar string2IntMap = make(String2IntMap, 5)\n\tstring2IntMap[\"USA\"] = 100\n\tstring2IntMap[\"China\"] = 200\n\tfmt.Printf(\"Map says %d \\r\\n\", len(string2IntMap))\n\tdelete(string2IntMap, \"USA\")\n\tfmt.Printf(\"Map says %d \\r\\n\", len(string2IntMap))\n\tfmt.Printf(\"Map says %d \\r\\n\", string2IntMap[\"USA\"])\n\tfmt.Printf(\"Map says %d \\r\\n\", len(string2IntMap))\n}", "func TestCitadelInteg(t *testing.T) {\n\t// integ test suite\n\tvar sts = &integTestSuite{}\n\n\tvar _ = Suite(sts)\n\tTestingT(t)\n}", "func TestIndexMetadata(t *testing.T) {\n\t// Constants\n\tconst (\n\t\tifName0 = \"if0\"\n\t\tipAddr0 = \"192.168.0.1/24\"\n\t\tipAddr1 = \"192.168.1.1/24\"\n\t\tifaceNameIndexKey = \"ipAddrKey\"\n\t)\n\n\t_, _, interfaces := testInitialization(t, map[string][]string{\n\t\tifName0: {ipAddr0, ipAddr1},\n\t})\n\n\tiface := interfaces[0]\n\n\tresult := ifaceidx.IndexMetadata(nil)\n\tExpect(result).To(HaveLen(0))\n\n\tresult = ifaceidx.IndexMetadata(iface)\n\tExpect(result).To(HaveLen(1))\n\n\tipAddrs := result[ifaceNameIndexKey]\n\tExpect(ipAddrs).To(HaveLen(2))\n\tExpect(ipAddrs).To(ContainElement(ipAddr0))\n\tExpect(ipAddrs).To(ContainElement(ipAddr1))\n}", "func assertionCacheMapKey(name, zone, context string, oType object.Type) string {\n\tkey := fmt.Sprintf(\"%s %s %d\", mergeSubjectZone(name, zone), context, oType)\n\tlog.Debug(\"assertionCacheMapKey\", \"key\", key)\n\treturn key\n}", "func TestSequencing(t *testing.T) {\n\tfor _, ts := range testStrings {\n\t\tfor _, m := range utf8map {\n\t\t\tfor _, s := range []string{ts + m.str, m.str + ts, ts + m.str + ts} {\n\t\t\t\ttestSequence(t, s)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestMemoryDBIterator(t *testing.T) {\n\ttests := []struct {\n\t\tcontent map[string]string\n\t\tprefix string\n\t\torder []string\n\t}{\n\t\t// Empty databases should be iterable\n\t\t{map[string]string{}, \"\", nil},\n\t\t{map[string]string{}, \"non-existent-prefix\", nil},\n\n\t\t// Single-item databases should be iterable\n\t\t{map[string]string{\"key\": \"val\"}, \"\", []string{\"key\"}},\n\t\t{map[string]string{\"key\": \"val\"}, \"k\", []string{\"key\"}},\n\t\t{map[string]string{\"key\": \"val\"}, \"l\", nil},\n\n\t\t// Multi-item databases should be fully iterable\n\t\t{\n\t\t\tmap[string]string{\"k1\": \"v1\", \"k5\": \"v5\", \"k2\": \"v2\", \"k4\": \"v4\", \"k3\": \"v3\"},\n\t\t\t\"\",\n\t\t\t[]string{\"k1\", \"k2\", \"k3\", \"k4\", \"k5\"},\n\t\t},\n\t\t{\n\t\t\tmap[string]string{\"k1\": \"v1\", \"k5\": \"v5\", \"k2\": \"v2\", \"k4\": \"v4\", \"k3\": \"v3\"},\n\t\t\t\"k\",\n\t\t\t[]string{\"k1\", \"k2\", \"k3\", \"k4\", \"k5\"},\n\t\t},\n\t\t{\n\t\t\tmap[string]string{\"k1\": \"v1\", \"k5\": \"v5\", \"k2\": \"v2\", \"k4\": \"v4\", \"k3\": \"v3\"},\n\t\t\t\"l\",\n\t\t\tnil,\n\t\t},\n\t\t// Multi-item databases should be prefix-iterable\n\t\t{\n\t\t\tmap[string]string{\n\t\t\t\t\"ka1\": \"va1\", \"ka5\": \"va5\", \"ka2\": \"va2\", \"ka4\": \"va4\", \"ka3\": \"va3\",\n\t\t\t\t\"kb1\": \"vb1\", \"kb5\": \"vb5\", \"kb2\": \"vb2\", \"kb4\": \"vb4\", \"kb3\": \"vb3\",\n\t\t\t},\n\t\t\t\"ka\",\n\t\t\t[]string{\"ka1\", \"ka2\", \"ka3\", \"ka4\", \"ka5\"},\n\t\t},\n\t\t{\n\t\t\tmap[string]string{\n\t\t\t\t\"ka1\": \"va1\", \"ka5\": \"va5\", \"ka2\": \"va2\", \"ka4\": \"va4\", \"ka3\": \"va3\",\n\t\t\t\t\"kb1\": \"vb1\", \"kb5\": \"vb5\", \"kb2\": \"vb2\", \"kb4\": \"vb4\", \"kb3\": \"vb3\",\n\t\t\t},\n\t\t\t\"kc\",\n\t\t\tnil,\n\t\t},\n\t}\n\tfor i, tt := range tests {\n\t\t// Create the key-value data store\n\t\tdb := New()\n\t\tfor key, val := range tt.content {\n\t\t\tif err := db.Put([]byte(key), []byte(val)); err != nil {\n\t\t\t\tt.Fatalf(\"test %d: failed to insert item %s:%s into database: %v\", i, key, val, err)\n\t\t\t}\n\t\t}\n\t\t// Iterate over the database with the given configs and verify the results\n\t\tit, idx := db.NewIterator([]byte(tt.prefix), nil), 0\n\t\tfor it.Next() {\n\t\t\tif !bytes.Equal(it.Key(), []byte(tt.order[idx])) {\n\t\t\t\tt.Errorf(\"test %d: item %d: key mismatch: have %s, want %s\", i, idx, string(it.Key()), tt.order[idx])\n\t\t\t}\n\t\t\tif !bytes.Equal(it.Value(), []byte(tt.content[tt.order[idx]])) {\n\t\t\t\tt.Errorf(\"test %d: item %d: value mismatch: have %s, want %s\", i, idx, string(it.Value()), tt.content[tt.order[idx]])\n\t\t\t}\n\t\t\tidx++\n\t\t}\n\t\tif err := it.Error(); err != nil {\n\t\t\tt.Errorf(\"test %d: iteration failed: %v\", i, err)\n\t\t}\n\t\tif idx != len(tt.order) {\n\t\t\tt.Errorf(\"test %d: iteration terminated prematurely: have %d, want %d\", i, idx, len(tt.order))\n\t\t}\n\t}\n}" ]
[ "0.58750165", "0.5579175", "0.5518057", "0.5478015", "0.5452692", "0.54349846", "0.5404309", "0.53754455", "0.5356827", "0.53459847", "0.5344256", "0.5319205", "0.5308026", "0.529849", "0.52878636", "0.5249721", "0.524902", "0.5232891", "0.52287203", "0.52131915", "0.52124083", "0.51670504", "0.51608866", "0.51608866", "0.51558954", "0.51520836", "0.5136883", "0.51218534", "0.5117725", "0.5109099", "0.5100698", "0.50953084", "0.5092227", "0.5070349", "0.50661474", "0.5045769", "0.5002651", "0.50021046", "0.4999882", "0.49902067", "0.49901348", "0.49789965", "0.49785328", "0.49762088", "0.49674824", "0.4966762", "0.4960316", "0.4956361", "0.49512267", "0.4950628", "0.4943731", "0.49337217", "0.4924291", "0.49171695", "0.49152625", "0.49135235", "0.4909742", "0.48997656", "0.48943368", "0.48920307", "0.48912323", "0.4890126", "0.48830238", "0.4881454", "0.48781037", "0.48690736", "0.4865667", "0.4864354", "0.48602873", "0.48496908", "0.48466533", "0.48443532", "0.4841215", "0.48261496", "0.4821359", "0.48196158", "0.48137578", "0.48058593", "0.4805175", "0.4802886", "0.480284", "0.4799252", "0.4799173", "0.47744372", "0.47726297", "0.4763518", "0.47538346", "0.47529942", "0.47526175", "0.47519764", "0.474906", "0.4739508", "0.47387508", "0.47384423", "0.47339964", "0.47334248", "0.47325695", "0.47307596", "0.47294965", "0.47290778", "0.47263476" ]
0.0
-1
unionRegexp separates values with a | operator to create a string representing a union of regexp patterns.
func unionRegexp(values []string) string { if len(values) == 0 { // As a regular expression, "()" and "" are equivalent so this // condition wouldn't ordinarily be needed to distinguish these // values. But, our internal search engine assumes that "" // implies "no regexp" (no values), while "()" implies "match // empty regexp" (all values) for file patterns. return "" } if len(values) == 1 { // Cosmetic format for regexp value, wherever this happens to be // pretty printed. return values[0] } return "(" + strings.Join(values, ")|(") + ")" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewUnion(l, r Regex) Regex {\n\tswitch l.(type) {\n\tcase *empty:\n\t\treturn r\n\tdefault:\n\t\treturn &union{\n\t\t\tl: l,\n\t\t\tr: r,\n\t\t}\n\t}\n}", "func RegexpSimplify(re *syntax.Regexp,) *syntax.Regexp", "func CombinedPatternsGiven(patterns []*regexp.Regexp) *regexp.Regexp {\n\tvar allPatterns []string\n\tfor _, pattern := range patterns {\n\t\tallPatterns = append(allPatterns, pattern.String())\n\t}\n\treturn regexp.MustCompile(strings.Join(allPatterns, \"|\"))\n}", "func Union(a, operand []string) []string {\n\tuniq := make(map[string]bool, len(a)+len(operand))\n\tfor _, elem := range a {\n\t\tuniq[elem] = true\n\t}\n\tfor _, elem := range operand {\n\t\tuniq[elem] = true\n\t}\n\tunion := make([]string, len(uniq))\n\ti := 0\n\tfor k := range uniq {\n\t\tunion[i] = k\n\t\ti++\n\t}\n\treturn union[:i]\n}", "func unionSelector(a, b Selector) Selector {\n\treturn func(n *Node) bool {\n\t\treturn a(n) || b(n)\n\t}\n}", "func Unionize(lhs, rhs SelectStatement, unionType string, by OrderBy, limit *Limit, lock string) *Union {\n\n\tunion, isUnion := lhs.(*Union)\n\tif isUnion {\n\t\tunion.UnionSelects = append(union.UnionSelects, &UnionSelect{UnionType: unionType, Statement: rhs})\n\t\tunion.OrderBy = by\n\t\tunion.Limit = limit\n\t\tunion.Lock = lock\n\t\treturn union\n\t}\n\n\treturn &Union{FirstStatement: lhs, UnionSelects: []*UnionSelect{{UnionType: unionType, Statement: rhs}}, OrderBy: by, Limit: limit, Lock: lock}\n}", "func TestUnion(t *testing.T) {\n\ttests := []struct {\n\t\tnote string\n\t\trules []string\n\t\texpected interface{}\n\t}{\n\t\t{\"union_0_sets\", []string{`p = x { union(set(), x) }`}, \"[]\"},\n\t\t{\"union_2_sets\", []string{`p = x { union({set(), {1, 2}}, x) }`}, \"[1, 2]\"},\n\t\t{\"union_2_sets\", []string{`p = x { s1 = {1, 2, 3}; s2 = {2}; union({s1, s2}, x) }`}, \"[1, 2, 3]\"},\n\t\t{\"union_3_sets\", []string{`p = x { s1 = {1, 2, 3}; s2 = {2, 3, 4}; s3 = {4, 5, 6}; union({s1, s2, s3}, x) }`}, \"[1, 2, 3, 4, 5, 6]\"},\n\t\t{\"union_4_sets\", []string{`p = x { s1 = {\"a\", \"b\", \"c\", \"d\"}; s2 = {\"b\", \"c\", \"d\"}; s3 = {\"c\", \"d\"}; s4 = {\"d\"}; union({s1, s2, s3, s4}, x) }`}, \"[\\\"a\\\", \\\"b\\\", \\\"c\\\", \\\"d\\\"]\"},\n\t}\n\n\tdata := loadSmallTestData()\n\n\tfor _, tc := range tests {\n\t\trunTopDownTestCase(t, data, tc.note, tc.rules, tc.expected)\n\t}\n}", "func unconcat(r *syntax.Regexp) (bool, *syntax.Regexp) {\n\tswitch {\n\tcase r.Op == syntax.OpConcat && len(r.Sub) <= 1:\n\t\tif len(r.Sub) == 1 {\n\t\t\treturn true, r.Sub[0]\n\t\t}\n\n\t\treturn true, &syntax.Regexp{\n\t\t\tOp: syntax.OpEmptyMatch,\n\t\t\tFlags: r.Flags,\n\t\t}\n\n\tcase r.Op == syntax.OpRepeat && r.Min == r.Max && r.Min == 1:\n\t\treturn true, r.Sub[0]\n\t}\n\n\treturn false, r\n}", "func Funion(lista, listb []string) []string {\n\tlistx := append(lista, listb...)\n\tFcompress(&listx)\n\treturn listx\n}", "func union(a, b []string) [][]rune {\n\tm := make(map[string]bool)\n\tfor _, item := range a {\n\t\tm[item] = true\n\t}\n\tfor _, item := range b {\n\t\tif _, ok := m[item]; !ok {\n\t\t\ta = append(a, item)\n\t\t}\n\t}\n\n\t// Convert a to rune matrix (with x -> words and y -> characters)\n\tout := make([][]rune, len(a))\n\tfor i, word := range a {\n\t\tout[i] = []rune(word)\n\t}\n\treturn out\n}", "func union(left, right []string) []string {\n\tu := make([]string, len(left))\n\tcopy(u, left)\noutter:\n\tfor _, r := range right {\n\t\tfor _, l := range left {\n\t\t\tif l == r {\n\t\t\t\tcontinue outter\n\t\t\t}\n\t\t}\n\t\tu = append(u, r)\n\t}\n\treturn u\n}", "func uncapture(r *syntax.Regexp) (bool, *syntax.Regexp) {\n\tif r.Op == syntax.OpCapture {\n\t\t// try to uncapture\n\t\tif len(r.Sub) == 1 {\n\t\t\t_, sub := uncapture(r.Sub[0])\n\t\t\treturn true, sub\n\t\t}\n\n\t\ttmp := *r\n\t\ttmp.Op = syntax.OpConcat\n\t\tr = &tmp\n\t}\n\n\tsub := make([]*syntax.Regexp, len(r.Sub))\n\tmodified := false\n\tfor i := range r.Sub {\n\t\tvar m bool\n\t\tm, sub[i] = uncapture(r.Sub[i])\n\t\tmodified = modified || m\n\t}\n\n\tif !modified {\n\t\treturn false, r\n\t}\n\n\ttmp := *r\n\ttmp.Sub = sub\n\treturn true, &tmp\n}", "func buildRegexFromList(patterns []string) *regexp.Regexp {\n\tif patterns == nil || len(patterns) == 0 {\n\t\tpatterns = make([]string, 0)\n\t}\n\treturn compileOrDie(\"(?i)^(\" + strings.Join(patterns, \"|\") + \")$\")\n}", "func expandOr(r string) []string {\n\t// Find every occurrence of |-separated things.\n\t// They look like MOV(B|W|L|Q|SS|SD)load or MOV(Q|L)loadidx(1|8).\n\t// Generate rules selecting one case from each |-form.\n\n\t// Count width of |-forms. They must match.\n\tn := 1\n\tfor _, idx := range findAllOpcode(r, -1) {\n\t\tif excludeFromExpansion(r, idx) {\n\t\t\tcontinue\n\t\t}\n\t\ts := r[idx[0]:idx[1]]\n\t\tc := strings.Count(s, \"|\") + 1\n\t\tif c == 1 {\n\t\t\tcontinue\n\t\t}\n\t\tif n > 1 && n != c {\n\t\t\tlog.Fatalf(\"'|' count doesn't match in %s: both %d and %d\\n\", r, n, c)\n\t\t}\n\t\tn = c\n\t}\n\tif n == 1 {\n\t\t// No |-form in this rule.\n\t\treturn []string{r}\n\t}\n\t// Build each new rule.\n\tres := make([]string, n)\n\tfor i := 0; i < n; i++ {\n\t\tbuf := new(strings.Builder)\n\t\tx := 0\n\t\tfor _, idx := range findAllOpcode(r, -1) {\n\t\t\tif excludeFromExpansion(r, idx) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbuf.WriteString(r[x:idx[0]]) // write bytes we've skipped over so far\n\t\t\ts := r[idx[0]+1 : idx[1]-1] // remove leading \"(\" and trailing \")\"\n\t\t\tbuf.WriteString(strings.Split(s, \"|\")[i]) // write the op component for this rule\n\t\t\tx = idx[1] // note that we've written more bytes\n\t\t}\n\t\tbuf.WriteString(r[x:])\n\t\tres[i] = buf.String()\n\t}\n\treturn res\n}", "func (s *StrSet) Union(o *StrSet) StrSet {\n\tus := NewStr()\n\tfor el := range s.els {\n\t\tus.Add(el)\n\t}\n\tfor el := range o.els {\n\t\tus.Add(el)\n\t}\n\treturn us\n}", "func (s stringSet) union(o stringSet) stringSet {\n\tns := newStringSet()\n\tfor k := range s {\n\t\tns[k] = struct{}{}\n\t}\n\tfor k := range o {\n\t\tns[k] = struct{}{}\n\t}\n\treturn ns\n}", "func IncludeRegexp(expr string) (Filter, error) {\n\treturn regexpFilter(expr, false)\n}", "func RegexpString(re *syntax.Regexp,) string", "func group(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(`(?:` + expression(res...).String() + `)`)\n}", "func group(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(`(?:` + expression(res...).String() + `)`)\n}", "func group(res ...*regexp.Regexp) *regexp.Regexp {\n\treturn match(`(?:` + expression(res...).String() + `)`)\n}", "func AsUnion(dt DataType) *Union {\n\tswitch t := dt.(type) {\n\tcase *UserTypeExpr:\n\t\treturn AsUnion(t.Type)\n\tcase *ResultTypeExpr:\n\t\treturn AsUnion(t.Type)\n\tcase *Union:\n\t\treturn t\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (c *TransferCounter) CompileRegex(operator string) (*regexp.Regexp, error) {\n\tvar r *regexp.Regexp\n\tvar err error\n\n\tfor _, regionOperator := range regionOperators {\n\t\tif operator == regionOperator {\n\t\t\tr, err = regexp.Compile(\".*?operator finish.*?region-id=([0-9]*).*?\" + operator + \".*?store \\\\[([0-9]*)\\\\] to \\\\[([0-9]*)\\\\].*?\")\n\t\t}\n\t}\n\n\tfor _, leaderOperator := range leaderOperators {\n\t\tif operator == leaderOperator {\n\t\t\tr, err = regexp.Compile(\".*?operator finish.*?region-id=([0-9]*).*?\" + operator + \".*?store ([0-9]*) to ([0-9]*).*?\")\n\t\t}\n\t}\n\n\tif r == nil {\n\t\terr = errors.New(\"unsupported operator. \")\n\t}\n\treturn r, err\n}", "func Union(elements ...Shape) Shape {\n\treturn Group{space.NoTransformation(), elements}\n}", "func NewUnion(exs ...Extractor) *Union {\n\tvar union = &Union{Extractors: make([]Extractor, len(exs))}\n\tfor i, ex := range exs {\n\t\tunion.Extractors[i] = ex\n\t}\n\treturn union\n}", "func compile(regex string) (regslc []rune) {\n regslc = make([]rune, 0, len(regex) + 10)\n \n for _, r := range regex {\n if r == '+' {\n regslc = append(regslc, regslc[len(regslc) - 1], '*')\n } else {\n regslc = append(regslc, r)\n }\n } \n return regslc\n }", "func (stmt *statement) Union(all bool, query Statement) Statement {\n\tp := posUnion\n\tif len(stmt.parts) > 0 {\n\t\tlast := (&stmt.parts[len(stmt.parts)-1]).position\n\t\tif last >= p {\n\t\t\tp = last + 1\n\t\t}\n\t}\n\tvar index int\n\tif all {\n\t\tindex = stmt.addPart(p, \"UNION ALL \", \"\", query.Args(), \"\")\n\t} else {\n\t\tindex = stmt.addPart(p, \"UNION \", \"\", query.Args(), \"\")\n\t}\n\tpart := &stmt.parts[index]\n\t// Make sure subquery is not dialect-specific.\n\tif query.GetDialect() != DefaultDialect {\n\t\tquery.SetDialect(DefaultDialect)\n\t\tquery.Invalidate()\n\t}\n\tstmt.buffer.WriteString(query.String())\n\tpart.bufHigh = stmt.buffer.Len()\n\t// Close the subquery\n\tquery.Close()\n\n\treturn stmt\n}", "func StructuralPatToRegexpQuery(pattern string, shortcircuit bool) (zoektquery.Q, error) {\n\tsubstrings := matchHoleRegexp.Split(pattern, -1)\n\tvar children []zoektquery.Q\n\tvar pieces []string\n\tfor _, s := range substrings {\n\t\tpiece := regexp.QuoteMeta(s)\n\t\tonMatchWhitespace := lazyregexp.New(`[\\s]+`)\n\t\tpiece = onMatchWhitespace.ReplaceAllLiteralString(piece, `[\\s]+`)\n\t\tpieces = append(pieces, piece)\n\t}\n\n\tif len(pieces) == 0 {\n\t\treturn &zoektquery.Const{Value: true}, nil\n\t}\n\tvar rs string\n\tif shortcircuit {\n\t\t// As a shortcircuit, do not match across newlines of structural search pieces.\n\t\trs = \"(\" + strings.Join(pieces, \").*?(\") + \")\"\n\t} else {\n\t\trs = \"(\" + strings.Join(pieces, \")(.|\\\\s)*?(\") + \")\"\n\t}\n\tre, _ := syntax.Parse(rs, syntax.ClassNL|syntax.PerlX|syntax.UnicodeGroups)\n\tchildren = append(children, &zoektquery.Regexp{\n\t\tRegexp: re,\n\t\tCaseSensitive: true,\n\t\tContent: true,\n\t})\n\treturn &zoektquery.And{Children: children}, nil\n}", "func (q AndOrQuery) RegexpPatterns(field string) (values, negatedValues []string) {\n\tVisitField(q.Query, field, func(visitedValue string, negated bool, _ Annotation) {\n\t\tif negated {\n\t\t\tnegatedValues = append(negatedValues, visitedValue)\n\t\t} else {\n\t\t\tvalues = append(values, visitedValue)\n\t\t}\n\t})\n\treturn values, negatedValues\n}", "func TransformRegExp(pattern string) (string, error) {\n\n\tlog.Printf(\"runtime.Caller(1): %#+v\\n\", myutils.Slice(runtime.Caller(1))...)\n\tos.Exit(349857394)\n\n\t// if pattern == \"\" {\n\t// \treturn \"\", nil\n\t// }\n\n\tswitch pattern {\n\t// common cases that will leave as is\n\t// but frequently occurred in many\n\t// popular frameworks like react.js etc.\n\tcase _regexp_empty,\n\t\t_regexp_any_nc,\n\t\t_regexp_any_c,\n\t\t_regexp_anyplus_nc,\n\t\t_regexp_anyplus_c,\n\n\t\t_regexp_squote_nc,\n\t\t_regexp_squote_c,\n\t\t_regexp_dquote_nc,\n\t\t_regexp_dquote_c,\n\n\t\t_regexp_plus_nc,\n\t\t_regexp_plus_c,\n\n\t\t_regexp_urlenc_space_nc,\n\t\t_regexp_urlenc_space_c,\n\t\t_regexp_http_validation,\n\n\t\t_regexp_any_uppercase_nc,\n\t\t_regexp_any_uppercase_c,\n\n\t\t_regexp_is_ms_pref:\n\t\treturn pattern, nil\n\t}\n\n\t// TODO If without \\, if without (?=, (?!, then another shortcut\n\n\tparser := _RegExp_parser{\n\t\tstr: pattern,\n\t\tlength: len(pattern),\n\t\tgoRegexp: bytes.NewBuffer(make([]byte, 0, 3*len(pattern)/2)),\n\t}\n\tparser.read() // Pull in the first character\n\tparser.scan()\n\tvar err error\n\tif len(parser.errors) > 0 {\n\t\terr = parser.errors[0]\n\t}\n\tif parser.invalid {\n\t\tlog.Printf(\"Input: regexp=[%s]\\n\", pattern)\n\t\tlog.Printf(\"Output: regexp=[%s] err=[%s]\\n\", parser.goRegexp.String(), err)\n\t\treturn \"\", err\n\t}\n\n\t// Might not be re2 compatible, but is still a valid JavaScript RegExp\n\treturn parser.goRegexp.String(), err\n}", "func RegexpBuilder(spec FilterSpec) (Filter, error) {\n\tswitch strings.ToLower(spec.Type) {\n\tcase \"regexp\", \"regex\", \"re\":\n\tdefault:\n\t\treturn nil, nil\n\t}\n\n\tswitch len(spec.Args) {\n\tcase 0, 1:\n\t\treturn nil, errors.New(\"regular expression filter requires a subject and an expression\")\n\tcase 2:\n\t\tsubject, expression := spec.Args[0], spec.Args[1]\n\n\t\t// Force case-insensitive matching\n\t\tif !strings.HasPrefix(expression, \"(?i)\") {\n\t\t\texpression = \"(?i)\" + expression\n\t\t}\n\n\t\tre, err := regexp.Compile(expression)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"invalid expression \\\"%s\\\": %v\", expression, err)\n\t\t}\n\n\t\treturn regexpFilter{\n\t\t\tsubject: subject,\n\t\t\tre: re,\n\t\t}.Filter, nil\n\tdefault:\n\t\treturn nil, errors.New(\"regular expression filter has %d arguments when two are needed\")\n\t}\n}", "func compileRegex() {\n\tfor _, value := range filterObj.Signatures {\n\t\tr, _ := regexp.Compile(value.Regex)\n\t\tsignatureRegex = append(signatureRegex, r)\n\t}\n\tfor _, value := range filterObj.Shallows {\n\t\tr, _ := regexp.Compile(value.Regex)\n\t\tshallowRegex = append(shallowRegex, r)\n\t}\n}", "func Union(queries ...Query) VariadicQuery {\n\treturn VariadicQuery{\n\t\tOperator: QueryUnion,\n\t\tQueries: queries,\n\t}\n}", "func Union(subQuery ...SQLProvider) *Query {\n\tq := newQuery()\n\tq.unions = append(q.unions, subQuery...)\n\tq.action = action_union\n\treturn q\n}", "func NewRegexpSet(patterns []string) (retVal *RegexpSet, err error) {\n\tfor _, pattern := range patterns {\n\t\t_, err := regexp.Compile(pattern)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Invalid regular pattern: '%v'.\\n\", pattern)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &RegexpSet{patterns}, nil\n}", "func Or(patts ...Pattern) Pattern {\n\tif len(patts) <= 0 {\n\t\treturn &EmptyNode{}\n\t}\n\n\t// optimization: make or right associative\n\tacc := patts[len(patts)-1]\n\tfor i := len(patts) - 2; i >= 0; i-- {\n\t\tacc = &AltNode{\n\t\t\tLeft: patts[i],\n\t\t\tRight: acc,\n\t\t}\n\t}\n\n\treturn acc\n}", "func (list List_str) Union(lists ...List_str) List_str {\n\n vsf := make(List_str, 0)\n \n //append all lists into list\n for _, lst := range lists {\n vsf = list.Append(lst)\n }\n \n //return uniq (non-duplicate)\n return vsf.Uniq()\n}", "func Or(parsers ...Parser) Parser {\n\treturn &orParser{parsers}\n}", "func ruleToRegexp(text string) (string, error) {\n\tif text == \"\" {\n\t\treturn \".*\", nil\n\t}\n\n\t// already regexp?\n\tlength := len(text)\n\tif length >= 2 && text[:1] == \"/\" && text[length-1:] == \"/\" {\n\t\t// filter is a regular expression\n\t\treturn text[1 : length-1], nil\n\t}\n\n\trule := escapeSpecialRegxp.ReplaceAllStringFunc(text, func(src string) string {\n\t\treturn fmt.Sprintf(`\\%v`, src)\n\t})\n\trule = strings.Replace(rule, \"^\", `(?:[^\\\\w\\\\d_\\\\\\-.%]|$)`, -1)\n\trule = strings.Replace(rule, \"*\", \".*\", -1)\n\n\tlength = len(rule)\n\tif rule[length-1] == '|' {\n\t\trule = rule[:length-1] + \"$\"\n\t}\n\n\tif rule[:2] == \"||\" {\n\t\tif len(rule) > 2 {\n\t\t\trule = `^(?:[^:/?#]+:)?(?://(?:[^/?#]*\\\\.)?)?` + rule[2:]\n\t\t}\n\t} else if rule[0] == '|' {\n\t\trule = \"^\" + rule[1:]\n\t}\n\n\trule = re.MustCompile(`(\\|)[^$]`).ReplaceAllString(rule, `\\|`)\n\n\treturn rule, nil\n}", "func (geom Geometry) Union(other Geometry) Geometry {\n\tnewGeom := C.OGR_G_Union(geom.cval, other.cval)\n\treturn Geometry{newGeom}\n}", "func RegexpParse(content, pattern string) ([]string, error) {\n\tre, err := pool.Compile(pattern)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"re:[%s] error:%+v\", pattern, err)\n\t}\n\tvar ret []string\n\tres := re.FindAllStringSubmatch(content, -1)\n\tfor i := range res {\n\t\tswitch {\n\t\tcase len(res[i]) == 1:\n\t\t\tret = append(ret, res[i][0])\n\t\tcase len(res[i]) > 1:\n\t\t\tret = append(ret, res[i][1:]...)\n\t\t}\n\t}\n\treturn ret, nil\n}", "func Regexp(expr *regexp.Regexp) Pattern {\n\treturn regexpMatch{expr}\n}", "func (set Set) Union(ctx context.Context, keys ...string) ([]string, error) {\n\treq := newRequestSize(2+len(keys), \"\\r\\n$6\\r\\nSUNION\\r\\n$\")\n\treq.addStringAndStrings(set.name, keys)\n\treturn set.c.cmdStrings(ctx, req)\n}", "func NewMultiOperationMatch(strs ...string) string {\n\treturn \"^\" + strings.Join(strs, \"|^\")\n}", "func getRegexp(env *lisp.LEnv, v *lisp.LVal) (re *regexp.Regexp, lerr *lisp.LVal) {\n\tif v.Type == lisp.LString {\n\t\tre, err := regexp.Compile(v.Str)\n\t\tif err != nil {\n\t\t\treturn nil, invalidPatternError(env, err)\n\t\t}\n\t\treturn re, nil\n\t}\n\tif v.Type != lisp.LNative {\n\t\treturn nil, env.Errorf(\"argument is not a regexp: %v\", v.Type)\n\t}\n\tre, ok := v.Native.(*regexp.Regexp)\n\tif !ok {\n\t\treturn nil, env.Errorf(\"argument is not a regexp: %v\", v)\n\t}\n\treturn re, nil\n}", "func (r *Rights) Union(b ...*Rights) *Rights {\n\treturn makeRightsSet(append(b, r)...).rights()\n}", "func Union(s1, s2 string) string {\n\tvar intersect strings.Builder\n\tset := make(map[rune]bool)\n\tfor _, char := range s1 {\n\t\tif _, ok := set[char]; !ok {\n\t\t\tset[char] = true\n\t\t\tintersect.WriteRune(char)\n\t\t}\n\t}\n\tfor _, char := range s2 {\n\t\tif _, ok := set[char]; !ok {\n\t\t\tset[char] = true\n\t\t\tintersect.WriteRune(char)\n\t\t}\n\t}\n\treturn intersect.String()\n}", "func wildCardToRegexp(pattern string) string {\n\tvar result strings.Builder\n\tfor i, literal := range strings.Split(pattern, \"*\") {\n\n\t\t// Replace * with .*\n\t\tif i > 0 {\n\t\t\tresult.WriteString(\".*\")\n\t\t}\n\n\t\t// Quote any regular expression meta characters in the\n\t\t// literal text.\n\t\tresult.WriteString(regexp.QuoteMeta(literal))\n\t}\n\treturn result.String()\n}", "func (u *union) Derivative(r rune) Regex {\n\treturn NewUnion(u.l.Derivative(r), u.r.Derivative(r))\n}", "func (oss *OrderedStringSet) Union(setB *OrderedStringSet) *OrderedStringSet {\n\tunion := NewOrderedStringSet(oss.Elements()...)\n\tif setB == nil {\n\t\treturn union\n\t}\n\n\tfor _, m := range setB.Elements() {\n\t\tunion.Add(m)\n\t}\n\n\treturn union\n}", "func unionMerge(obj reflect.Value, src reflect.Value, name string) reflect.Value {\n\tout := reflect.New(obj.Type()).Elem()\n\n\tmergeField := func(i int) {\n\t\tstructField := obj.Type().Field(i)\n\t\tfieldName := fmt.Sprintf(\"%v.%v\", name, structField.Name)\n\t\tx := merge(obj.Field(i), src.Field(i), fieldName)\n\t\tout.Field(i).Set(x)\n\t}\n\n\t// Iterate through all the fields of the struct once, identifying union members and merging\n\t// the non-union members.\n\tobjHasMember := -1\n\tsrcHasMember := -1\n\tfor i := 0; i < src.NumField(); i++ {\n\t\tif _, ok := obj.Type().Field(i).Tag.Lookup(\"union\"); ok {\n\t\t\t// Union member, remember it for later.\n\t\t\tif !obj.Field(i).IsZero() {\n\t\t\t\tobjHasMember = i\n\t\t\t}\n\t\t\tif !src.Field(i).IsZero() {\n\t\t\t\tsrcHasMember = i\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// Non-union member, merge it normally.\n\t\tmergeField(i)\n\t}\n\tif objHasMember > -1 {\n\t\t// When obj has a union member, we can only merge that union member.\n\t\tmergeField(objHasMember)\n\t} else if srcHasMember > -1 {\n\t\t// Otherwise we merge whatever the src has defined.\n\t\tmergeField(srcHasMember)\n\t}\n\treturn out.Convert(obj.Type())\n}", "func regexpFilter(regexps []string, keep bool) (func(string) bool, error) {\n\tif len(regexps) == 0 {\n\t\treturn func(name string) bool {\n\t\t\treturn false\n\t\t}, nil\n\t}\n\tfilterNames := []*regexp.Regexp{}\n\tfor _, n := range regexps {\n\t\tre, err := regexp.Compile(n)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"filter pattern: %s\", n)\n\t\t}\n\t\tfilterNames = append(filterNames, re)\n\t}\n\n\treturn func(name string) bool {\n\t\tfor _, r := range filterNames {\n\t\t\tif r.MatchString(name) {\n\t\t\t\treturn !keep\n\t\t\t}\n\t\t}\n\t\treturn keep\n\t}, nil\n}", "func Or(m gomock.Matcher, ms ...gomock.Matcher) gomock.Matcher {\n\tmcs := append([]gomock.Matcher{m}, ms...)\n\treturn orMatcher{mcs}\n}", "func (s String) Union(strings ...String) (union String) {\n\tunion = s.Copy()\n\tfor _, set := range strings {\n\t\tfor key := range set {\n\t\t\tunion[key] = yes\n\t\t}\n\t}\n\treturn union\n}", "func Regex(pattern, options string) Val {\n\tregex := primitive.Regex{Pattern: pattern, Options: options}\n\treturn Val{t: bsontype.Regex, primitive: regex}\n}", "func (g *Grammar) UnionSingleTerms(name string, terms ...Term) {\n\trule := g.Lookup(name)\n\tfor _, t := range terms {\n\t\trule.Productions = append(rule.Productions, Production{t})\n\t}\n\tg.rules[name] = rule\n}", "func QuoteRegex(operand string) string { return regexp.QuoteMeta(operand) }", "func stripBare(re *syntax.Regexp) (retPart part) {\n\tswitch re.Op {\n\tcase syntax.OpNoMatch: // matches no strings\n\t\t// TODO(quis): Introduce a part type for this?\n\t\treturn word(\"__no_matches\")\n\tcase syntax.OpEmptyMatch: // matches empty string\n\t\treturn word(\"\")\n\tcase syntax.OpLiteral: // matches Runes sequence\n\t\treturn word(re.Rune)\n\tcase syntax.OpCharClass: // matches Runes interpreted as range pair list\n\t\trs := expandRanges(re.Rune)\n\t\tif len(rs) > 5 {\n\t\t\treturn separator{}\n\t\t}\n\t\tvar ret orPart\n\t\tfor _, r := range rs {\n\t\t\tret = append(ret, word(fmt.Sprintf(\"%c\", r)))\n\t\t}\n\t\treturn ret\n\tcase syntax.OpAnyCharNotNL: // matches any character except newline\n\t\treturn separator{}\n\tcase syntax.OpAnyChar: // matches any character\n\t\treturn separator{}\n\tcase syntax.OpBeginLine: // matches empty string at beginning of line\n\t\treturn separator{}\n\tcase syntax.OpEndLine: // matches empty string at end of line\n\t\treturn separator{}\n\tcase syntax.OpBeginText: // matches empty string at beginning of text\n\t\t// TODO(quis): Introduce a part type for this so we can generate SQL expressions with LIKEs that can be anchored at the start/end of a field.\n\t\treturn separator{}\n\tcase syntax.OpEndText: // matches empty string at end of text\n\t\treturn separator{}\n\tcase syntax.OpWordBoundary: // matches word boundary `\\b`\n\t\treturn word(\"\")\n\tcase syntax.OpNoWordBoundary: // matches word non-boundary `\\B`\n\t\treturn word(\"\")\n\tcase syntax.OpCapture: // capturing subexpression with index Cap, optional name Name\n\t\treturn stripBare(re.Sub[0])\n\tcase syntax.OpStar: // matches Sub[0] zero or more times\n\t\treturn separator{}\n\tcase syntax.OpPlus: // matches Sub[0] one or more times\n\t\treturn concatenation{stripBare(re.Sub[0]), separator{}}\n\tcase syntax.OpQuest: // matches Sub[0] zero or one times\n\t\treturn orPart{stripBare(re.Sub[0]), word(\"\")}\n\tcase syntax.OpRepeat: // matches Sub[0] at least Min times, at most Max (Max == -1 is no limit)\n\t\ts := stripBare(re.Sub[0])\n\t\t// If the difference is more than 5 we're generating too many different combinations. Just treat it as a separator rather than generating all possibilities.\n\t\tif re.Max == -1 || re.Max-re.Min > 5 {\n\t\t\tvar ret concatenation\n\t\t\tfor i := 0; re.Min > i; i++ {\n\t\t\t\tret = append(ret, s)\n\t\t\t}\n\t\t\tif re.Min != re.Max {\n\t\t\t\tret = append(ret, separator{})\n\t\t\t}\n\t\t\treturn ret\n\t\t} else {\n\t\t\tvar ret orPart\n\t\t\tfor j := re.Min; re.Max >= j; j++ {\n\t\t\t\tvar c concatenation\n\t\t\t\tfor i := 0; j > i; i++ {\n\t\t\t\t\tc = append(c, s)\n\t\t\t\t}\n\t\t\t\tret = append(ret, c)\n\t\t\t}\n\t\t\treturn ret\n\t\t}\n\tcase syntax.OpConcat: // matches concatenation of Subs\n\t\tvar ret concatenation\n\t\tfor _, s := range re.Sub {\n\t\t\tret = append(ret, stripBare(s))\n\t\t}\n\t\treturn ret\n\tcase syntax.OpAlternate: // matches alternation of Subs\n\t\tvar ret orPart\n\t\tfor _, s := range re.Sub {\n\t\t\tret = append(ret, stripBare(s))\n\t\t}\n\t\treturn ret\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown opcode %d\", re.Op))\n\t}\n}", "func r(pattern string) *regexp.Regexp { return regexp.MustCompile(pattern) }", "func (v *VerbalExpression) Or(ve *VerbalExpression) *VerbalExpression {\n\tv.parts = append(v.parts, ve.Regex().String()+\"|\")\n\treturn v\n}", "func RegexpFilter(pattern string) Filter {\n\tp := regexp.MustCompile(pattern)\n\treturn regexpFilter{p}\n}", "func (p *planner) UnionClause(n *parser.UnionClause, desiredTypes []parser.Datum, autoCommit bool) (planNode, error) {\n\tvar emitAll = false\n\tvar emit unionNodeEmit\n\tswitch n.Type {\n\tcase parser.UnionOp:\n\t\tif n.All {\n\t\t\temitAll = true\n\t\t} else {\n\t\t\temit = make(unionNodeEmitDistinct)\n\t\t}\n\tcase parser.IntersectOp:\n\t\tif n.All {\n\t\t\temit = make(intersectNodeEmitAll)\n\t\t} else {\n\t\t\temit = make(intersectNodeEmitDistinct)\n\t\t}\n\tcase parser.ExceptOp:\n\t\tif n.All {\n\t\t\temit = make(exceptNodeEmitAll)\n\t\t} else {\n\t\t\temit = make(exceptNodeEmitDistinct)\n\t\t}\n\tdefault:\n\t\treturn nil, errors.Errorf(\"%v is not supported\", n.Type)\n\t}\n\n\tleft, err := p.newPlan(n.Left, desiredTypes, autoCommit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tright, err := p.newPlan(n.Right, desiredTypes, autoCommit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tleftColumns := left.Columns()\n\trightColumns := right.Columns()\n\tif len(leftColumns) != len(rightColumns) {\n\t\treturn nil, fmt.Errorf(\"each %v query must have the same number of columns: %d vs %d\", n.Type, len(left.Columns()), len(right.Columns()))\n\t}\n\tfor i := 0; i < len(leftColumns); i++ {\n\t\tl := leftColumns[i]\n\t\tr := rightColumns[i]\n\t\t// TODO(dan): This currently checks whether the types are exactly the same,\n\t\t// but Postgres is more lenient:\n\t\t// http://www.postgresql.org/docs/9.5/static/typeconv-union-case.html.\n\t\tif !l.Typ.TypeEqual(r.Typ) {\n\t\t\treturn nil, fmt.Errorf(\"%v types %s and %s cannot be matched\", n.Type, l.Typ.Type(), r.Typ.Type())\n\t\t}\n\t\tif l.hidden != r.hidden {\n\t\t\treturn nil, fmt.Errorf(\"%v types cannot be matched\", n.Type)\n\t\t}\n\t}\n\n\tnode := &unionNode{\n\t\tright: right,\n\t\tleft: left,\n\t\trightDone: false,\n\t\tleftDone: false,\n\t\temitAll: emitAll,\n\t\temit: emit,\n\t\tscratch: make([]byte, 0),\n\t}\n\treturn node, nil\n}", "func Union[T comparable](a, b Set[T]) Set[T] {\n\tresult := a.New()\n\tresult.Add(a.Elements()...)\n\tresult.Add(b.Elements()...)\n\treturn result\n}", "func (r Report) FilterRegexp(pattern ...string) (result Report) {\n\tif len(pattern) == 0 {\n\t\treturn r\n\t}\n\n\tregexps := make([]*regexp.Regexp, len(pattern))\n\tfor i := range pattern {\n\t\tregexps[i] = regexp.MustCompile(pattern[i])\n\t}\n\n\treturn r.filter(func(filterPath *ytbx.Path) bool {\n\t\tfor _, regexp := range regexps {\n\t\t\tif filterPath != nil && regexp.MatchString(filterPath.String()) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t})\n}", "func (p *reParser) concat() *reSyntax {\n\t// Scan down to find pseudo-operator || or ((.\n\ti := len(p.stack)\n\tfor i > 0 && p.stack[i-1].op < opPseudo {\n\t\ti--\n\t}\n\tsubs := p.stack[i:]\n\tp.stack = p.stack[:i]\n\n\t// Empty concatenation is special case.\n\tif len(subs) == 0 {\n\t\treturn p.push(&reSyntax{op: opEmpty})\n\t}\n\n\treturn p.push(p.collapse(opConcat, subs))\n}", "func expression(res ...*regexp.Regexp) *regexp.Regexp {\n\tvar s string\n\tfor _, re := range res {\n\t\ts += re.String()\n\t}\n\n\treturn match(s)\n}", "func expression(res ...*regexp.Regexp) *regexp.Regexp {\n\tvar s string\n\tfor _, re := range res {\n\t\ts += re.String()\n\t}\n\n\treturn match(s)\n}", "func expression(res ...*regexp.Regexp) *regexp.Regexp {\n\tvar s string\n\tfor _, re := range res {\n\t\ts += re.String()\n\t}\n\n\treturn match(s)\n}", "func Union(s, t Interface) (u Interface) {\n\tu = s.Copy()\n\tfor _, x := range t.Members() {\n\t\tu.Add(x)\n\t}\n\treturn\n}", "func RegexFromGlobWithOptions(glob string, config Options) string {\n\treStr := \"\"\n\n\tdelimiter := '/'\n\tif config.Delimiter != 0 {\n\t\tdelimiter = config.Delimiter\n\t}\n\n\tdelimiterOutsideClass, delimiterInsideClass := escapeDelimiter(delimiter)\n\n\tinGroup := false\n\n\tglobLen := len(glob)\n\n\tfor i := 0; i < globLen; i++ {\n\t\tc := glob[i]\n\n\t\tswitch c {\n\t\tcase '/', '$', '^', '+', '.', '(', ')', '=', '!', '|':\n\t\t\treStr += \"\\\\\" + string(c)\n\n\t\tcase '?':\n\t\t\tif config.Extended {\n\t\t\t\treStr += \".\"\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treStr += \"\\\\\" + string(c)\n\n\t\tcase '[', ']':\n\t\t\tif config.Extended {\n\t\t\t\treStr += string(c)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treStr += \"\\\\\" + string(c)\n\n\t\tcase '{':\n\t\t\tif config.Extended {\n\t\t\t\tinGroup = true\n\t\t\t\treStr += \"(\"\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treStr += \"\\\\\" + string(c)\n\n\t\tcase '}':\n\t\t\tif config.Extended {\n\t\t\t\tinGroup = false\n\t\t\t\treStr += \")\"\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treStr += \"\\\\\" + string(c)\n\n\t\tcase ',':\n\t\t\tif inGroup {\n\t\t\t\treStr += \"|\"\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treStr += \"\\\\\" + string(c)\n\n\t\tcase '*':\n\t\t\t// Move over all consecutive \"*\"'s.\n\t\t\t// Also store the previous and next characters\n\t\t\tvar nextChar, prevChar rune\n\t\t\tif i > 0 {\n\t\t\t\tprevChar = rune(glob[i-1])\n\t\t\t}\n\t\t\tstarCount := 1\n\t\t\tfor i < globLen-1 && glob[i+1] == '*' {\n\t\t\t\tstarCount++\n\t\t\t\ti++\n\t\t\t}\n\n\t\t\tif i < globLen-1 {\n\t\t\t\tnextChar = rune(glob[i+1])\n\t\t\t}\n\n\t\t\tif !config.GlobStar {\n\t\t\t\t// globstar is disabled, so treat any number of \"*\" as one\n\t\t\t\treStr += \".*\"\n\t\t\t} else {\n\t\t\t\t// globstar is enabled, so determine if this is a globstar segment\n\t\t\t\tisGlobstar := starCount > 1 && // multiple \"*\"'s\n\t\t\t\t\t(prevChar == delimiter || prevChar == 0) && // from the start of the segment\n\t\t\t\t\t(nextChar == delimiter || nextChar == 0) // to the end of the segment\n\n\t\t\t\tif isGlobstar {\n\t\t\t\t\t// it's a globstar, so match zero or more path segments\n\t\t\t\t\treStr += \"(?:(?:[^\" + delimiterInsideClass + \"]*(?:\" + delimiterOutsideClass + \"|$))*)\"\n\t\t\t\t\ti++ // move over the delimiter\n\t\t\t\t} else {\n\t\t\t\t\t// it's not a globstar, so only match one path segment\n\t\t\t\t\treStr += \"(?:[^\" + delimiterInsideClass + \"]*)\"\n\t\t\t\t}\n\t\t\t}\n\n\t\tdefault:\n\t\t\treStr += string(c)\n\t\t}\n\t}\n\n\treturn \"^\" + reStr + \"$\"\n}", "func (o HttpHeaderMatchOutput) RegexMatch() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v HttpHeaderMatch) *string { return v.RegexMatch }).(pulumi.StringPtrOutput)\n}", "func ArrayInStringToRegularExpression(arrayString string) string {\n\tif arrayString == \"x\" || len(arrayString) == 0 {\n\t\treturn allThingsRegex\n\t}\n\tarray := strings.Split(arrayString, \",\")\n\tif len(array) == 1 {\n\t\treturn fmt.Sprint(\"[0-9,]*\", array[0], \"[0-9,]*\")\n\t}\n\treturn fmt.Sprint(\"[0-9,]*(\", strings.Join(array, \"|\"), \")[0-9,]*\")\n}", "func FilterRegex(regex string, metrics []string) ([]string, error) {\n\tr, err := regexp.Compile(regex)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := make([]string, 0)\n\n\tfor _, v := range metrics {\n\t\tif r.MatchString(v) {\n\t\t\tresult = append(result, v)\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func CompileERE(pattern string) (*regexp.Regexp, error) { return regexp.CompilePOSIX(pattern) }", "func NewRegexpMatcher(terms ...*regexp.Regexp) (RegexpMatcher, error) {\n\tif len(terms) == 0 {\n\t\treturn matchNothingRegexpMatcher, nil\n\t}\n\n\t// combine expressions into one using OR, i.e.\n\t// [RE1, RE2, ..., REn] -> (RE1)|(RE2)|...|(REn)\n\tbuf := bytes.NewBuffer([]byte(`(\\A`))\n\tsep := []byte(`\\z)|(\\A`)\n\n\tfor _, term := range terms {\n\t\treBytes := []byte(term.String())\n\t\t// strip leading beginning-of-line matchers, as they are already included into the combined expression\n\t\treBytes = bytes.TrimPrefix(bytes.TrimLeft(reBytes, \"^\"), []byte(`\\A`))\n\t\t// strip trailing end-of-line matchers, as they are already included into the combined expression\n\t\treBytes = bytes.TrimSuffix(bytes.TrimRight(reBytes, \"$\"), []byte(`\\z`))\n\n\t\tbuf.Write(reBytes)\n\t\tbuf.Write(sep)\n\t}\n\tbuf.Truncate(buf.Len() - len(sep)) // trim trailing separator\n\tbuf.WriteString(`\\z)`)\n\n\tcombined := buf.String()\n\n\tre, err := regexp.Compile(combined)\n\tif err != nil {\n\t\treturn matchNothingRegexpMatcher, fmt.Errorf(\"malformed regexp %q: %s\", combined, err)\n\t}\n\n\treturn RegexpMatcher{re}, nil\n}", "func Regexp(pattern string) (*regexp.Regexp, error) {\n\treturn pool.Compile(pattern)\n}", "func StringSlicesUnion(one, two []string) []string {\n\tvar union []string\n\tunion = append(union, one...)\n\tunion = append(union, two...)\n\treturn OnlyUnique(union)\n}", "func NewConcat(l, r Regex) Regex {\n\tswitch l.(type) {\n\tcase *empty:\n\t\treturn NewEmpty()\n\tcase *epsilon:\n\t\treturn r\n\tdefault:\n\t\treturn &concat{\n\t\t\tl: l,\n\t\t\tr: r,\n\t\t}\n\t}\n}", "func (p *Parser) regex() (RegEx, error) {\n\tt, err := p.term()\n\tif err != nil {\n\t\treturn nil, errors.New(\"p.regex() expected a term\\n\" + err.Error())\n\t}\n\n\tif p.peek() == '|' {\n\t\t_ = p.eat('|')\n\t\tr, err := p.regex()\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"p.regex() expected a regex\\n\" + err.Error())\n\t\t}\n\t\treturn NewChoose(t, r), nil\n\t} else {\n\t\treturn t, nil\n\t}\n}", "func RegexpFromQuery(q string) (*regexp.Regexp, error) {\n\tplan, err := query.Pipeline(query.Init(q, query.SearchTypeRegex))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(plan) != 1 {\n\t\treturn nil, errors.New(\"compute endpoint only supports one search pattern currently ('and' or 'or' operators are not supported yet)\")\n\t}\n\tswitch node := plan[0].Pattern.(type) {\n\tcase query.Operator:\n\t\tif len(node.Operands) == 1 {\n\t\t\tif pattern, ok := node.Operands[0].(query.Pattern); ok && !pattern.Negated {\n\t\t\t\trp, err := regexp.Compile(pattern.Value)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.Wrap(err, \"regular expression is not valid for compute endpoint\")\n\t\t\t\t}\n\t\t\t\treturn rp, nil\n\t\t\t}\n\t\t}\n\t\treturn nil, errors.New(\"compute endpoint only supports one search pattern currently ('and' or 'or' operators are not supported yet)\")\n\tcase query.Pattern:\n\t\tif !node.Negated {\n\t\t\treturn regexp.Compile(node.Value)\n\t\t}\n\t}\n\t// unreachable\n\treturn nil, nil\n}", "func NewRegexPatternSet(ctx *pulumi.Context,\n\tname string, args *RegexPatternSetArgs, opts ...pulumi.ResourceOption) (*RegexPatternSet, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.RegularExpressionList == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'RegularExpressionList'\")\n\t}\n\tif args.Scope == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Scope'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource RegexPatternSet\n\terr := ctx.RegisterResource(\"aws-native:wafv2:RegexPatternSet\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func CompileRegexp(str string) (regexp *Regexp, error string) {\n\tregexp = new(Regexp);\n\tregexp.expr = str;\n\tregexp.inst = make([]instr, 0, 20);\n\terror = regexp.doParse();\n\treturn;\n}", "func TestConverterUnion(t *testing.T) {\n\t// values for union component types\n\tvvTrue := vdl.BoolValue(nil, true)\n\tvv123 := vdl.IntValue(vdl.Int64Type, 123)\n\tvvAbc := vdl.StringValue(nil, \"Abc\")\n\tvvStruct123 := vdl.ZeroValue(vdl.StructInt64TypeN)\n\tvvStruct123.StructField(0).Assign(vv123)\n\trvTrue := bool(true)\n\trv123 := int64(123)\n\trvAbc := string(\"Abc\")\n\trvStruct123 := vdl.NStructInt64{123}\n\t// values for union{A bool;B string;C struct}\n\tvvTrueABC := vdl.UnionValue(vdl.UnionABCTypeN, 0, vvTrue)\n\tvvAbcABC := vdl.UnionValue(vdl.UnionABCTypeN, 1, vvAbc)\n\tvvStruct123ABC := vdl.UnionValue(vdl.UnionABCTypeN, 2, vvStruct123)\n\trvTrueABC := vdl.NUnionABCA{rvTrue}\n\trvAbcABC := vdl.NUnionABCB{rvAbc}\n\trvStruct123ABC := vdl.NUnionABCC{rvStruct123}\n\trvTrueABCi := vdl.NUnionABC(rvTrueABC)\n\trvAbcABCi := vdl.NUnionABC(rvAbcABC)\n\trvStruct123ABCi := vdl.NUnionABC(rvStruct123ABC)\n\t// values for union{B string;C struct;D int64}\n\tvvAbcBCD := vdl.UnionValue(vdl.UnionBCDTypeN, 0, vvAbc)\n\tvvStruct123BCD := vdl.UnionValue(vdl.UnionBCDTypeN, 1, vvStruct123)\n\tvv123BCD := vdl.UnionValue(vdl.UnionBCDTypeN, 2, vv123)\n\trvAbcBCD := vdl.NUnionBCDB{rvAbc}\n\trvStruct123BCD := vdl.NUnionBCDC{rvStruct123}\n\trv123BCD := vdl.NUnionBCDD{rv123}\n\trvAbcBCDi := vdl.NUnionBCD(rvAbcBCD)\n\trvStruct123BCDi := vdl.NUnionBCD(rvStruct123BCD)\n\trv123BCDi := vdl.NUnionBCD(rv123BCD)\n\t// values for union{X string;Y struct}, which has no Go equivalent.\n\tvvAbcXY := vdl.UnionValue(vdl.UnionXYTypeN, 0, vvAbc)\n\tvvStruct123XY := vdl.UnionValue(vdl.UnionXYTypeN, 1, vvStruct123)\n\n\ttests := []struct {\n\t\tvvWant *vdl.Value\n\t\trvWant interface{}\n\t\tvvSrc *vdl.Value\n\t\trvSrc interface{}\n\t}{\n\t\t// Convert source and target same union.\n\t\t{vvTrueABC, rvTrueABC, vvTrueABC, rvTrueABC},\n\t\t{vv123BCD, rv123BCD, vv123BCD, rv123BCD},\n\t\t{vvAbcABC, rvAbcABC, vvAbcABC, rvAbcABC},\n\t\t{vvAbcBCD, rvAbcBCD, vvAbcBCD, rvAbcBCD},\n\t\t{vvStruct123ABC, rvStruct123ABC, vvStruct123ABC, rvStruct123ABC},\n\t\t{vvStruct123BCD, rvStruct123BCD, vvStruct123BCD, rvStruct123BCD},\n\t\t// Same thing, but with pointers to the interface type.\n\t\t{vvTrueABC, &rvTrueABCi, vvTrueABC, &rvTrueABCi},\n\t\t{vv123BCD, &rv123BCDi, vv123BCD, &rv123BCD},\n\t\t{vvAbcABC, &rvAbcABCi, vvAbcABC, &rvAbcABC},\n\t\t{vvAbcBCD, &rvAbcBCDi, vvAbcBCD, &rvAbcBCD},\n\t\t{vvStruct123ABC, &rvStruct123ABCi, vvStruct123ABC, &rvStruct123ABCi},\n\t\t{vvStruct123BCD, &rvStruct123BCDi, vvStruct123BCD, &rvStruct123BCDi},\n\n\t\t// Convert source and target different union.\n\t\t{vvAbcABC, rvAbcABC, vvAbcBCD, rvAbcBCD},\n\t\t{vvAbcBCD, rvAbcBCD, vvAbcABC, rvAbcABC},\n\t\t{vvStruct123ABC, rvStruct123ABC, vvStruct123BCD, rvStruct123BCD},\n\t\t{vvStruct123BCD, rvStruct123BCD, vvStruct123ABC, rvStruct123ABC},\n\t\t// Same thing, but with pointers to the interface type.\n\t\t{vvAbcABC, &rvAbcABCi, vvAbcBCD, &rvAbcBCDi},\n\t\t{vvAbcBCD, &rvAbcBCDi, vvAbcABC, &rvAbcABCi},\n\t\t{vvStruct123ABC, &rvStruct123ABCi, vvStruct123BCD, &rvStruct123BCDi},\n\t\t{vvStruct123BCD, &rvStruct123BCDi, vvStruct123ABC, &rvStruct123ABCi},\n\n\t\t// Test unions that have no Go equivalent.\n\t\t{vvAbcXY, nil, vvAbcXY, nil},\n\t\t{vvStruct123XY, nil, vvStruct123XY, nil},\n\t}\n\tfor _, test := range tests {\n\t\ttestConverterWantSrc(t,\n\t\t\tvvrv{vvSlice(test.vvWant), rvSlice(test.rvWant)},\n\t\t\tvvrv{vvSlice(test.vvSrc), rvSlice(test.rvSrc)})\n\t}\n}", "func generatePatternForRegexp(pattern string) (string, error) {\n\tpattern = patternRegexp.ReplaceAllStringFunc(pattern, func(subMatch string) string {\n\t\t// The sub match string conforms the parameter pattern: `{parameter-name:regexp-expression}`.\n\t\tfoos := strings.SplitN(subMatch, \":\", 2)\n\t\tif len(foos) < 2 {\n\t\t\treturn `([^/]+)`\n\t\t} else {\n\t\t\treturn \"(\" + foos[1][0:len(foos[1])-1] + \")\"\n\t\t}\n\t})\n\t// Checking for abnormal patterns.\n\t_, err := regexp.Compile(pattern)\n\treturn pattern, err\n}", "func GobwasMatcherFromPatterns(patterns []string) ([]Matcher, error) {\n\tret := make([]Matcher, 0, len(patterns))\n\tfor _, p := range patterns {\n\t\tmatcher, err := glob.Compile(p)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"can not instantiate matcher\")\n\t\t}\n\t\tret = append(ret, matcher)\n\t}\n\treturn ret, nil\n}", "func Union(list1 []Node, list2 []Node) []Node {\n\n\tidSet := map[string]Node{}\n\n\tfor _, n := range list1 {\n\t\tidSet[n.String()] = n\n\t}\n\tfor _, n := range list2 {\n\t\tif _, ok := idSet[n.String()]; !ok {\n\t\t\tidSet[n.String()] = n\n\t\t}\n\t}\n\n\tres := make([]Node, len(idSet))\n\ti := 0\n\tfor _, n := range idSet {\n\t\tres[i] = n\n\t\ti++\n\t}\n\n\treturn res\n}", "func (o HttpQueryParameterMatchOutput) RegexMatch() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v HttpQueryParameterMatch) *string { return v.RegexMatch }).(pulumi.StringPtrOutput)\n}", "func MatchOneOf(text string, patterns ...string) []string {\n\tvar (\n\t\tre *regexp.Regexp\n\t\tvalue []string\n\t)\n\tfor _, pattern := range patterns {\n\t\t// (?flags): set flags within current group; non-capturing\n\t\t// s: let . match \\n (default false)\n\t\t// https://github.com/google/re2/wiki/Syntax\n\t\tre = regexp.MustCompile(pattern)\n\t\tvalue = re.FindStringSubmatch(text)\n\t\tif len(value) > 0 {\n\t\t\treturn value\n\t\t}\n\t}\n\treturn nil\n}", "func TestUnionSubTypes(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tinCtxEntry *yang.Entry\n\t\t// inNoContext means to only pass in the type of the context\n\t\t// entry as a parameter to goUnionSubTypes without the context entry.\n\t\tinNoContext bool\n\t\twant []string\n\t\twantMtypes map[int]*ygen.MappedType\n\t\twantErr bool\n\t}{{\n\t\tname: \"union of strings\",\n\t\tinCtxEntry: &yang.Entry{\n\t\t\tName: \"union-leaf\",\n\t\t\tKind: yang.LeafEntry,\n\t\t\tType: &yang.YangType{\n\t\t\t\tKind: yang.Yunion,\n\t\t\t\tType: []*yang.YangType{\n\t\t\t\t\t{Kind: yang.Ystring},\n\t\t\t\t\t{Kind: yang.Ystring},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []string{\"string\"},\n\t\twantMtypes: map[int]*ygen.MappedType{\n\t\t\t0: {\n\t\t\t\tNativeType: \"string\",\n\t\t\t\tUnionTypes: nil,\n\t\t\t\tIsEnumeratedValue: false,\n\t\t\t\tZeroValue: goZeroValues[\"string\"],\n\t\t\t\tDefaultValue: nil,\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"union of int8, string\",\n\t\tinCtxEntry: &yang.Entry{\n\t\t\tName: \"union-leaf\",\n\t\t\tKind: yang.LeafEntry,\n\t\t\tType: &yang.YangType{\n\t\t\t\tKind: yang.Yunion,\n\t\t\t\tType: []*yang.YangType{\n\t\t\t\t\t{Kind: yang.Yint8},\n\t\t\t\t\t{Kind: yang.Ystring},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []string{\"int8\", \"string\"},\n\t\twantMtypes: map[int]*ygen.MappedType{\n\t\t\t0: {\n\t\t\t\tNativeType: \"int8\",\n\t\t\t\tUnionTypes: nil,\n\t\t\t\tIsEnumeratedValue: false,\n\t\t\t\tZeroValue: goZeroValues[\"int8\"],\n\t\t\t\tDefaultValue: nil,\n\t\t\t},\n\t\t\t1: {\n\t\t\t\tNativeType: \"string\",\n\t\t\t\tUnionTypes: nil,\n\t\t\t\tIsEnumeratedValue: false,\n\t\t\t\tZeroValue: goZeroValues[\"string\"],\n\t\t\t\tDefaultValue: nil,\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"union of unions\",\n\t\tinCtxEntry: &yang.Entry{\n\t\t\tName: \"union-leaf\",\n\t\t\tKind: yang.LeafEntry,\n\t\t\tType: &yang.YangType{\n\t\t\t\tKind: yang.Yunion,\n\t\t\t\tType: []*yang.YangType{\n\t\t\t\t\t{\n\t\t\t\t\t\tKind: yang.Yunion,\n\t\t\t\t\t\tType: []*yang.YangType{\n\t\t\t\t\t\t\t{Kind: yang.Ystring},\n\t\t\t\t\t\t\t{Kind: yang.Yint32},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tKind: yang.Yunion,\n\t\t\t\t\t\tType: []*yang.YangType{\n\t\t\t\t\t\t\t{Kind: yang.Yuint64},\n\t\t\t\t\t\t\t{Kind: yang.Yint16},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []string{\"string\", \"int32\", \"uint64\", \"int16\"},\n\t\twantMtypes: map[int]*ygen.MappedType{\n\t\t\t0: {\n\t\t\t\tNativeType: \"string\",\n\t\t\t\tUnionTypes: nil,\n\t\t\t\tIsEnumeratedValue: false,\n\t\t\t\tZeroValue: goZeroValues[\"string\"],\n\t\t\t\tDefaultValue: nil,\n\t\t\t},\n\t\t\t1: {\n\t\t\t\tNativeType: \"int32\",\n\t\t\t\tUnionTypes: nil,\n\t\t\t\tIsEnumeratedValue: false,\n\t\t\t\tZeroValue: goZeroValues[\"int32\"],\n\t\t\t\tDefaultValue: nil,\n\t\t\t},\n\t\t\t2: {\n\t\t\t\tNativeType: \"uint64\",\n\t\t\t\tUnionTypes: nil,\n\t\t\t\tIsEnumeratedValue: false,\n\t\t\t\tZeroValue: goZeroValues[\"uint64\"],\n\t\t\t\tDefaultValue: nil,\n\t\t\t},\n\t\t\t3: {\n\t\t\t\tNativeType: \"int16\",\n\t\t\t\tUnionTypes: nil,\n\t\t\t\tIsEnumeratedValue: false,\n\t\t\t\tZeroValue: goZeroValues[\"int16\"],\n\t\t\t\tDefaultValue: nil,\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"erroneous union without context\",\n\t\tinCtxEntry: &yang.Entry{\n\t\t\tName: \"union-leaf\",\n\t\t\tKind: yang.LeafEntry,\n\t\t\tType: &yang.YangType{\n\t\t\t\tName: \"enumeration-union\",\n\t\t\t\tKind: yang.Yunion,\n\t\t\t\tType: []*yang.YangType{{\n\t\t\t\t\tKind: yang.Yenum,\n\t\t\t\t\tName: \"enumeration\",\n\t\t\t\t\tEnum: &yang.EnumType{},\n\t\t\t\t}},\n\t\t\t\tBase: &yang.Type{\n\t\t\t\t\tName: \"union\",\n\t\t\t\t\tParent: &yang.Typedef{\n\t\t\t\t\t\tName: \"enumeration-union\",\n\t\t\t\t\t\tParent: &yang.Module{\n\t\t\t\t\t\t\tName: \"typedef-module\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tParent: &yang.Entry{Name: \"base-module\"},\n\t\t\tNode: &yang.Leaf{\n\t\t\t\tParent: &yang.Module{\n\t\t\t\t\tName: \"base-module\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tinNoContext: true,\n\t\twantErr: true,\n\t}, {\n\t\tname: \"typedef enum within a union\",\n\t\tinCtxEntry: &yang.Entry{\n\t\t\tName: \"union-leaf\",\n\t\t\tKind: yang.LeafEntry,\n\t\t\tType: &yang.YangType{\n\t\t\t\tName: \"union\",\n\t\t\t\tKind: yang.Yunion,\n\t\t\t\tType: []*yang.YangType{{\n\t\t\t\t\tKind: yang.Yenum,\n\t\t\t\t\tName: \"derived-enum\",\n\t\t\t\t\tEnum: &yang.EnumType{},\n\t\t\t\t\tBase: &yang.Type{\n\t\t\t\t\t\tName: \"enumeration\",\n\t\t\t\t\t\tParent: &yang.Typedef{\n\t\t\t\t\t\t\tName: \"derived-enum\",\n\t\t\t\t\t\t\tParent: &yang.Module{\n\t\t\t\t\t\t\t\tName: \"typedef-module\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}, {\n\t\t\t\t\tName: \"int16\",\n\t\t\t\t\tKind: yang.Yint16,\n\t\t\t\t}},\n\t\t\t},\n\t\t\tParent: &yang.Entry{Name: \"base-module\"},\n\t\t\tNode: &yang.Leaf{\n\t\t\t\tParent: &yang.Module{\n\t\t\t\t\tName: \"base-module\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []string{\"E_TypedefModule_DerivedEnum\", \"int16\"},\n\t\twantMtypes: map[int]*ygen.MappedType{\n\t\t\t0: {\n\t\t\t\tNativeType: \"E_TypedefModule_DerivedEnum\",\n\t\t\t\tIsEnumeratedValue: true,\n\t\t\t\tZeroValue: \"0\",\n\t\t\t},\n\t\t\t1: {\n\t\t\t\tNativeType: \"int16\",\n\t\t\t\tZeroValue: \"0\",\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"enum within a typedef union\",\n\t\tinCtxEntry: &yang.Entry{\n\t\t\tName: \"union-leaf\",\n\t\t\tKind: yang.LeafEntry,\n\t\t\tType: &yang.YangType{\n\t\t\t\tName: \"derived-union\",\n\t\t\t\tKind: yang.Yunion,\n\t\t\t\tType: []*yang.YangType{{\n\t\t\t\t\tKind: yang.Yenum,\n\t\t\t\t\tName: \"enumeration\",\n\t\t\t\t\tEnum: &yang.EnumType{},\n\t\t\t\t}, {\n\t\t\t\t\tName: \"int16\",\n\t\t\t\t\tKind: yang.Yint16,\n\t\t\t\t}},\n\t\t\t\tBase: &yang.Type{\n\t\t\t\t\tName: \"union\",\n\t\t\t\t\tParent: &yang.Typedef{\n\t\t\t\t\t\tName: \"derived-union\",\n\t\t\t\t\t\tParent: &yang.Module{\n\t\t\t\t\t\t\tName: \"union-module\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tParent: &yang.Entry{Name: \"base-module\"},\n\t\t\tNode: &yang.Leaf{\n\t\t\t\tParent: &yang.Module{\n\t\t\t\t\tName: \"base-module\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []string{\"E_UnionModule_DerivedUnion_Enum\", \"int16\"},\n\t\twantMtypes: map[int]*ygen.MappedType{\n\t\t\t0: {\n\t\t\t\tNativeType: \"E_UnionModule_DerivedUnion_Enum\",\n\t\t\t\tIsEnumeratedValue: true,\n\t\t\t\tZeroValue: \"0\",\n\t\t\t},\n\t\t\t1: {\n\t\t\t\tNativeType: \"int16\",\n\t\t\t\tZeroValue: \"0\",\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"typedef enum within a typedef union\",\n\t\tinCtxEntry: &yang.Entry{\n\t\t\tName: \"union-leaf\",\n\t\t\tKind: yang.LeafEntry,\n\t\t\tType: &yang.YangType{\n\t\t\t\tName: \"derived-union\",\n\t\t\t\tKind: yang.Yunion,\n\t\t\t\tType: []*yang.YangType{{\n\t\t\t\t\tKind: yang.Yenum,\n\t\t\t\t\tName: \"derived-enum\",\n\t\t\t\t\tEnum: &yang.EnumType{},\n\t\t\t\t\tBase: &yang.Type{\n\t\t\t\t\t\tName: \"enumeration\",\n\t\t\t\t\t\tParent: &yang.Typedef{\n\t\t\t\t\t\t\tName: \"derived-enum\",\n\t\t\t\t\t\t\tParent: &yang.Module{\n\t\t\t\t\t\t\t\tName: \"typedef-module\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}, {\n\t\t\t\t\tName: \"int16\",\n\t\t\t\t\tKind: yang.Yint16,\n\t\t\t\t}},\n\t\t\t\tBase: &yang.Type{\n\t\t\t\t\tName: \"union\",\n\t\t\t\t\tParent: &yang.Typedef{\n\t\t\t\t\t\tName: \"derived-union\",\n\t\t\t\t\t\tParent: &yang.Module{\n\t\t\t\t\t\t\tName: \"union-module\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tParent: &yang.Entry{Name: \"base-module\"},\n\t\t\tNode: &yang.Leaf{\n\t\t\t\tParent: &yang.Module{\n\t\t\t\t\tName: \"base-module\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []string{\"E_TypedefModule_DerivedEnum\", \"int16\"},\n\t\twantMtypes: map[int]*ygen.MappedType{\n\t\t\t0: {\n\t\t\t\tNativeType: \"E_TypedefModule_DerivedEnum\",\n\t\t\t\tIsEnumeratedValue: true,\n\t\t\t\tZeroValue: \"0\",\n\t\t\t},\n\t\t\t1: {\n\t\t\t\tNativeType: \"int16\",\n\t\t\t\tZeroValue: \"0\",\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"union of a single enum\",\n\t\tinCtxEntry: &yang.Entry{\n\t\t\tName: \"union-leaf\",\n\t\t\tKind: yang.LeafEntry,\n\t\t\tType: &yang.YangType{\n\t\t\t\tName: \"union\",\n\t\t\t\tKind: yang.Yunion,\n\t\t\t\tType: []*yang.YangType{{\n\t\t\t\t\tKind: yang.Yenum,\n\t\t\t\t\tName: \"enumeration\",\n\t\t\t\t\tEnum: &yang.EnumType{},\n\t\t\t\t}},\n\t\t\t},\n\t\t\tParent: &yang.Entry{Name: \"base-module\"},\n\t\t\tNode: &yang.Leaf{\n\t\t\t\tParent: &yang.Module{\n\t\t\t\t\tName: \"base-module\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []string{\"E_BaseModule_UnionLeaf_Enum\"},\n\t\twantMtypes: map[int]*ygen.MappedType{\n\t\t\t0: {\n\t\t\t\tNativeType: \"E_BaseModule_UnionLeaf_Enum\",\n\t\t\t\tIsEnumeratedValue: true,\n\t\t\t\tZeroValue: \"0\",\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"union of identityrefs\",\n\t\tinCtxEntry: &yang.Entry{\n\t\t\tName: \"context-leaf\",\n\t\t\tType: &yang.YangType{\n\t\t\t\tKind: yang.Yunion,\n\t\t\t\tType: []*yang.YangType{{\n\t\t\t\t\tKind: yang.Yidentityref,\n\t\t\t\t\tIdentityBase: &yang.Identity{\n\t\t\t\t\t\tName: \"id\",\n\t\t\t\t\t\tParent: &yang.Module{Name: \"basemod\"},\n\t\t\t\t\t},\n\t\t\t\t}, {\n\t\t\t\t\tKind: yang.Yidentityref,\n\t\t\t\t\tIdentityBase: &yang.Identity{\n\t\t\t\t\t\tName: \"id2\",\n\t\t\t\t\t\tParent: &yang.Module{Name: \"basemod2\"},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t\tNode: &yang.Leaf{\n\t\t\t\tName: \"context-leaf\",\n\t\t\t\tParent: &yang.Module{Name: \"basemod\"},\n\t\t\t},\n\t\t},\n\t\twant: []string{\"E_Basemod_Id\", \"E_Basemod2_Id2\"},\n\t\twantMtypes: map[int]*ygen.MappedType{\n\t\t\t0: {\n\t\t\t\tNativeType: \"E_Basemod_Id\",\n\t\t\t\tUnionTypes: nil,\n\t\t\t\tIsEnumeratedValue: true,\n\t\t\t\tZeroValue: \"0\",\n\t\t\t\tDefaultValue: nil,\n\t\t\t},\n\t\t\t1: {\n\t\t\t\tNativeType: \"E_Basemod2_Id2\",\n\t\t\t\tUnionTypes: nil,\n\t\t\t\tIsEnumeratedValue: true,\n\t\t\t\tZeroValue: \"0\",\n\t\t\t\tDefaultValue: nil,\n\t\t\t},\n\t\t},\n\t}, {\n\t\tname: \"union of single identityref\",\n\t\tinCtxEntry: &yang.Entry{\n\t\t\tName: \"union-leaf\",\n\t\t\tKind: yang.LeafEntry,\n\t\t\tType: &yang.YangType{\n\t\t\t\tName: \"union\",\n\t\t\t\tKind: yang.Yunion,\n\t\t\t\tType: []*yang.YangType{{\n\t\t\t\t\tKind: yang.Yidentityref,\n\t\t\t\t\tName: \"identityref\",\n\t\t\t\t\tDefault: \"prefix:CHIPS\",\n\t\t\t\t\tIdentityBase: &yang.Identity{\n\t\t\t\t\t\tName: \"base-identity\",\n\t\t\t\t\t\tParent: &yang.Module{\n\t\t\t\t\t\t\tName: \"base-module\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t\tParent: &yang.Entry{Name: \"base-module\"},\n\t\t\tNode: &yang.Leaf{\n\t\t\t\tParent: &yang.Module{\n\t\t\t\t\tName: \"base-module\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\twant: []string{\"E_BaseModule_BaseIdentity\"},\n\t\twantMtypes: map[int]*ygen.MappedType{\n\t\t\t0: {\n\t\t\t\tNativeType: \"E_BaseModule_BaseIdentity\",\n\t\t\t\tUnionTypes: nil,\n\t\t\t\tIsEnumeratedValue: true,\n\t\t\t\tZeroValue: \"0\",\n\t\t\t\tDefaultValue: ygot.String(\"prefix:CHIPS\"),\n\t\t\t},\n\t\t},\n\t}}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := NewGoLangMapper(true)\n\t\t\tif err := s.InjectEnumSet(enumMapFromEntry(tt.inCtxEntry), false, false, false, true, true, true, nil); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tmtypes := make(map[int]*ygen.MappedType)\n\t\t\tctypes := make(map[string]ygen.MappedUnionSubtype)\n\t\t\tctxEntry := tt.inCtxEntry\n\t\t\tif tt.inNoContext {\n\t\t\t\tctxEntry = nil\n\t\t\t}\n\t\t\tif errs := s.goUnionSubTypes(tt.inCtxEntry.Type, ctxEntry, ctypes, mtypes, false, false, true, true, nil); !tt.wantErr && errs != nil {\n\t\t\t\tt.Errorf(\"unexpected errors: %v\", errs)\n\t\t\t}\n\n\t\t\tfor i, wt := range tt.want {\n\t\t\t\tif subtype, ok := ctypes[wt]; !ok {\n\t\t\t\t\tt.Errorf(\"could not find expected type in ctypes: %s\", wt)\n\t\t\t\t\tcontinue\n\t\t\t\t} else if i != subtype.Index {\n\t\t\t\t\tt.Errorf(\"index of type %s was not as expected (%d != %d)\", wt, i, subtype.Index)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor ct := range ctypes {\n\t\t\t\tfound := false\n\t\t\t\tfor _, gt := range tt.want {\n\t\t\t\t\tif ct == gt {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found {\n\t\t\t\t\tt.Errorf(\"found unexpected type %s\", ct)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif diff := cmp.Diff(tt.wantMtypes, mtypes, cmp.AllowUnexported(ygen.MappedType{}), cmpopts.EquateEmpty()); diff != \"\" {\n\t\t\t\tt.Errorf(\"mtypes not as expected (-want, +got):\\n%s\", diff)\n\t\t\t}\n\t\t})\n\t}\n}", "func parseMultipleValues(v string) []string {\n\ttemp_vals := strings.Split(v, \"|\")\n\tvals := make([]string, 0, len(temp_vals))\n\tfor i := 0; i < len(temp_vals); i++ {\n\t\tstr := temp_vals[i]\n\t\tfor strings.HasSuffix(str, \"\\\\\") {\n\t\t\t// This | separator was escaped!\n\t\t\ti++\n\t\t\tif i < len(temp_vals) {\n\t\t\t\tstr = strings.Join([]string{str, temp_vals[i]}, \"|\")\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tvals = append(vals, str)\n\t}\n\treturn vals\n}", "func CompileRegexp(pattern string) *regexp.Regexp {\n\tif pattern == \"\" {\n\t\treturn nil\n\t}\n\n\t// add ^...$ to all regexp when not given\n\tif !strings.HasPrefix(pattern, \"^\") {\n\t\tpattern = \"^\" + pattern\n\t}\n\tif !strings.HasSuffix(pattern, \"$\") {\n\t\tpattern += \"$\"\n\t}\n\n\t// make all regexp case insensitive by default\n\tif !strings.Contains(pattern, \"(?i)\") {\n\t\tpattern = \"(?i)\" + pattern\n\t}\n\n\treturn regexp.MustCompile(pattern)\n}", "func toPattern(theType string) string {\n\tvar thePattern string\n\n\tswitch theType {\n\tcase \"string\":\n\t\tthePattern = \"\\\\w+\" //xmmm or [a-zA-Z0-9]+\n\n\tcase \"int\":\n\t\tthePattern = \"[0-9]+\"\n\tdefault:\n\n\t}\n\n\treturn thePattern\n}", "func UnionPolicy(sub ...GCPolicy) GCPolicy { return unionPolicy{sub} }", "func Pattern(query []byte) []byte {\n\ttokenizer := sqlparser.NewStringTokenizer(string(query))\n\tbuf := bytes.Buffer{}\n\tl := make([]byte, 4)\n\tfor {\n\t\ttyp, val := tokenizer.Scan()\n\t\tswitch typ {\n\t\tcase sqlparser.ID: //table, database, variable & ... names\n\t\t\tbuf.Write(val)\n\t\tcase 0: //End of query\n\t\t\treturn buf.Bytes()\n\t\tdefault:\n\t\t\tbinary.BigEndian.PutUint32(l, uint32(typ))\n\t\t\tbuf.Write(l)\n\t\t}\n\t}\n}", "func (s *sqlStrConcat) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {\n\tif node, ok := n.(*ast.BinaryExpr); ok {\n\t\tif start, ok := node.X.(*ast.BasicLit); ok {\n\t\t\tif str, e := gosec.GetString(start); e == nil {\n\t\t\t\tif !s.MatchPatterns(str) {\n\t\t\t\t\treturn nil, nil\n\t\t\t\t}\n\t\t\t\tif _, ok := node.Y.(*ast.BasicLit); ok {\n\t\t\t\t\treturn nil, nil // string cat OK\n\t\t\t\t}\n\t\t\t\tif second, ok := node.Y.(*ast.Ident); ok && s.checkObject(second, c) {\n\t\t\t\t\treturn nil, nil\n\t\t\t\t}\n\t\t\t\treturn gosec.NewIssue(c, n, s.ID(), s.What, s.Severity, s.Confidence), nil\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, nil\n}", "func BitwiseOr(a, b Expr) Expr {\n\treturn &arithmeticOperator{&simpleOperator{a, b, scanner.BITWISEOR}}\n}", "func (p *DefaultParser) CompileRegex(fields []string) ([]*regexp.Regexp, error) {\n\tr := make([]*regexp.Regexp, len(fields))\n\tfor i, f := range fields {\n\t\t/*\n\t\t\tvar nextField string\n\t\t\tif i == len(fields)-1 {\n\t\t\t\tnextField = \"\"\n\t\t\t} else {\n\t\t\t\tnextField = fields[i+1]\n\t\t\t}\n\t\t*/\n\t\tfieldName := p.NamedGroup(f)\n\t\t// TODO(stratus): This is the foundation for possibly two\n\t\t// regexes - one for easy single line fields and another one for\n\t\t// multi-field.\n\t\tre, err := regexp.Compile(fmt.Sprintf(`(?mis)%s\\s*(?P<%s>.*?)\\n`, f, fieldName))\n\t\t//re, err := regexp.Compile(fmt.Sprintf(`(?mis)%s\\s*(?P<%s>.*?)%s`, f, fieldName, nextField))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr[i] = re\n\t}\n\treturn r, nil\n}", "func wildCardToRegexp(pattern string) string {\n\tvar result strings.Builder\n\tresult.WriteString(\"(?i)\")\n\n\trpattern := strings.Replace(pattern, \"%\", \".*\", -1)\n\trpattern = strings.Replace(rpattern, \"_\", \".+\", -1)\n\tresult.WriteString(rpattern)\n\n\treturn result.String()\n}", "func WildcardToRegex(wildcard string) string {\n\tvar b strings.Builder\n\tb.WriteByte('^')\n\tfor {\n\t\tidx := strings.IndexByte(wildcard, '*')\n\t\tif idx < 0 {\n\t\t\tbreak\n\t\t}\n\t\tb.WriteString(regexp.QuoteMeta(wildcard[:idx]))\n\t\tb.WriteString(\"(.*)\")\n\t\twildcard = wildcard[idx+1:]\n\t}\n\tb.WriteString(regexp.QuoteMeta(wildcard))\n\tb.WriteByte('$')\n\treturn b.String()\n}", "func Pattern(query string) []byte {\n\ttokenizer := sqlparser.NewStringTokenizer(query)\n\tbuf := bytes.Buffer{}\n\tl := make([]byte, 4)\n\tfor {\n\t\ttyp, val := tokenizer.Scan()\n\t\tswitch typ {\n\t\tcase sqlparser.ID: //table, database, variable & ... names\n\t\t\tbuf.Write(val)\n\t\tcase 0: //End of query\n\t\t\treturn buf.Bytes()\n\t\tdefault:\n\t\t\tbinary.BigEndian.PutUint32(l, uint32(typ))\n\t\t\tbuf.Write(l)\n\t\t}\n\t}\n}" ]
[ "0.61462075", "0.5724693", "0.54109585", "0.5389475", "0.5352758", "0.5311938", "0.5296446", "0.52079266", "0.509988", "0.5068835", "0.50166506", "0.4883824", "0.48613974", "0.48101395", "0.476411", "0.47462666", "0.4721221", "0.47110087", "0.4707788", "0.4707788", "0.4707788", "0.47034052", "0.46927962", "0.4690483", "0.4679697", "0.4673898", "0.4671834", "0.46588546", "0.46551266", "0.4629399", "0.46276677", "0.46121502", "0.4607193", "0.46041298", "0.4599739", "0.45771435", "0.45724624", "0.45523068", "0.4517283", "0.45063072", "0.44724262", "0.44691747", "0.44674215", "0.44578397", "0.44559187", "0.4439225", "0.44369343", "0.4434684", "0.4432795", "0.44110462", "0.44036174", "0.43980512", "0.43868226", "0.43707", "0.43661848", "0.43642822", "0.4343667", "0.43379578", "0.43302333", "0.43285304", "0.43220276", "0.43206105", "0.4318368", "0.43178517", "0.43164745", "0.43152827", "0.43152827", "0.43152827", "0.43122888", "0.431062", "0.4305046", "0.43028057", "0.43021986", "0.42987874", "0.429769", "0.4289649", "0.42861116", "0.42818186", "0.42788905", "0.42740837", "0.42619228", "0.42353457", "0.42343026", "0.42336497", "0.4230622", "0.4229629", "0.42114812", "0.42107007", "0.4210694", "0.41924772", "0.4185505", "0.41815132", "0.4173137", "0.41692024", "0.41655874", "0.4155836", "0.4155094", "0.41439623", "0.41400468", "0.41383117" ]
0.8219543
0
langToFileRegexp converts a lang: parameter to its corresponding file patterns for file filters. The lang value must be valid, cf. validate.go
func langToFileRegexp(lang string) string { lang, _ = enry.GetLanguageByAlias(lang) // Invariant: lang is valid. extensions := enry.GetLanguageExtensions(lang) patterns := make([]string, len(extensions)) for i, e := range extensions { // Add `\.ext$` pattern to match files with the given extension. patterns[i] = regexp.QuoteMeta(e) + "$" } return unionRegexp(patterns) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FileExtFilterForLang(lang string) (regex, glob string) {\n\tswitch strings.ToLower(lang) {\n\tcase \"go\", \"golang\":\n\t\treturn \".*\\\\.go\", \"*.go\"\n\t}\n\treturn \".*\", \"*\"\n}", "func FileExtToLanguage(ext string) (Language, error) {\n\tswitch {\n\tcase ext == \"c\":\n\t\treturn LangC, nil\n\tcase ext == \"cpp\" || ext == \"cxx\" || ext == \"C\":\n\t\treturn LangCPP, nil\n\t\t//\tcase ext == \"java\":\n\t\t//\t\treturn LangJava, nil\n\t\t//\tcase ext == \"py\":\n\t\t//\t\treturn LangPython2, nil\n\t\t//\tcase ext == \"py3\":\n\t\t//\t\treturn LangPython3, nil\n\t\t//\tcase ext == \"hs\":\n\t\t//\t\treturn LangHaskell, nil\n\t\t//\tcase ext == \"rb\":\n\t\t//\t\treturn LangRuby, nil\n\t\t//\tcase ext == \"lisp\":\n\t\t//\t\treturn LangCommonLISP, nil\n\t\t//\tcase ext == \"pas\":\n\t\t//\t\treturn LangPascal, nil\n\tcase ext == \"go\":\n\t\treturn LangGo, nil\n\tdefault:\n\t\treturn \"\", ErrInvalidLanguage(ext)\n\t}\n}", "func LangColumnNameRegexp() *regexp.Regexp {\n\tlangColumnRegexpInitializer.Do(func() {\n\t\tr, err := regexp.Compile(\"lang_([a-z]{2})\")\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"Can't create a regexp for lang column name. Reason: %w. Please, submit an issue with the execution logs here: https://github.com/s0nerik/goloc\", err))\n\t\t}\n\t\tlangColumnRegexp = r\n\t})\n\treturn langColumnRegexp\n}", "func NewRegexpFile(r *regexp.Regexp) *File {\n\treturn NewFile(&regexpElement{Data: r})\n}", "func validateLang() {\n\t\n\t//print all lang options\n\tfmt.Println(intro)\n\tfor _, lang := range languages {\n\t\tfmt.Println(lang)\n\t}\n\n\t//local lines that will hold all lines in the choosen lang file\n\tlines = make([]string,0)\n\t//l will be our predefined languages\n\tl := languages\n\n\t//infinit loop for reading user input language, loop ends if correct lang was choosen \n\tfor {\n\t\tpicked := strings.TrimSpace(userInput()) //read the input from Stdin, trim spaces \n\n\t\t//looping through our predefined languages\n\t\tfor _,lang := range(l) {\n\t\t\tfmt.Println(lang)\n\t\t\tif (picked == lang) {\n\t\t\t\t//fmt.Println(\"Found language!\", lang, picked)\n\t\t\t\tcustlang = lang //variable to hold current lang for client\n\t\t\t\tlang = lang + \".txt\" //append .txt because we are reading from files\n\t\t\t\n\t\t\t\tfile, err := os.Open(lang) //open the given languge file\n\t\t\t\tcheck(err) //check if correct\n\n\t\t\t\tscanner := bufio.NewScanner(file) //scanning through the file\n\t\t\t\tfor scanner.Scan() {\n\t\t\t\t\tlines = append(lines, scanner.Text()) //appending each line in the given langue file to lines\n\t\t\t\t }\n\t\t\t\tfile.Close() //close the file\n\t\t\t\tcheck(scanner.Err()) //check for errors so nothing is left in the file to read\n\t\t\t\tbreak\n\t\t\t} \n\t\t}\n\t\t//check so we actually got something in len, if we have, we have successfully changed language\n\t\tif (len(lines) != 0) {\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(end) //print error msg\n\t\t}\n\t}\n}", "func ruleToRegexp(text string) (string, error) {\n\tif text == \"\" {\n\t\treturn \".*\", nil\n\t}\n\n\t// already regexp?\n\tlength := len(text)\n\tif length >= 2 && text[:1] == \"/\" && text[length-1:] == \"/\" {\n\t\t// filter is a regular expression\n\t\treturn text[1 : length-1], nil\n\t}\n\n\trule := escapeSpecialRegxp.ReplaceAllStringFunc(text, func(src string) string {\n\t\treturn fmt.Sprintf(`\\%v`, src)\n\t})\n\trule = strings.Replace(rule, \"^\", `(?:[^\\\\w\\\\d_\\\\\\-.%]|$)`, -1)\n\trule = strings.Replace(rule, \"*\", \".*\", -1)\n\n\tlength = len(rule)\n\tif rule[length-1] == '|' {\n\t\trule = rule[:length-1] + \"$\"\n\t}\n\n\tif rule[:2] == \"||\" {\n\t\tif len(rule) > 2 {\n\t\t\trule = `^(?:[^:/?#]+:)?(?://(?:[^/?#]*\\\\.)?)?` + rule[2:]\n\t\t}\n\t} else if rule[0] == '|' {\n\t\trule = \"^\" + rule[1:]\n\t}\n\n\trule = re.MustCompile(`(\\|)[^$]`).ReplaceAllString(rule, `\\|`)\n\n\treturn rule, nil\n}", "func parseLanguageFile(languagefile string, values interface{}) error {\n\tfilename, _ := filepath.Abs(languagefile)\n\tconfigFile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := yaml.Unmarshal(configFile, values); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func FilterLang(text, lang string) (new string) {\n\tfor _, value := range text {\n\t\tif unicode.IsLetter(value) || unicode.Is(unicode.Scripts[lang], value) {\n\t\t\tnew += string(value)\n\t\t}\n\t}\n\n\treturn\n}", "func LangValidator(l Lang) error {\n\tswitch l {\n\tcase LangPy, LangJs:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"allocationstrategy: invalid enum value for lang field: %q\", l)\n\t}\n}", "func readFileToRegexpList(filename string) []*regexp.Regexp {\n\tvar regexp_list = []*regexp.Regexp{}\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err == nil {\n\t\tfor _, line := range strings.Split(string(content), \"\\n\") {\n\t\t\tif line != \"\" {\n\t\t\t\tregexp_list = append(regexp_list, regexp.MustCompile(line))\n\t\t\t}\n\t\t}\n\t}\n\treturn regexp_list\n}", "func filterLang(p pageView, lang string, emit func(pageView)) {\n\tif p.Lang == lang {\n\t\temit(p)\n\t}\n}", "func ValidateLanguage(lang string) bool {\n\tif len(lang) != 2 {\n\t\treturn false\n\t}\n\tfor _, lan := range exixtentLanguages {\n\t\tif lan == lang {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func SetLanguageFilePath(path string) string {\n\tlastPath := langFilePath\n\tlangFilePath = path\n\treturn lastPath\n}", "func detectLanguage(f *os.File) (string, error) {\n\tswitch filepath.Ext(f.Name()) {\n\tcase \".go\":\n\t\treturn golang, nil\n\tcase \".py\":\n\t\treturn python, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unknown language for file %v\", f.Name())\n\t}\n}", "func (c *Client) MatchLang(strings ...string) Lang {\n\t_, index := language.MatchStrings(c.matcher, strings...)\n\treturn c.langs[index]\n}", "func checkLang() {\n\tif flag_lang == \"\" {\n\t\treturn\n\t}\n\n\tvar err error\n\tlangWant, err = parseLang(flag_lang)\n\tif err != nil {\n\t\tlog.Fatalf(\"invalid value %q for -lang: %v\", flag_lang, err)\n\t}\n\n\tif def := currentLang(); flag_lang != def {\n\t\tdefVers, err := parseLang(def)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"internal error parsing default lang %q: %v\", def, err)\n\t\t}\n\t\tif langWant.major > defVers.major || (langWant.major == defVers.major && langWant.minor > defVers.minor) {\n\t\t\tlog.Fatalf(\"invalid value %q for -lang: max known version is %q\", flag_lang, def)\n\t\t}\n\t}\n}", "func (c *Lang) cleanLang(code string) error {\n\ts := c.langFileName(\"tmp_dir\", code)\n\terr := ioutil.WriteFile(s, []byte(\"[]\"), 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.Remove(s)\n\treturn i18n.LoadTranslationFile(s)\n}", "func fnRegex(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tif params == nil || len(params) > 3 {\n\t\tctx.Log().Error(\"error_type\", \"func_regex\", \"op\", \"regex\", \"cause\", \"wrong_number_of_parameters\", \"params\", params)\n\t\tstats.IncErrors()\n\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"wrong number of parameters in call to regex function\"), \"regex\", params})\n\t\treturn nil\n\t}\n\treg, err := regexp.Compile(extractStringParam(params[1]))\n\tif err != nil {\n\t\tctx.Log().Error(\"error_type\", \"func_regex\", \"op\", \"regex\", \"cause\", \"invalid_regex\", \"params\", params, \"error\", err.Error())\n\t\tstats.IncErrors()\n\t\tAddError(ctx, RuntimeError{fmt.Sprintf(\"invalid regex in call to regex function: %s\", err.Error()), \"regex\", params})\n\t\treturn nil\n\n\t}\n\tall := false\n\tif len(params) == 3 {\n\t\tall, err = strconv.ParseBool(extractStringParam(params[2]))\n\t\tif err != nil {\n\t\t\tctx.Log().Error(\"error_type\", \"func_regex\", \"op\", \"regex\", \"cause\", \"non_boolean_parameter\", \"params\", params, \"error\", err.Error())\n\t\t\tstats.IncErrors()\n\t\t\tAddError(ctx, SyntaxError{fmt.Sprintf(\"non boolean parameters in call to regex function\"), \"regex\", params})\n\t\t\treturn nil\n\t\t}\n\t}\n\tif all {\n\t\titems := reg.FindAllString(extractStringParam(params[0]), -1)\n\t\tres := \"\"\n\t\tfor _, it := range items {\n\t\t\tres += it\n\t\t}\n\t\treturn res\n\t} else {\n\t\treturn reg.FindString(extractStringParam(params[0]))\n\t}\n}", "func (c *Lang) applyFile(code string) (error, string) {\n\n\t_, header, err := c.GetFile(\"file\")\n\tif err != nil {\n\t\treturn err, T(\"lang_nofile\")\n\t}\n\n\ta := strings.Split(header.Filename, \".\")\n\tif l := len(a); l < 2 || strings.ToLower(a[l-1]) != \"json\" {\n\t\treturn errors.New(\"client validation by file type hacked\"), T(\"lang_badfile\")\n\t}\n\n\ts := c.langFileName(\"tmp_dir\", code)\n\n\terr = c.SaveToFile(\"file\", s)\n\tif err != nil {\n\t\treturn err, T(\"internal\")\n\t}\n\n\terr = i18n.LoadTranslationFile(s)\n\tdefer os.Remove(s)\n\tif err != nil {\n\t\treturn err, T(\"internal\")\n\t}\n\n\ts2 := c.langFileName(\"lang::folder\", code)\n\terr = c.SaveToFile(\"file\", s2)\n\tif err == nil {\n\t\terr = i18n.LoadTranslationFile(s2)\n\t}\n\n\tif err != nil {\n\t\treturn err, T(\"internal\")\n\t}\n\n\treturn nil, \"\"\n}", "func genRegex(domain string) string {\n\treturn fmt.Sprintf(`(?:^|.+\\.)%s$`, strings.Replace(domain, \".\", `\\.`, -1))\n}", "func FileKindForLang(langID string) FileKind {\n\tswitch langID {\n\tcase \"go\":\n\t\treturn Go\n\tcase \"go.mod\":\n\t\treturn Mod\n\tcase \"go.sum\":\n\t\treturn Sum\n\tcase \"tmpl\", \"gotmpl\":\n\t\treturn Tmpl\n\tcase \"go.work\":\n\t\treturn Work\n\tdefault:\n\t\treturn UnknownKind\n\t}\n}", "func loadLangInfo(fn string) (li *LangInfo, err error) {\n fin, err := os.Open(fn)\n if err != nil {return}\n defer fin.Close()\n bn := filepath.Base(fn)\n dat := strings.Split(bn, \".\")\n if len(dat) != 3 || dat[2] != \"lm\" {\n return nil, errors.New(\"bad format filename: \" + bn)\n }\n li = &LangInfo{fmap:make(map[string]int)}\n i, err := strconv.ParseInt(dat[1], 10, 16)\n if err != nil {\n return nil, err\n }\n li.id, li.name = int(i), dat[0]\n cnt := 0\n scanner := bufio.NewScanner(fin)\n for scanner.Scan() {\n cols := splitByByte(scanner.Text(), []byte(\" \\r\\n\\t\"))\n li.fmap[strings.TrimSpace(cols[0])] = cnt\n cnt++\n if cnt >= lMax {break}\n }\n return\n}", "func Language(val string) Argument {\n\treturn func(request *requests.Request) error {\n\t\tif !(val == \"es\" || val == \"en\" || val == \"pt\") {\n\t\t\treturn errors.New(\"language not supported. Supported languages are \\\"es\\\", \\\"en\\\" and \\\"pt\\\"\")\n\t\t}\n\t\trequest.AddArgument(\"language\", val)\n\t\treturn nil\n\t}\n}", "func translateGlob(glob string) (string, error) {\n\tre := []byte{}\n\tfor i := 0; i < len(glob); i++ {\n\t\tch := glob[i]\n\t\tswitch ch {\n\t\tcase '*':\n\t\t\tif i+1 < len(glob) && glob[i+1] == '*' {\n\t\t\t\tre = append(re, \".*\"...)\n\t\t\t\ti++\n\t\t\t} else {\n\t\t\t\tre = append(re, \"[^/]*\"...)\n\t\t\t}\n\t\tcase '?':\n\t\t\tre = append(re, \"[^/]\"...)\n\t\tcase '.':\n\t\t\tre = append(re, \"\\\\.\"...)\n\t\tcase '[':\n\t\t\tfor ; i < len(glob) && glob[i] != ']'; i++ {\n\t\t\t\tre = append(re, glob[i])\n\t\t\t}\n\t\t\tif i < len(glob) {\n\t\t\t\tre = append(re, ']')\n\t\t\t} else {\n\t\t\t\treturn \"\", errors.New(\"unterminated character range\")\n\t\t\t}\n\t\tdefault:\n\t\t\tre = append(re, ch)\n\t\t}\n\t}\n\tre = append(re, '$')\n\treturn string(re), nil\n}", "func fileMatchRegexp(logRoot, fileMatch string) *regexp.Regexp {\n\tif !os.IsPathSeparator(logRoot[len(logRoot)-1]) && !os.IsPathSeparator(fileMatch[0]) {\n\t\tlogRoot += string(os.PathSeparator)\n\t}\n\treturn regexp.MustCompile(\"^\" + regexp.QuoteMeta(logRoot) + fileMatch)\n}", "func Convert(pattern string) (*regexp.Regexp, error) {\n\tpattern = \"^\" + metaReplacer.Replace(regexp.QuoteMeta(pattern)) + \"$\"\n\treturn regexp.Compile(pattern)\n}", "func Rule(regex string) ConfigOption {\n\treturn func(c *Config) error {\n\t\treg, err := regexp.Compile(regex)\n\t\tc.Rules = append(c.Rules, rule{Regex: reg})\n\t\treturn err\n\t}\n}", "func detectLambdaLanguage(dirPath string) (string, error) {\n\tdirContents, err := utils.ReadDirectoryContents(dirPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Check the first file that is not a directory.\n\tvar fileNameParts []string\n\tfor i, content := range dirContents {\n\t\tcontentParts := strings.Split(content, \".\")\n\t\tif len(contentParts) >= 2 {\n\t\t\tfileNameParts = contentParts\n\t\t\tbreak\n\t\t}\n\n\t\tif i == (len(dirContents) - 1) {\n\t\t\treturn \"\", fmt.Errorf(\"Invalid file name provided.\")\n\t\t}\n\t}\n\n\tswitch fileNameParts[len(fileNameParts)-1] {\n\tcase \"ts\":\n\t\treturn \"typescript\", nil\n\tcase \"go\":\n\t\treturn \"go\", nil\n\tcase \"cs\", \"csproj\":\n\t\treturn \"dotnet\", nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Unsupported language file detected.\")\n\t}\n}", "func CompileRegex(pattern string) (*regexp.Regexp, error) { return regexp.Compile(pattern) }", "func parseLang(s string) (lang, error) {\n\tmatches := goVersionRE.FindStringSubmatch(s)\n\tif matches == nil {\n\t\treturn lang{}, fmt.Errorf(`should be something like \"go1.12\"`)\n\t}\n\tmajor, err := strconv.Atoi(matches[1])\n\tif err != nil {\n\t\treturn lang{}, err\n\t}\n\tminor, err := strconv.Atoi(matches[2])\n\tif err != nil {\n\t\treturn lang{}, err\n\t}\n\treturn lang{major: major, minor: minor}, nil\n}", "func (r Reader) DetectLanguages(path string) []string {\n\tlangs := []string{}\n\tfiles, err := ioutil.ReadDir(path)\n\n\tif err != nil {\n\t\treturn langs\n\t}\n\n\tfor _, f := range files {\n\t\tname := f.Name()\n\t\tisDirectory := f.IsDir()\n\n\t\tif !isDirectory && strings.HasSuffix(name, \".resx\") {\n\t\t\tparts := strings.Split(name, \".\")\n\t\t\tlength := len(parts)\n\n\t\t\tif length <= 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlanguage := parts[length-2]\n\t\t\tlangs = append(langs, language)\n\t\t}\n\t}\n\n\treturn langs\n}", "func GetFileLanguage(f os.File) *Language {\n\tfstat, _ := f.Stat()\n\treturn getFileLanguage(fstat.Name())\n}", "func GetLanguageFromFileName(fname string) *Language {\n\treturn getFileLanguage(fname)\n}", "func setLang(lang string) {\n\tif lang == \"pl\" {\n\t\tl = langTexts[\"pl\"]\n\t} else if lang == \"en\" {\n\t\tl = langTexts[\"en\"]\n\t}\n}", "func emailTemplateFilenameRegexp(c context.Context) (*regexp.Regexp, error) {\n\tappID, err := common.GetAppID(c)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to get app ID\").Err()\n\t}\n\n\treturn regexp.MustCompile(fmt.Sprintf(\n\t\t`^%s+/email-templates/([a-z][a-z0-9_]*)%s$`,\n\t\tregexp.QuoteMeta(appID),\n\t\tregexp.QuoteMeta(mailtmpl.FileExt),\n\t)), nil\n}", "func getRegexp(env *lisp.LEnv, v *lisp.LVal) (re *regexp.Regexp, lerr *lisp.LVal) {\n\tif v.Type == lisp.LString {\n\t\tre, err := regexp.Compile(v.Str)\n\t\tif err != nil {\n\t\t\treturn nil, invalidPatternError(env, err)\n\t\t}\n\t\treturn re, nil\n\t}\n\tif v.Type != lisp.LNative {\n\t\treturn nil, env.Errorf(\"argument is not a regexp: %v\", v.Type)\n\t}\n\tre, ok := v.Native.(*regexp.Regexp)\n\tif !ok {\n\t\treturn nil, env.Errorf(\"argument is not a regexp: %v\", v)\n\t}\n\treturn re, nil\n}", "func (l *Language) MatchFilename(name string) bool {\n\t// If you adjust this implementation, remember to update CompileByFilename\n\tfor _, n := range l.Filenames {\n\t\tif name == n {\n\t\t\treturn true\n\t\t}\n\t}\n\tif ext := path.Ext(name); ext != \"\" {\n\t\tfor _, x := range l.Extensions {\n\t\t\tif strings.EqualFold(ext, x) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (s *htmlState) checkLang(lang string) {\n\tif s.ignore&issueLangTag != 0 {\n\t\treturn\n\t}\n\t_, err := language.Parse(lang)\n\tswitch e := err.(type) {\n\tcase nil:\n\t\t// No error.\n\tcase language.ValueError:\n\t\ts.err(fmt.Errorf(\"language tag '%s' has bad part %s\", lang, e.Subtag()))\n\tdefault:\n\t\t// A syntax error.\n\t\ts.err(fmt.Errorf(\"language tag '%s' is ill-formed\", lang))\n\t}\n}", "func SearchFile(filePath string, reader io.Reader, cb func(*Comment)) error {\n\t// TODO right now, enry only infers the language based on the file extension\n\t// we should add some \"preview\" bytes from the file so that it has some sample content to examine\n\tlang := Language(enry.GetLanguage(filepath.Base(filePath), nil))\n\tif enry.IsVendor(filePath) {\n\t\treturn nil\n\t}\n\toptions, ok := LanguageParseOptions[lang]\n\tif !ok { // TODO provide a default parse option?\n\t\treturn nil\n\t}\n\tcommentParser, err := lege.NewParser(options)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcollections, err := commentParser.Parse(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, c := range collections {\n\t\tcomment := Comment{*c, filePath}\n\t\tcb(&comment)\n\t}\n\n\treturn nil\n}", "func LangIn(vs ...Lang) predicate.AllocationStrategy {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.AllocationStrategy(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldLang), v...))\n\t})\n}", "func regExp(context interface{}, value string) (bson.RegEx, error) {\n\tidx := strings.IndexByte(value[1:], '/')\n\tif value[0] != '/' || idx == -1 {\n\t\terr := fmt.Errorf(\"Parameter %q is not a regular expression\", value)\n\t\tlog.Error(context, \"varLookup\", err, \"Regex parsing\")\n\t\treturn bson.RegEx{}, err\n\t}\n\n\tpattern := value[1 : idx+1]\n\tl := len(pattern) + 2\n\n\tvar options string\n\tif l < len(value) {\n\t\toptions = value[l:]\n\t}\n\n\treturn bson.RegEx{Pattern: pattern, Options: options}, nil\n}", "func loadFilters(regexes []string, mh filefilter.MatchHandler, newLine string) ([]*filefilter.Filter, error) {\n\tfilters := make([]*filefilter.Filter, len(regexes))\n\tvar err error\n\tfor i, regex := range regexes {\n\t\tif filters[i], err = filefilter.NewFilter(regex, mh, newLine); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn filters, nil\n}", "func IsLang(x string) bool {\n\tv := parse(x)\n\treturn v != version{} && v.patch == \"\" && v.kind == \"\" && v.pre == \"\"\n}", "func (l *Lexer) acceptRegexp(valid string) bool {\n\tif MatchRegexp(valid, []byte(string(l.next()))) {\n\t\treturn true\n\t}\n\tl.backup()\n\n\treturn false\n}", "func GetLanguage(filename string, content []byte) string {\n\tif lang, safe := GetLanguageByFilename(filename); safe {\n\t\treturn lang\n\t}\n\n\tif lang, safe := GetLanguageByShebang(content); safe {\n\t\treturn lang\n\t}\n\n\tif lang, safe := GetLanguageByExtension(filename); safe {\n\t\treturn lang\n\t}\n\n\tlang, _ := GetLanguageByContent(filename, content)\n\treturn lang\n}", "func (m *GitignoreLang) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (p *DefaultParser) CompileRegex(fields []string) ([]*regexp.Regexp, error) {\n\tr := make([]*regexp.Regexp, len(fields))\n\tfor i, f := range fields {\n\t\t/*\n\t\t\tvar nextField string\n\t\t\tif i == len(fields)-1 {\n\t\t\t\tnextField = \"\"\n\t\t\t} else {\n\t\t\t\tnextField = fields[i+1]\n\t\t\t}\n\t\t*/\n\t\tfieldName := p.NamedGroup(f)\n\t\t// TODO(stratus): This is the foundation for possibly two\n\t\t// regexes - one for easy single line fields and another one for\n\t\t// multi-field.\n\t\tre, err := regexp.Compile(fmt.Sprintf(`(?mis)%s\\s*(?P<%s>.*?)\\n`, f, fieldName))\n\t\t//re, err := regexp.Compile(fmt.Sprintf(`(?mis)%s\\s*(?P<%s>.*?)%s`, f, fieldName, nextField))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr[i] = re\n\t}\n\treturn r, nil\n}", "func parseFile(path string) string {\n\tif isVar(path) {\n\t\t// replace wildcard\n\t\tpath = strings.Replace(path, \"*\", `[\\S]*`, -1)\n\t\t// escape '.'\n\t\tpath = strings.Replace(path, \".\", `\\.`, -1)\n\t\t// escape '/'\n\t\tpath = strings.Replace(path, \"/\", `\\/`, -1)\n\t\t// add wildcard after dir suffix\n\t\t// note: this is not really needed as\n\t\t// burp will treat blank files as wildcards\n\t\tif strings.HasSuffix(path, \"/\") {\n\t\t\tpath = path + `[\\S]*`\n\t\t}\n\t\tpath = \"^\" + path + \"$\"\n\t} else {\n\t\tpath = `^[\\S]*$`\n\t}\n\treturn path\n}", "func load(assetNames []string, asset func(string) ([]byte, error), options ...LoaderOption) Loader {\n\tvar c = LoaderConfig{\n\t\tLeft: \"{{\",\n\t\tRight: \"}}\",\n\t\tStrict: false,\n\t}\n\n\tfor _, opt := range options {\n\t\topt(&c)\n\t}\n\n\treturn func(m *Matcher) (Localizer, error) {\n\t\tlanguageFiles, err := m.ParseLanguageFiles(assetNames)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlocales := make(MemoryLocalizer)\n\n\t\tfor langIndex, langFiles := range languageFiles {\n\t\t\tkeyValues := make(map[string]interface{})\n\n\t\t\tfor _, fileName := range langFiles {\n\t\t\t\tunmarshal := yaml.Unmarshal\n\t\t\t\tif idx := strings.LastIndexByte(fileName, '.'); idx > 1 {\n\t\t\t\t\tswitch fileName[idx:] {\n\t\t\t\t\tcase \".toml\", \".tml\":\n\t\t\t\t\t\tunmarshal = toml.Unmarshal\n\t\t\t\t\tcase \".json\":\n\t\t\t\t\t\tunmarshal = json.Unmarshal\n\t\t\t\t\tcase \".ini\":\n\t\t\t\t\t\tunmarshal = unmarshalINI\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tb, err := asset(fileName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tif err = unmarshal(b, &keyValues); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar (\n\t\t\t\ttemplateKeys = make(map[string]*template.Template)\n\t\t\t\tlineKeys = make(map[string]string)\n\t\t\t\tother = make(map[string]interface{})\n\t\t\t)\n\n\t\t\tfor k, v := range keyValues {\n\t\t\t\t// fmt.Printf(\"[%d] %s = %v of type: [%T]\\n\", langIndex, k, v, v)\n\n\t\t\t\tswitch value := v.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tif leftIdx, rightIdx := strings.Index(value, c.Left), strings.Index(value, c.Right); leftIdx != -1 && rightIdx > leftIdx {\n\t\t\t\t\t\t// we assume it's template?\n\t\t\t\t\t\tif t, err := template.New(k).Delims(c.Left, c.Right).Funcs(c.FuncMap).Parse(value); err == nil {\n\t\t\t\t\t\t\ttemplateKeys[k] = t\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t} else if c.Strict {\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tlineKeys[k] = value\n\t\t\t\tdefault:\n\t\t\t\t\tother[k] = v\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tt := m.Languages[langIndex]\n\t\t\tlocales[langIndex] = &defaultLocale{\n\t\t\t\tindex: langIndex,\n\t\t\t\tid: t.String(),\n\t\t\t\ttag: &t,\n\t\t\t\ttemplateKeys: templateKeys,\n\t\t\t\tlineKeys: lineKeys,\n\t\t\t\tother: other,\n\t\t\t}\n\t\t}\n\n\t\tif n := len(locales); n == 0 {\n\t\t\treturn nil, fmt.Errorf(\"locales not found in %s\", strings.Join(assetNames, \", \"))\n\t\t} else if c.Strict && n < len(m.Languages) {\n\t\t\treturn nil, fmt.Errorf(\"locales expected to be %d but %d parsed\", len(m.Languages), n)\n\t\t}\n\n\t\treturn locales, nil\n\t}\n}", "func FromFiles(dir, lang string) (*Locale, error) {\n\tlocale := Locale{\n\t\tLang: lang,\n\t\tData: make(map[string]interface{}),\n\t}\n\tbasePath := fmt.Sprintf(\"%s/%s/\", dir, lang)\n\tfiles, err := ioutil.ReadDir(basePath)\n\tif err != nil {\n\t\treturn &locale, err\n\t}\n\n\tfor _, file := range files {\n\t\tvar target interface{}\n\t\tcontents, err := ioutil.ReadFile(basePath + file.Name())\n\t\tif err != nil {\n\t\t\treturn &locale, err\n\t\t}\n\t\terr = yaml.Unmarshal(contents, &target)\n\t\tif err != nil {\n\t\t\treturn &locale, err\n\t\t}\n\t\tlocale.Data[strings.ReplaceAll(file.Name(), \".yml\", \"\")] = target\n\t}\n\n\treturn &locale, nil\n}", "func (ls Languages) ByFilename(name string) []*Language {\n\tvar matches []*Language\n\tfor _, l := range ls {\n\t\tif l.MatchFilename(name) {\n\t\t\tmatches = append(matches, l)\n\t\t}\n\t}\n\tsort.Sort(&sortByPrimaryMatch{name, matches})\n\treturn matches\n}", "func (this *Tidy) Language(val string) (bool, error) {\n\tv := (*C.tmbchar)(C.CString(val))\n\tdefer C.free(unsafe.Pointer(v))\n\treturn this.optSetString(C.TidyLanguage, v)\n}", "func BuildRegex(cfg YamlConfig) *regexp.Regexp {\n\n\t// Create subPatterns slice from cfg.Definitions\n\tsubPatterns := make([]interface{}, len(cfg.Definitions))\n\tfor i, def := range cfg.Definitions {\n\t\tsubPatterns[i] = def.Pattern\n\t}\n\n\t// Interpolate subpatterns in main pattern, compile regex\n\tpattern := fmt.Sprintf(cfg.LogPattern, subPatterns...)\n\tregex := regexp.MustCompile(pattern)\n\n\treturn regex\n\n}", "func (c *TransferCounter) CompileRegex(operator string) (*regexp.Regexp, error) {\n\tvar r *regexp.Regexp\n\tvar err error\n\n\tfor _, regionOperator := range regionOperators {\n\t\tif operator == regionOperator {\n\t\t\tr, err = regexp.Compile(\".*?operator finish.*?region-id=([0-9]*).*?\" + operator + \".*?store \\\\[([0-9]*)\\\\] to \\\\[([0-9]*)\\\\].*?\")\n\t\t}\n\t}\n\n\tfor _, leaderOperator := range leaderOperators {\n\t\tif operator == leaderOperator {\n\t\t\tr, err = regexp.Compile(\".*?operator finish.*?region-id=([0-9]*).*?\" + operator + \".*?store ([0-9]*) to ([0-9]*).*?\")\n\t\t}\n\t}\n\n\tif r == nil {\n\t\terr = errors.New(\"unsupported operator. \")\n\t}\n\treturn r, err\n}", "func NewFile(path string, lang string) *File {\n\treturn &File{Path: path, Lang: lang}\n}", "func (app *adapter) ToLanguage(parsed parsers.LanguageCommand) (Language, error) {\n\tvalues := []Value{}\n\tparsedValues := parsed.Values()\n\tfor _, oneParsedValue := range parsedValues {\n\t\tvalueBuilder := app.valueBuilder.Create()\n\t\tif oneParsedValue.IsRoot() {\n\t\t\troot := oneParsedValue.Root()\n\t\t\tvalueBuilder.WithRoot(root)\n\t\t}\n\n\t\tif oneParsedValue.IsTokens() {\n\t\t\ttokensPath := oneParsedValue.Tokens()\n\t\t\tvalueBuilder.WithTokensPath(tokensPath)\n\t\t}\n\n\t\tif oneParsedValue.IsChannels() {\n\t\t\tchannelsPath := oneParsedValue.Channels()\n\t\t\tvalueBuilder.WithChannelsPath(channelsPath)\n\t\t}\n\n\t\tif oneParsedValue.IsRules() {\n\t\t\trulesPath := oneParsedValue.Rules()\n\t\t\tvalueBuilder.WithRulesPath(rulesPath)\n\t\t}\n\n\t\tif oneParsedValue.IsLogic() {\n\t\t\tlogicsPath := oneParsedValue.Logic()\n\t\t\tvalueBuilder.WithLogicsPath(logicsPath)\n\t\t}\n\n\t\tif oneParsedValue.IsInputVariable() {\n\t\t\tinputVariable := oneParsedValue.InputVariable()\n\t\t\tvalueBuilder.WithInputVariable(inputVariable)\n\t\t}\n\n\t\tif oneParsedValue.IsExtends() {\n\t\t\tparsedExtendPaths := oneParsedValue.Extends()\n\t\t\tvalueBuilder.WithExtends(parsedExtendPaths)\n\t\t}\n\n\t\tif oneParsedValue.IsPatternMatches() {\n\t\t\tparsedPatternMatches := oneParsedValue.PatternMatches()\n\t\t\tpatternMatches, err := app.patternMatchadapter.ToPatternMatches(parsedPatternMatches)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tvalueBuilder.WithPatternMatches(patternMatches)\n\t\t}\n\n\t\tvalue, err := valueBuilder.Now()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvalues = append(values, value)\n\t}\n\n\tvariable := parsed.Variable()\n\treturn app.builder.Create().\n\t\tWithValues(values).\n\t\tWithVariable(variable).\n\t\tNow()\n}", "func makePatterns(t string, rules ...string) (*PatternInfo, error) {\n\tvar (\n\t\tptns = []*Pattern{}\n\t\tok bool\n\t\tformatList *FormatList\n\t)\n\tif formatList, ok = allFormats[t]; ok {\n\t\t// finded in all formats\n\t} else if t == RFCSYMBOL {\n\t\t// append to rfc formats\n\t\tfor _, list := range allFormats {\n\t\t\tfor k, v := range *list {\n\t\t\t\trfcFormats[k] = v\n\t\t\t}\n\t\t}\n\t\t// dynamic add rfc to all formats\n\t\tallFormats[RFCSYMBOL] = &rfcFormats\n\t\t// set the variables\n\t\tformatList = &rfcFormats\n\t\tok = true\n\t}\n\tif ok {\n\t\tregRule, _ := regexp.Compile(`\\$\\{[A-Za-z_]+}`)\n\t\tfor _, rule := range rules {\n\t\t\tpattern := new(Pattern)\n\t\t\tpattern.Type = t\n\t\t\tpattern.Original = rule\n\t\t\tkeys := []string{}\n\t\t\tcontext := regRule.ReplaceAllStringFunc(rule, func(all string) string {\n\t\t\t\trns := []rune(all)\n\t\t\t\tkey := string(rns[2 : len(rns)-1])\n\t\t\t\tif seg, ok := (*formatList)[key]; ok {\n\t\t\t\t\tkeys = append(keys, key)\n\t\t\t\t\treturn seg\n\t\t\t\t}\n\t\t\t\treturn all\n\t\t\t})\n\t\t\tcurRule := regexp.MustCompile(context)\n\t\t\tpattern.Rule = curRule\n\t\t\tpattern.Keys = keys\n\t\t\tptns = append(ptns, pattern)\n\t\t}\n\t\tinfo := new(PatternInfo)\n\t\tinfo.Patterns = ptns\n\t\tallPatternInfo[t] = info\n\t\treturn info, nil\n\t}\n\treturn nil, fmt.Errorf(\"the format type '%s' doesn't exist\", t)\n}", "func FilterByLanguageSql(languages []string) string {\n\tif len(languages) == 0 {\n\t\treturn \"\"\n\t}\n\torClauses := []string{}\n\tfor i := range languages {\n\t\tif languages[i] == \"he\" {\n\t\t\torClauses = append(orClauses, \"(cu.properties->>'original_language')::text = 'he'\")\n\t\t\tlanguages = append(languages[:i], languages[i+1:]...)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif len(languages) > 0 {\n\t\torClauses = append(orClauses, fmt.Sprintf(`\n\t\t\t\t0 < (\n\t\t\t\t\tselect\n\t\t\t\t\t\tcount(f.language)\n\t\t\t\t\tfrom\n\t\t\t\t\t\tfiles as f\n\t\t\t\t\twhere\n\t\t\t\t\t\tf.content_unit_id = cu.id and f.mime_type in ('video/mp4', 'audio/mpeg') %s\n\t\t\t\t)\n\t\t\t`, utils.InClause(\" and f.language in \", languages)))\n\t}\n\n\treturn fmt.Sprintf(\" and (%s)\", strings.Join(orClauses, \" or \"))\n}", "func LangEQ(v Lang) predicate.AllocationStrategy {\n\treturn predicate.AllocationStrategy(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldLang), v))\n\t})\n}", "func Regex(path string, r string) ([]string, error) {\n\tclearVars()\n\n\tregex, err := regexp.Compile(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = Find(path, func(s string, i os.FileInfo) {\n\t\tif regex.FindString(i.Name()) != \"\" {\n\t\t\tresults = append(results, s)\n\t\t}\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn results, nil\n}", "func LoadPatterns(path string) error {\n\treturn filepath.Walk(path, walkPatternDir)\n}", "func DirRegex(path string, r string) ([]string, error) {\n\tclearVars()\n\n\tregex, err := regexp.Compile(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = Find(path, func(s string, i os.FileInfo) {\n\t\tif i.Mode().IsDir() {\n\t\t\tif regex.FindString(i.Name()) != \"\" {\n\t\t\t\tresults = append(results, s)\n\t\t\t}\n\t\t}\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn results, nil\n}", "func regexFilter(attr, val string) map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"regexp\": map[string]string{\n\t\t\tattr: val,\n\t\t},\n\t}\n}", "func CompileERE(pattern string) (*regexp.Regexp, error) { return regexp.CompilePOSIX(pattern) }", "func (c Configuration) compileRegex(listofPaths []string) []*regexp.Regexp {\n\tlogger := c.logger()\n\tvar regexpObjects []*regexp.Regexp\n\tfor _, path := range listofPaths {\n\t\treg, err := regexp.Compile(path)\n\t\tif err != nil {\n\t\t\tlogger.Error().Err(err).Msgf(\"Error while compiling regex: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tregexpObjects = append(regexpObjects, reg)\n\t}\n\treturn regexpObjects\n}", "func loadWordlist() (bool, error) {\n\tregex_wordlist = []regexp.Regexp{}\n\n\t// Use dictionary to generate list of regexes for matching replacements\n\tf, err := os.Open(wordlist_file)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer f.Close()\n\n\twordscanner := bufio.NewScanner(f)\n\tfor wordscanner.Scan() {\n\t\tword := wordscanner.Text()\n\n\t\t// Skip empty lines\n\t\tif len(word) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tword = wordToRegex(word)\n\t\tif verbose {\n\t\t\tfmt.Printf(\"Adding regex:%s\\n\", word)\n\t\t}\n\n\t\tword_regex := regexp.MustCompile(word)\n\t\tregex_wordlist = append(regex_wordlist, *word_regex)\n\t}\n\treturn true, nil\n}", "func parseDirName(path string) (domain, lang, ver string, err error) {\n match := reDataDir.FindStringSubmatch(path)\n if match == nil {\n err = fmt.Errorf(\"error parsing text directory name: %s\", path)\n return\n }\n\n var val string\n for i, name := range reDataDir.SubexpNames() {\n switch name {\n case \"domain\":\n val = match[i]\n if val != \"_\" {\n domain = val\n }\n case \"lang\":\n val = match[i]\n if val != \"_\" {\n lang = val\n }\n case \"ver\":\n val = match[i]\n if val != \"_\" {\n ver = val\n }\n /* \n case \"weight\":\n if weight != 100 {\n weight, _ = strconv.Atoi(match[i])\n if weight > 99 {\n weight = 99\n }\n }\n */\n }\n }\n return\n}", "func AddRegex(name, reg string, fn govalidator.ParamValidator) {\n\tif paramTagMap[name] != nil {\n\t\tpanic(name + \", reg:\" + reg + \" is duplicated\")\n\t}\n\tparamTagRegexMap[name] = regexp.MustCompile(reg)\n\tparamTagMap[name] = fn\n}", "func (r *localRepository) Rules(location string) ([]Rule, error) {\n\tfile, err := os.Open(location)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tvar rules []Rule\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tmatches := reRuleSplitter.FindStringSubmatch(scanner.Text())\n\t\tif len(matches) == 4 {\n\t\t\trules = append(rules, Rule{\n\t\t\t\tCommand: matches[1],\n\t\t\t\tURL: matches[2],\n\t\t\t\tFilterExpression: matches[3],\n\t\t\t})\n\t\t}\n\t}\n\treturn rules, scanner.Err()\n}", "func (e *HTMLApplet) Lang(v string) *HTMLApplet {\n\te.a[\"lang\"] = v\n\treturn e\n}", "func (r *RenderEnv) RenderDirRegexp() *regexp.Regexp {\n\tregex := regexp.MustCompile(`\\${[A-Za-z0-9_]+}`)\n\treturn regex\n}", "func I18n(options ...Options) macaron.Handler {\n\topt := prepareOptions(options)\n\tinitLocales(opt)\n\treturn func(ctx *macaron.Context) {\n\t\tisNeedRedir := false\n\t\thasCookie := false\n\n\t\t// 1. Check URL arguments.\n\t\tlang := ctx.Query(opt.Parameter)\n\n\t\t// 2. Get language information from cookies.\n\t\tif len(lang) == 0 {\n\t\t\tlang = ctx.GetCookie(\"lang\")\n\t\t\thasCookie = true\n\t\t} else {\n\t\t\tisNeedRedir = true\n\t\t}\n\n\t\t// Check again in case someone modify by purpose.\n\t\tif !i18n.IsExist(lang) {\n\t\t\tlang = \"\"\n\t\t\tisNeedRedir = false\n\t\t\thasCookie = false\n\t\t}\n\n\t\t// 3. Get language information from 'Accept-Language'.\n\t\tif len(lang) == 0 {\n\t\t\tal := ctx.Req.Header.Get(\"Accept-Language\")\n\t\t\tif len(al) > 4 {\n\t\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\t\tif i18n.IsExist(al) {\n\t\t\t\t\tlang = al\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// 4. Default language is the first element in the list.\n\t\tif len(lang) == 0 {\n\t\t\tlang = i18n.GetLangByIndex(0)\n\t\t\tisNeedRedir = false\n\t\t}\n\n\t\tcurLang := LangType{\n\t\t\tLang: lang,\n\t\t}\n\n\t\t// Save language information in cookies.\n\t\tif !hasCookie {\n\t\t\tctx.SetCookie(\"lang\", curLang.Lang, 1<<31-1, \"/\"+strings.TrimPrefix(opt.SubURL, \"/\"))\n\t\t}\n\n\t\trestLangs := make([]LangType, 0, i18n.Count()-1)\n\t\tlangs := i18n.ListLangs()\n\t\tnames := i18n.ListLangDescs()\n\t\tfor i, v := range langs {\n\t\t\tif lang != v {\n\t\t\t\trestLangs = append(restLangs, LangType{v, names[i]})\n\t\t\t} else {\n\t\t\t\tcurLang.Name = names[i]\n\t\t\t}\n\t\t}\n\n\t\t// Set language properties.\n\t\tlocale := Locale{i18n.Locale{lang}}\n\t\tctx.Map(locale)\n\t\tctx.Locale = locale\n\t\tctx.Data[opt.TmplName] = locale\n\t\tctx.Data[\"Tr\"] = i18n.Tr\n\t\tctx.Data[\"Lang\"] = locale.Lang\n\t\tctx.Data[\"LangName\"] = curLang.Name\n\t\tctx.Data[\"AllLangs\"] = append([]LangType{curLang}, restLangs...)\n\t\tctx.Data[\"RestLangs\"] = restLangs\n\n\t\tif opt.Redirect && isNeedRedir {\n\t\t\tctx.Redirect(opt.SubURL + ctx.Req.RequestURI[:strings.Index(ctx.Req.RequestURI, \"?\")])\n\t\t}\n\t}\n}", "func (r *RenderEnv) File2File(src, dst string, vars *variables.Variables, nounset, noempty bool) (err error) {\n\tb, err := ioutil.ReadFile(src)\n\terrutils.Elogf(\"Can not open template file %s for reading: %v\", src, err)\n\tr.Text2File(string(b), dst, vars, nounset, noempty)\n\treturn\n}", "func ValidateRegexp(ch *Changeset, field string, exp *regexp.Regexp, opts ...Option) {\n\tval, exist := ch.changes[field]\n\tif !exist {\n\t\treturn\n\t}\n\n\toptions := Options{\n\t\tmessage: ValidateRegexpErrorMessage,\n\t}\n\toptions.apply(opts)\n\n\tif str, ok := val.(string); ok {\n\t\tmatch := exp.MatchString(str)\n\t\tif !match {\n\t\t\tmsg := strings.Replace(options.message, \"{field}\", field, 1)\n\t\t\tAddError(ch, field, msg)\n\t\t}\n\t\treturn\n\t}\n}", "func fileMatchPattern(filePath string, matchPattern string,\n\tnumExpectedMatches int) error {\n\tcontent, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open file %s\", filePath)\n\t}\n\t// need to normalize since Windows has different EOL character\n\tnormalizedContent := strings.Replace(string(content), \"\\r\\n\", \"\\n\", -1)\n\n\tmatcher := regexp.MustCompile(matchPattern)\n\tmatches := matcher.FindAllString(normalizedContent, -1)\n\tif len(matches) != numExpectedMatches {\n\t\treturn fmt.Errorf(\"failed pattern match: %s matched %d times instead of %d\",\n\t\t\tmatchPattern, len(matches), numExpectedMatches)\n\t}\n\n\treturn nil\n}", "func r(pattern string) *regexp.Regexp { return regexp.MustCompile(pattern) }", "func TestLoadingConfigRegexp(t *testing.T) {\n\t// list of filters used repeatedly on testdata/config.yaml\n\ttestDataFilters := []string{\n\t\t\"prefix/.*\",\n\t\t\"prefix_.*\",\n\t\t\".*/suffix\",\n\t\t\".*_suffix\",\n\t\t\".*/contains/.*\",\n\t\t\".*_contains_.*\",\n\t\t\"full/name/match\",\n\t\t\"full_name_match\",\n\t}\n\n\ttestDataMetricProperties := &filterconfig.MetricMatchProperties{\n\t\tMatchType: filterconfig.MetricRegexp,\n\t\tMetricNames: testDataFilters,\n\t}\n\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config_regexp.yaml\"))\n\trequire.NoError(t, err)\n\n\ttests := []struct {\n\t\tid component.ID\n\t\texpected component.Config\n\t}{\n\t\t{\n\t\t\tid: component.NewIDWithName(\"filter\", \"include\"),\n\t\t\texpected: &Config{\n\t\t\t\tErrorMode: ottl.PropagateError,\n\t\t\t\tMetrics: MetricFilters{\n\t\t\t\t\tInclude: testDataMetricProperties,\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tid: component.NewIDWithName(\"filter\", \"exclude\"),\n\t\t\texpected: &Config{\n\t\t\t\tErrorMode: ottl.PropagateError,\n\t\t\t\tMetrics: MetricFilters{\n\t\t\t\t\tExclude: testDataMetricProperties,\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tid: component.NewIDWithName(\"filter\", \"unlimitedcache\"),\n\t\t\texpected: &Config{\n\t\t\t\tErrorMode: ottl.PropagateError,\n\t\t\t\tMetrics: MetricFilters{\n\t\t\t\t\tInclude: &filterconfig.MetricMatchProperties{\n\t\t\t\t\t\tMatchType: filterconfig.MetricRegexp,\n\t\t\t\t\t\tRegexpConfig: &fsregexp.Config{\n\t\t\t\t\t\t\tCacheEnabled: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tMetricNames: testDataFilters,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tid: component.NewIDWithName(\"filter\", \"limitedcache\"),\n\t\t\texpected: &Config{\n\t\t\t\tErrorMode: ottl.PropagateError,\n\t\t\t\tMetrics: MetricFilters{\n\t\t\t\t\tExclude: &filterconfig.MetricMatchProperties{\n\t\t\t\t\t\tMatchType: filterconfig.MetricRegexp,\n\t\t\t\t\t\tRegexpConfig: &fsregexp.Config{\n\t\t\t\t\t\t\tCacheEnabled: true,\n\t\t\t\t\t\t\tCacheMaxNumEntries: 10,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tMetricNames: testDataFilters,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.id.String(), func(t *testing.T) {\n\t\t\tfactory := NewFactory()\n\t\t\tcfg := factory.CreateDefaultConfig()\n\n\t\t\tsub, err := cm.Sub(tt.id.String())\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, component.UnmarshalConfig(sub, cfg))\n\n\t\t\tassert.NoError(t, component.ValidateConfig(cfg))\n\t\t\tassert.Equal(t, tt.expected, cfg)\n\t\t})\n\t}\n}", "func OutputLanguagesToProtoLanguages(languages []string) ([]registryv1alpha1.PluginLanguage, error) {\n\tlanguageToEnum := make(map[string]registryv1alpha1.PluginLanguage)\n\tvar supportedLanguages []string\n\tfor pluginLanguageKey, pluginLanguage := range registryv1alpha1.PluginLanguage_value {\n\t\tif pluginLanguage == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tpluginLanguageKey := strings.TrimPrefix(pluginLanguageKey, \"PLUGIN_LANGUAGE_\")\n\t\tpluginLanguageKey = strings.ToLower(pluginLanguageKey)\n\t\t// Example:\n\t\t// { go: 1, javascript: 2 }\n\t\tlanguageToEnum[pluginLanguageKey] = registryv1alpha1.PluginLanguage(pluginLanguage)\n\t\tsupportedLanguages = append(supportedLanguages, pluginLanguageKey)\n\t}\n\tsort.Strings(supportedLanguages)\n\tvar protoLanguages []registryv1alpha1.PluginLanguage\n\tfor _, language := range languages {\n\t\tif pluginLanguage, ok := languageToEnum[language]; ok {\n\t\t\tprotoLanguages = append(protoLanguages, pluginLanguage)\n\t\t\tcontinue\n\t\t}\n\t\treturn nil, fmt.Errorf(\"invalid plugin output language: %q\\nsupported languages: %s\", language, strings.Join(supportedLanguages, \", \"))\n\t}\n\tsort.Slice(protoLanguages, func(i, j int) bool {\n\t\treturn protoLanguages[i] < protoLanguages[j]\n\t})\n\treturn protoLanguages, nil\n}", "func validateFileOrURL(v string) error {\n\tvalGen := pflagValueFuncMap[fileFlag]\n\tif valGen().Set(v) == nil {\n\t\treturn nil\n\t}\n\tvalGen = pflagValueFuncMap[urlFlag]\n\treturn valGen().Set(v)\n}", "func identifyLanguageStyle(path string) *languageStyle {\n\t// This comparison is probably cheaper so do it first.\n\tif result := identifyFromExtension(filepath.Ext(path)); result != nil {\n\t\treturn result\n\t}\n\tif match, _ := regexp.MatchString(\"\\\\..*rc\", path); match {\n\t\treturn commentStyles[\"shell\"]\n\t}\n\tif match, _ := regexp.MatchString(\".*Makefile$\", path); match {\n\t\treturn commentStyles[\"make\"]\n\t}\n\tif match, _ := regexp.MatchString(\".*Dockerfile(\\\\..*)?$\", path); match {\n\t\treturn commentStyles[\"docker\"]\n\t}\n\tif match, _ := regexp.MatchString(\".*BUILD(\\\\..*)?$|WORKSPACE(\\\\..*)?$\", path); match {\n\t\treturn commentStyles[\"bazel\"]\n\t}\n\t_, _ = fmt.Fprintf(os.Stderr, \"unable to identify language of %v\\n\", path)\n\treturn nil\n}", "func formatToRegexPattern(format string) string {\n\ts := gregex.Quote(formatToStdLayout(format))\n\ts, _ = gregex.ReplaceString(`[0-9]`, `[0-9]`, s)\n\ts, _ = gregex.ReplaceString(`[A-Za-z]`, `[A-Za-z]`, s)\n\treturn s\n}", "func getLangFormat() string {\n\treturn fmt.Sprintf(\"%v.%v\", lang.String(), format)\n}", "func (p Reviewer) Check(file reviewdata.FileDiff,\n passback interface{},\n commentChan chan <- reviewdata.Comment,\n wg *sync.WaitGroup) {\n\n for _, regex := range config.RegexReviewer.Checks {\n matchRegex := regexp.MustCompile(strings.Join(regex.File.Match, \"|\"))\n excludeRegex := regexp.MustCompile(strings.Join(regex.File.Exclude,\n \"|\"))\n\n if (matchRegex.MatchString(file.Filename) &&\n (len(regex.File.Exclude) == 0 ||\n !excludeRegex.MatchString(file.Filename))) {\n for _, chunk := range file.Diff_Data.Chunks {\n if (chunk.Change == \"insert\" || chunk.Change == \"replace\") {\n CheckChunk(regex, chunk, commentChan)\n }\n }\n }\n }\n\n (*wg).Done()\n}", "func (h *MemHome) Lang(path string) Lang { return h.langs.lang(path) }", "func (c *Config) FeatureRegex() *regexp.Regexp {\n\treturn c.featureRegex\n}", "func (l *Location) ListByRegex(regex *regexp.Regexp) ([]string, error) {\n\n\tfilenames, err := l.List()\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tvar filteredFilenames []string\n\tfor _, filename := range filenames {\n\t\tif regex.MatchString(filename) {\n\t\t\tfilteredFilenames = append(filteredFilenames, filename)\n\t\t}\n\t}\n\treturn filteredFilenames, nil\n}", "func addRule(rulesMap map[string]rule, ruleName string, checkFunc checkFuncType, fileTypeFlags int, fileExtensions string) {\n\tfileExtensionsArray := []string{}\n\tif fileExtensions != \"\" {\n\t\tfileExtensionsArray = strings.Split(fileExtensions, \"|\")\n\t}\n\n\trulesMap[ruleName] = rule{\n\t\tname: ruleName,\n\t\tcheckFunc: checkFunc,\n\t\tfileTypeFlags: fileTypeFlags,\n\t\tfileExtensions: fileExtensionsArray,\n\t}\n}", "func (a Action) OnRegexChange(regex string) Action {\n\treturn a.onSummaryChange(func(name string) string {\n\t\tre := regexp.MustCompile(regex)\n\t\t// TODO: avoid reading whole file if possible.\n\t\tb, err := ioutil.ReadFile(name)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Failed to open file:\", name)\n\t\t\treturn \"\"\n\t\t}\n\t\treturn fmt.Sprintf(\"%q\\n\", re.FindAll(b, -1))\n\t})\n}", "func scanExelFile() {\n\tvar (\n\t\tfileName string\n\t\terr error\n\t)\n\tfmt.Println(\"enter the exel file name with google translate phrasebook:\")\n\tfor {\n\t\t_, err = fmt.Scanf(\"%s\", &fileName)\n\t\tfmt.Println()\n\t\tif err == nil {\n\t\t\tbreak\n\t\t} else {\n\t\t\tfmt.Println(\"Some error occured: \", err)\n\t\t}\n\t}\n\txlsFile, err := excelize.OpenFile(fileName)\n\tif err != nil {\n\t\tfmt.Println(\"Some error occured when tryed to read exel file: \", err)\n\t}\n\tvar rows = xlsFile.GetRows(xlsFile.GetSheetName(1))\n\twb.words = make([]wordsPair, 0)\n\n\tfor i := 0; i < len(rows); i++ {\n\t\tif rows[i][0] == \"английский\" {\n\t\t\twb.addNewWord(&rows[i][2], &rows[i][3])\n\t\t} else {\n\t\t\twb.addNewWord(&rows[i][3], &rows[i][2])\n\t\t}\n\t}\n}", "func MatchExt(exts ...string) MatcherFunc { return MatchExts(exts) }", "func wildCardToRegexp(pattern string) string {\n\tvar result strings.Builder\n\tresult.WriteString(\"(?i)\")\n\n\trpattern := strings.Replace(pattern, \"%\", \".*\", -1)\n\trpattern = strings.Replace(rpattern, \"_\", \".+\", -1)\n\tresult.WriteString(rpattern)\n\n\treturn result.String()\n}", "func TestRegExSetPsqlite(t *testing.T) {\n\tvar pSqlite string\n\tb := []byte(\"\")\n\tif err := ioutil.WriteFile(\"/tmp/primary.sqlitexz\", b, 0644); err != nil {\n\t\tos.Remove(\"/tmp/primary.sqlitexz\")\n\t\tt.Fatalf(\"Error writing file\")\n\t}\n\terr := filepath.Walk(\"/tmp\", setPsqlite(&pSqlite))\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tif pSqlite != \"\" {\n\t\tos.Remove(\"/tmp/primary.sqlitexz\")\n\t\tt.Fatalf(\"Expected to not match file got \" + pSqlite)\n\t}\n\tos.Remove(\"/tmp/primary.sqlitexz\")\n\n\tif err := ioutil.WriteFile(\"/tmp/primary.sqlite.xzz\", b, 0644); err != nil {\n\t\tos.Remove(\"/tmp/primary.sqlite.xzz\")\n\t\tt.Fatalf(\"Error writing file\")\n\t}\n\terr = filepath.Walk(\"/tmp\", setPsqlite(&pSqlite))\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tif pSqlite != \"\" {\n\t\tos.Remove(\"/tmp/primary.sqlite.xzz\")\n\t\tt.Fatalf(\"Expected to not match file got \" + pSqlite)\n\t}\n\tos.Remove(\"/tmp/primary.sqlite.xzz\")\n\n\tif err := ioutil.WriteFile(\"/tmp/primary.sqlite.bz\", b, 0644); err != nil {\n\t\tos.Remove(\"/tmp/primary.sqlite.bz\")\n\t\tt.Fatalf(\"Error writing file\")\n\t}\n\terr = filepath.Walk(\"/tmp\", setPsqlite(&pSqlite))\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tif pSqlite != \"\" {\n\t\tos.Remove(\"/tmp/primary.sqlite.bz\")\n\t\tt.Fatalf(\"Expected to not match file got \" + pSqlite)\n\t}\n\tos.Remove(\"/tmp/primary.sqlite.bz\")\n}", "func matchPattern(fp string, patterns []MapPattern) (string, bool, error) {\n\tfp, err := realpath.Realpath(fp)\n\tif err != nil {\n\t\treturn \"\", false,\n\t\t\tErr(fmt.Errorf(\"failed to get the real path: %w\", err).Error())\n\t}\n\n\tfor _, pattern := range patterns {\n\t\tif pattern.Regex.MatchString(fp) {\n\t\t\tmatches := pattern.Regex.FindStringSubmatch(fp)\n\t\t\tif len(matches) > 0 {\n\t\t\t\tparams := make([]interface{}, len(matches[1:]))\n\t\t\t\tfor i, v := range matches[1:] {\n\t\t\t\t\tparams[i] = v\n\t\t\t\t}\n\n\t\t\t\tresult, err := pyfmt.Fmt(pattern.Name, params...)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"error formatting %q: %s\", pattern.Name, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\treturn result, true, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", false, nil\n}", "func NewParser(r io.Reader, lang *Language) *Parser {\n\treturn &Parser{s: NewScanner(r), lang: lang}\n}", "func (c *ReconcileCall) Lang(lang ...string) *ReconcileCall {\n\tc.urlParams_.SetMulti(\"lang\", append([]string{}, lang...))\n\treturn c\n}", "func TestLoadingConfigRegexp(t *testing.T) {\n\t// list of filters used repeatedly on testdata/config.yaml\n\ttestDataFilters := []string{\n\t\t\"prefix/.*\",\n\t\t\"prefix_.*\",\n\t\t\".*/suffix\",\n\t\t\".*_suffix\",\n\t\t\".*/contains/.*\",\n\t\t\".*_contains_.*\",\n\t\t\"full/name/match\",\n\t\t\"full_name_match\",\n\t}\n\n\ttestDataMetricProperties := &filtermetric.MatchProperties{\n\t\tMatchType: filtermetric.Regexp,\n\t\tMetricNames: testDataFilters,\n\t}\n\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config_regexp.yaml\"))\n\trequire.NoError(t, err)\n\n\ttests := []struct {\n\t\tid config.ComponentID\n\t\texpected config.Processor\n\t}{\n\t\t{\n\t\t\tid: config.NewComponentIDWithName(\"filter\", \"include\"),\n\t\t\texpected: &Config{\n\t\t\t\tProcessorSettings: config.NewProcessorSettings(config.NewComponentID(typeStr)),\n\t\t\t\tMetrics: MetricFilters{\n\t\t\t\t\tInclude: testDataMetricProperties,\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tid: config.NewComponentIDWithName(\"filter\", \"exclude\"),\n\t\t\texpected: &Config{\n\t\t\t\tProcessorSettings: config.NewProcessorSettings(config.NewComponentID(typeStr)),\n\t\t\t\tMetrics: MetricFilters{\n\t\t\t\t\tExclude: testDataMetricProperties,\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tid: config.NewComponentIDWithName(\"filter\", \"unlimitedcache\"),\n\t\t\texpected: &Config{\n\t\t\t\tProcessorSettings: config.NewProcessorSettings(config.NewComponentID(typeStr)),\n\t\t\t\tMetrics: MetricFilters{\n\t\t\t\t\tInclude: &filtermetric.MatchProperties{\n\t\t\t\t\t\tMatchType: filtermetric.Regexp,\n\t\t\t\t\t\tRegexpConfig: &fsregexp.Config{\n\t\t\t\t\t\t\tCacheEnabled: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tMetricNames: testDataFilters,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tid: config.NewComponentIDWithName(\"filter\", \"limitedcache\"),\n\t\t\texpected: &Config{\n\t\t\t\tProcessorSettings: config.NewProcessorSettings(config.NewComponentID(typeStr)),\n\t\t\t\tMetrics: MetricFilters{\n\t\t\t\t\tExclude: &filtermetric.MatchProperties{\n\t\t\t\t\t\tMatchType: filtermetric.Regexp,\n\t\t\t\t\t\tRegexpConfig: &fsregexp.Config{\n\t\t\t\t\t\t\tCacheEnabled: true,\n\t\t\t\t\t\t\tCacheMaxNumEntries: 10,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tMetricNames: testDataFilters,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.id.String(), func(t *testing.T) {\n\t\t\tfactory := NewFactory()\n\t\t\tcfg := factory.CreateDefaultConfig()\n\n\t\t\tsub, err := cm.Sub(tt.id.String())\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, config.UnmarshalProcessor(sub, cfg))\n\n\t\t\tassert.NoError(t, cfg.Validate())\n\t\t\tassert.Equal(t, tt.expected, cfg)\n\t\t})\n\t}\n}", "func Regex(pattern, options string) Val {\n\tregex := primitive.Regex{Pattern: pattern, Options: options}\n\treturn Val{t: bsontype.Regex, primitive: regex}\n}", "func parseRules(file string) ([]*Rule, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tvar rules []*Rule\n\terr = json.NewDecoder(f).Decode(&rules)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rules, nil\n}", "func SetLang(newLang string) error {\n\tfound := false\n\tfor _, l := range availLangs {\n\t\tif newLang == l {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn ErrNoLanguageFn(newLang)\n\t}\n\tlang = newLang\n\treturn nil\n}", "func Parse(s string, flags syntax.Flags,) (*syntax.Regexp, error)" ]
[ "0.6439551", "0.5576716", "0.5206838", "0.51490414", "0.50916624", "0.5010436", "0.49206352", "0.48391092", "0.47405547", "0.46976352", "0.46198", "0.45917705", "0.45901117", "0.45758092", "0.45268458", "0.45258516", "0.4491104", "0.44281682", "0.4424431", "0.4423438", "0.4404155", "0.44032088", "0.4397927", "0.43714845", "0.43670112", "0.43606368", "0.4332192", "0.43285146", "0.43083957", "0.4278119", "0.4276088", "0.42702034", "0.42583886", "0.4242676", "0.42386076", "0.42247832", "0.42245921", "0.42158183", "0.42060226", "0.41878226", "0.41831836", "0.41772905", "0.41684774", "0.41535124", "0.41450527", "0.41428858", "0.4134392", "0.41291142", "0.4129102", "0.41211718", "0.41210616", "0.41008115", "0.40972722", "0.4084119", "0.40771827", "0.40679654", "0.4062081", "0.40611446", "0.4047988", "0.4047433", "0.40456775", "0.40415883", "0.40329203", "0.40263087", "0.40191224", "0.40144113", "0.4006078", "0.400585", "0.39792085", "0.39784428", "0.39752257", "0.39685118", "0.39528292", "0.3949101", "0.3941122", "0.39392456", "0.39385784", "0.393207", "0.39318153", "0.3931806", "0.39208215", "0.39145213", "0.39143297", "0.39113656", "0.3911177", "0.39083195", "0.39036915", "0.38939947", "0.38894984", "0.3888281", "0.3886272", "0.3884512", "0.3878915", "0.38758492", "0.38708982", "0.3870489", "0.38612175", "0.38557294", "0.3853118", "0.38515374" ]
0.8471336
0
ToTextPatternInfo converts a an atomic query to internal values that drive text search. An atomic query is a Basic query where the Pattern is either nil, or comprises only one Pattern node (hence, an atom, and not an expression). See TextPatternInfo for the values it computes and populates.
func ToTextPatternInfo(q query.Basic, p Protocol, transform query.BasicPass) *TextPatternInfo { q = transform(q) // Handle file: and -file: filters. filesInclude, filesExclude := IncludeExcludeValues(q, query.FieldFile) // Handle lang: and -lang: filters. langInclude, langExclude := IncludeExcludeValues(q, query.FieldLang) filesInclude = append(filesInclude, mapSlice(langInclude, langToFileRegexp)...) filesExclude = append(filesExclude, mapSlice(langExclude, langToFileRegexp)...) filesReposMustInclude, filesReposMustExclude := IncludeExcludeValues(q, query.FieldRepoHasFile) selector, _ := filter.SelectPathFromString(q.FindValue(query.FieldSelect)) // Invariant: select is validated count := count(q, p) // Ugly assumption: for a literal search, the IsRegexp member of // TextPatternInfo must be set true. The logic assumes that a literal // pattern is an escaped regular expression. isRegexp := q.IsLiteral() || q.IsRegexp() var pattern string if p, ok := q.Pattern.(query.Pattern); ok { if q.IsLiteral() { // Escape regexp meta characters if this pattern should be treated literally. pattern = regexp.QuoteMeta(p.Value) } else { pattern = p.Value } } if q.Pattern == nil { // For compatibility: A nil pattern implies isRegexp is set to // true. This has no effect on search logic. isRegexp = true } negated := false if p, ok := q.Pattern.(query.Pattern); ok { negated = p.Negated } return &TextPatternInfo{ // Values dependent on pattern atom. IsRegExp: isRegexp, IsStructuralPat: q.IsStructural(), IsCaseSensitive: q.IsCaseSensitive(), FileMatchLimit: int32(count), Pattern: pattern, IsNegated: negated, // Values dependent on parameters. IncludePatterns: filesInclude, ExcludePattern: unionRegexp(filesExclude), FilePatternsReposMustInclude: filesReposMustInclude, FilePatternsReposMustExclude: filesReposMustExclude, Languages: langInclude, PathPatternsAreCaseSensitive: q.IsCaseSensitive(), CombyRule: q.FindValue(query.FieldCombyRule), Index: q.Index(), Select: selector, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func make_pattern_text(T int, // size of text\n\tP int, // size of pattern.\n\tN int, // number of pattern repetitions\n) ([]byte, []byte) {\n\n\tM := int(T / P) // Max # patterns that fit in text\n\tif M < N {\n\t\tpanic(fmt.Sprintf(\"make_pattern_text M < N. T=%d,P=%d,N=%d,M=%d\", T, P, N, M))\n\t}\n\tD := int(M / N) // Distance between filled pattern slots\n\n\ttext := make([]byte, T, T) // String to be indexed and searched\n\tpattern := make([]byte, P, P) // Substring to search for\n\tunpattern := make([]byte, P, P)\n\n\tfor j := 0; j < P; j++ {\n\t\tpattern[j] = byte(j%0xFD + 1)\n\t}\n\tfor j := 0; j < P-1; j++ {\n\t\tunpattern[j] = byte(j%0xFD + 1)\n\t}\n\tunpattern[P-1] = 0xFF\n\n\t// for j := P - 10; j < P; j++ {\n\t// \tfmt.Printf(\"%5d: %3d\\n\", j, pattern[j])\n\t// }\n\n\tn := 0\n\tfor m := 0; m < M; m++ {\n\t\tt0 := m * P\n\t\tvar pat []byte\n\t\tif m%D == 0 && n < N {\n\t\t\tpat = pattern\n\t\t\tn++\n\t\t} else {\n\t\t\tpat = unpattern\n\t\t}\n\t\tfor j := 0; j < P; j++ {\n\t\t\ttext[t0+j] = pat[j]\n\t\t}\n\t}\n\n\treturn pattern, text\n}", "func Pattern(query []byte) []byte {\n\ttokenizer := sqlparser.NewStringTokenizer(string(query))\n\tbuf := bytes.Buffer{}\n\tl := make([]byte, 4)\n\tfor {\n\t\ttyp, val := tokenizer.Scan()\n\t\tswitch typ {\n\t\tcase sqlparser.ID: //table, database, variable & ... names\n\t\t\tbuf.Write(val)\n\t\tcase 0: //End of query\n\t\t\treturn buf.Bytes()\n\t\tdefault:\n\t\t\tbinary.BigEndian.PutUint32(l, uint32(typ))\n\t\t\tbuf.Write(l)\n\t\t}\n\t}\n}", "func (plan *Plan) AsText() *PlanAsText {\n\tresult := NewPlanAsText()\n\n\t// apply the plan and capture actions as text\n\tplan.applyInternal(WrapSequential(func(act Interface) error {\n\t\tresult.Actions = append(result.Actions, act.DescribeChanges())\n\t\treturn nil\n\t}), NewApplyResultUpdaterImpl())\n\n\treturn result\n}", "func NewTextQuery() *TextQuery {\n\treturn &TextQuery{\n\t\tIn: make([]string, 0),\n\t}\n}", "func (o TransformationPtrOutput) Query() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Transformation) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Query\n\t}).(pulumi.StringPtrOutput)\n}", "func (bp *binaryPattern) toPattern() (p *Pattern) {\n\tp = new(Pattern)\n\n\t// Convert headers\n\tn := 0\n\tfor bp.version_string[n] != byte(0x0) {\n\t\tn++\n\t}\n\tp.version = string(bp.version_string[:n])\n\tp.tempo = bp.tempo\n\n\t// Convert tracks\n\tp.tracks = make(map[int]Track, len(bp.tracks))\n\tp.printOrder = make([]int, 0)\n\tfor _, bt := range bp.tracks {\n\t\tvar t Track\n\t\tt.name = string(bt.name[:int(bt.strlen)])\n\t\tfor i := 0; i < len(t.steps); i++ {\n\t\t\tt.steps[i] = bt.steps[i] == 0x1\n\t\t}\n\n\t\tvar id int = int(bt.id)\n\t\tp.tracks[id] = t\n\t\tp.printOrder = append(p.printOrder, id)\n\t}\n\treturn p\n}", "func GetTextFromQuery(body string, query string) string {\n\tdoc, err := goquery.NewDocumentFromReader(strings.NewReader(body))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttextFromQuery := \"\"\n\t// Find the requested item\n\tdoc.Find(query).Each(func(i int, s *goquery.Selection) {\n\t\t// For each item found, get the title and absolute link\n\t\ttextFromQuery = s.Text()\n\t})\n\n\treturn textFromQuery\n}", "func Pattern(query string) []byte {\n\ttokenizer := sqlparser.NewStringTokenizer(query)\n\tbuf := bytes.Buffer{}\n\tl := make([]byte, 4)\n\tfor {\n\t\ttyp, val := tokenizer.Scan()\n\t\tswitch typ {\n\t\tcase sqlparser.ID: //table, database, variable & ... names\n\t\t\tbuf.Write(val)\n\t\tcase 0: //End of query\n\t\t\treturn buf.Bytes()\n\t\tdefault:\n\t\t\tbinary.BigEndian.PutUint32(l, uint32(typ))\n\t\t\tbuf.Write(l)\n\t\t}\n\t}\n}", "func NotifyTextProcess(stBodyInfo public.BodyInfo, pstNotifyText *public.NotifyText) {\n\n\t(*pstNotifyText).Msgtype = \"text\"\n\tif stBodyInfo.ObjectAttributes.Status == \"success\" {\n\t\t(*pstNotifyText).Text.Content += \"恭喜你CI成功了!\" + \"\\n\"\n\t} else {\n\t\t(*pstNotifyText).Text.Content += stBodyInfo.User.Name + \"的CI失败了!\" + \"\\n\"\n\t}\n\n\tfmt.Println(\"Username : \", stBodyInfo.User.Username)\n\tfmt.Println(\"mobile : \", public.MapUsername2Mobile[stBodyInfo.User.Username])\n\t(*pstNotifyText).At.AtMobiles = append((*pstNotifyText).At.AtMobiles, public.MapUsername2Mobile[stBodyInfo.User.Username])\n\tfmt.Println(\"mobile : \", (*pstNotifyText).At.AtMobiles)\n\n\tfmt.Println(\"ref : \", stBodyInfo.ObjectAttributes.Ref)\n\tfmt.Println(\"env : \", public.MapRxQueue[stBodyInfo.ObjectAttributes.ID])\n\t/* notify to all if master branch */\n\tif stBodyInfo.ObjectAttributes.Ref == \"master\" && (public.MapRxQueue[stBodyInfo.ObjectAttributes.ID] == \"NEBULAE-DEV-A\" || public.MapRxQueue[stBodyInfo.ObjectAttributes.ID] == \"\") {\n\t\t\t(*pstNotifyText).At.IsAtAll = \"true\"\n\t} else {\n\t\t/* notify to all if pipeline failed */\n\t\tif stBodyInfo.ObjectAttributes.Status == \"success\" {\n\t\t\t(*pstNotifyText).At.IsAtAll = \"false\"\n\t\t} else {\n\t\t\t(*pstNotifyText).At.IsAtAll = \"true\"\n\t\t}\n\t}\n\n\tfmt.Println(\"+++++++++NotifyTextProcess++++++++++++++++\")\n\tfmt.Println(*pstNotifyText)\n\tfmt.Println(\"++++++++++++++++++++++++++++++++++++++++\")\n}", "func (o TransformationOutput) Query() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v Transformation) *string { return v.Query }).(pulumi.StringPtrOutput)\n}", "func (m *QueryCondition) GetQueryText()(*string) {\n val, err := m.GetBackingStore().Get(\"queryText\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (t *Binary) Query() string {\n\tif t == nil {\n\t\treturn \"''\"\n\t}\n\treturn `'` + string(*t) + `'`\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func NewQueryRuleInfo() *QueryRuleInfo {\n\tqri := &QueryRuleInfo{\n\t\tqueryRulesMap: map[string]*QueryRules{},\n\t}\n\treturn qri\n}", "func (o WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementPtrOutput) TextTransformations() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementTextTransformationArrayOutput)\n}", "func QueryText(text string) []string {\n\tres, err := db.Query(\"SELECT DISTINCT filename FROM texts WHERE text like ?\", \"%\"+text+\"%\")\n\tdefer res.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn getFilenamesFromRes(res)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexMatchStatementTextTransformationArrayOutput)\n}", "func (*XMLDocument) QueryCommandText(commandId string) (s string) {\n\tmacro.Rewrite(\"$_.queryCommandText($1)\", commandId)\n\treturn s\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementTextTransformationArrayOutput)\n}", "func FindQueryTextSearches(qMap *tokenizer.QueryMap) []QueryTextSearch {\n\tbsonMatch := make(bson.M)\n\tfor qType, qVal := range *qMap {\n\t\tswitch qType {\n\t\tcase \"lines\":\n\t\t\tlinesMap, ok := qVal.(map[string]int)\n\t\t\tif !ok || len(linesMap) != 1 {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfor linesOp, linesThreshold := range linesMap {\n\t\t\t\tbsonMatch[\"fileinfo.numlines\"] = bson.M{fmt.Sprintf(\"$%s\", linesOp): linesThreshold}\n\t\t\t}\n\n\t\tcase \"text\":\n\t\t\ttextMap, ok := qVal.(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tqTextRegex, ok := textMap[\"val\"].(string)\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tisRegex, ok := textMap[\"regex\"].(bool)\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif !isRegex {\n\t\t\t\tqTextRegex = regexp.QuoteMeta(qTextRegex)\n\t\t\t}\n\n\t\t\tbsonMatch[\"fileinfo.formatteddata\"] = bson.M{\"$regex\": qTextRegex, \"$options\": \"si\"}\n\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tsession, err := mgo.Dial(\"mongodb://localhost\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer session.Close()\n\n\tcollQueriesTextSearch := common.GetCollection(session, \"queries.textsearch\")\n\n\tvar results []QueryTextSearch\n\terr = collQueriesTextSearch.Find(bsonMatch).Sort(\"fileinfo.repositoryname fileinfo.filepath\").All(&results)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn results\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatement) []WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementXssMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatement) []WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementRegexMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatement) []WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexMatchStatementTextTransformationArrayOutput)\n}", "func main() {\n patFile, err := ioutil.ReadFile(\"patterns.txt\")\n if err != nil {\n log.Fatal(err)\n }\n textFile, err := ioutil.ReadFile(\"text.txt\")\n if err != nil {\n log.Fatal(err)\n }\n patterns := strings.Split(string(patFile), \" \")\n fmt.Printf(\"\\nRunning: Set Backward Oracle Matching algorithm.\\n\\n\")\n if debugMode==true { \n fmt.Printf(\"Searching for %d patterns/words:\\n\",len(patterns))\n }\n for i := 0; i < len(patterns); i++ {\n if (len(patterns[i]) > len(textFile)) {\n log.Fatal(\"There is a pattern that is longer than text! Pattern number:\", i+1)\n }\n if debugMode==true { \n fmt.Printf(\"%q \", patterns[i])\n }\n }\n if debugMode==true { \n fmt.Printf(\"\\n\\nIn text (%d chars long): \\n%q\\n\\n\",len(textFile), textFile)\n }\n sbom(string(textFile), patterns)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatement) []WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementSqliMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func toText(t *Table) []*textRow {\n\tvar textRows []*textRow\n\tswitch len(t.Configs) {\n\tcase 1:\n\t\ttextRows = append(textRows, newTextRow(\"name\", t.Metric))\n\tcase 2:\n\t\ttextRows = append(textRows, newTextRow(\"name\", \"old \"+t.Metric, \"new \"+t.Metric, \"delta\"))\n\tdefault:\n\t\trow := newTextRow(\"name \\\\ \" + t.Metric)\n\t\tfor _, config := range t.Configs {\n\t\t\trow.cols = append(row.cols, config)\n\t\t\tif t.OldNewDelta {\n\t\t\t\trow.cols = append(row.cols, \"delta\", \"note\")\n\t\t\t}\n\t\t}\n\t\ttextRows = append(textRows, row)\n\t}\n\n\tvar group string\n\n\tfor _, row := range t.Rows {\n\t\tif row.Group != group {\n\t\t\tgroup = row.Group\n\t\t\ttextRows = append(textRows, newTextRow(group))\n\t\t}\n\t\ttext := newTextRow(row.Benchmark)\n\t\tfor i, m := range row.Metrics {\n\t\t\ttext.cols = append(text.cols, m.Format(row.Scaler))\n\t\t\tif t.OldNewDelta && (len(row.Metrics) > 2 || i > 0) {\n\t\t\t\tdelta := row.Deltas[i]\n\t\t\t\tif delta == \"~\" {\n\t\t\t\t\tdelta = \"~ \"\n\t\t\t\t}\n\t\t\t\ttext.cols = append(text.cols, delta)\n\t\t\t\ttext.cols = append(text.cols, row.Notes[i])\n\t\t\t}\n\t\t}\n\t\ttextRows = append(textRows, text)\n\t}\n\tfor _, r := range textRows {\n\t\tr.trim()\n\t}\n\treturn textRows\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatement) []WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementSqliMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatement) []WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementOrStatementStatementXssMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementXssMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementXssMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementXssMatchStatement) []WebAclRuleStatementNotStatementStatementXssMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementXssMatchStatementTextTransformationArrayOutput)\n}", "func CommandFromText(text string) (command Command, err error) {\n\t// First test if it's a regexp literal\n\tmatch := LiteralRegexp.FindStringSubmatch(text)\n\tif len(match) == 3 {\n\t\tcommand.Type = CmdLiteral\n\t\tcommand.Value = match[1]\n\t\tcommand.Comment = match[2]\n\t\treturn command, nil\n\t}\n\n\tmatch = CommandRegexp.FindStringSubmatch(text)\n\n\tif len(match) != 4 {\n\t\treturn Command{}, fmt.Errorf(\"Invalid command syntax: %s\", text)\n\t}\n\n\tcommand.Params = match[2]\n\tcommand.Comment = match[3]\n\n\tswitch match[1] {\n\tcase \"XExpression\":\n\t\tcommand.Type = CmdXExpression\n\tcase \"Alias\":\n\t\tcommand.Type = CmdAliasDefinition\n\tcase \"Description\":\n\t\tcommand.Type = CmdDescription\n\tcase \"Example\":\n\t\tcommand.Type = CmdExample\n\tcase \"Match\":\n\t\tcommand.Type = CmdExampleMatch\n\tcase \"Non Match\":\n\t\tcommand.Type = CmdExampleNonMatch\n\tcase \"Select\":\n\t\tcommand.Type = CmdSelect\n\tcase \"Case\":\n\t\tcommand.Type = CmdCase\n\tcase \"Group\":\n\t\tcommand.Type = CmdGroup\n\tdefault:\n\t\tcommand.Type = CmdAliasCall\n\t\tcommand.Value = match[1]\n\t}\n\n\treturn command, nil\n}", "func (client *Client) QueryContactInfo(request *QueryContactInfoRequest) (response *QueryContactInfoResponse, err error) {\n\tresponse = CreateQueryContactInfoResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (o WebAclRuleStatementNotStatementStatementRegexMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementRegexMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementRegexMatchStatement) []WebAclRuleStatementNotStatementStatementRegexMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementRegexMatchStatementTextTransformationArrayOutput)\n}", "func text2matrix(set noteMap, figures map[string]figure, txt []string) (channels, notes matrix, figuremap map[int][]midiFigure) {\n\tfiguremap = make(map[int][]midiFigure)\n\tfor _, line := range txt {\n\t\tvar chanV, noteV []int\n\t\tlane := strings.Split(strings.TrimSpace(line), laneSplitStr)\n\t\t// use our own index because we need to be able to decrease it\n\t\t// if we encounter unwanted (uncounted) characters\n\t\tvar i = -1\n\t\tfor _, elem := range lane {\n\t\t\ti++\n\t\t\tif elem == \"\" {\n\t\t\t\ti--\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfirst, rest := splitFirstRune(elem)\n\t\t\tif first == figurePrefix {\n\t\t\t\t// generate a micro pattern\n\t\t\t\tfiguremap[i] = append(figuremap[i], translateFigure(set, figures, rest))\n\t\t\t\t// also generate an empty single note\n\t\t\t\tchanV = append(chanV, 0)\n\t\t\t\tnoteV = append(noteV, 0)\n\t\t\t} else {\n\t\t\t\t// generate a normal note\n\t\t\t\tc, n := translateKit(set, elem)\n\t\t\t\tchanV = append(chanV, c)\n\t\t\t\tnoteV = append(noteV, n)\n\t\t\t}\n\t\t}\n\t\tchannels = append(channels, row(chanV))\n\t\tnotes = append(notes, row(noteV))\n\t}\n\tdebugf(\"text2matrix(): figuremap: %v\", figuremap)\n\treturn\n}", "func (o WebAclRuleStatementNotStatementStatementSqliMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementSqliMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementSqliMatchStatement) []WebAclRuleStatementNotStatementStatementSqliMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementSqliMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (app *patternMatchAdapter) ToPatternMatch(parsed parsers.PatternMatch) (PatternMatch, error) {\n\tpattern := parsed.Pattern()\n\tbuilder := app.builder.Create().WithPattern(pattern)\n\n\tlabels := parsed.Labels()\n\tif labels.HasEnterLabel() {\n\t\tenterLabel := labels.EnterLabel()\n\t\tbuilder.WithEnterLabel(enterLabel)\n\t}\n\n\tif labels.HasExitLabel() {\n\t\texitLabel := labels.ExitLabel()\n\t\tbuilder.WithExitLabel(exitLabel)\n\t}\n\n\treturn builder.Now()\n}", "func (s *SimpleTextSource) DiagnosticInfo() (Result, error) {\n\tout, err := s.toCall()\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\treturn Result{\n\t\tExt: s.ext,\n\t\tData: out,\n\t}, nil\n}", "func (t *Trie) Query(text string) (sanitize string, keywords []string, exist bool) {\n\tchars := []rune(text)\n\ttxtLen := len(chars)\n\n\tif txtLen == 0 {\n\t\treturn\n\t}\n\n\tnode := t.root\n\tt.mu.RLock()\n\tfor i := 0; i < txtLen; i++ {\n\t\tif _, ok := node.children[chars[i]]; !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tnode = node.children[chars[i]]\n\t\tfor j := i + 1; j < txtLen; j++ {\n\t\t\tif _, ok := node.children[chars[j]]; !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tnode = node.children[chars[j]]\n\t\t\tif node.end {\n\t\t\t\tkeywords = append(keywords, string(chars[i:j+1]))\n\t\t\t\tt.replaceWithMask(chars, i, j+1)\n\t\t\t}\n\t\t}\n\t\tnode = t.root\n\t}\n\n\tif len(keywords) > 0 {\n\t\texist = true\n\t}\n\tsanitize = string(chars)\n\tt.mu.RUnlock()\n\n\treturn\n}", "func NewContractInfoQuery() *ContractInfoQuery {\n\tquery := _NewQuery(true)\n\n\tquery.SetMaxQueryPayment(NewHbar(2))\n\n\treturn &ContractInfoQuery{\n\t\tQuery: query,\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (r RuleRegex) MarshalText() ([]byte, error) {\n\tif r.Pattern != nil {\n\t\treturn []byte(*r.Pattern), nil\n\t}\n\treturn nil, nil\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementOutput) TextTransformations() WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func constructTree(query cqr.CommonQueryRepresentation, index InvertedIndex, seen map[uint32]logicalTreeNode) (logicalTreeNode, map[uint32]logicalTreeNode, error) {\n\tif seen == nil {\n\t\tseen = make(map[uint32]logicalTreeNode)\n\t}\n\tswitch q := query.(type) {\n\tcase cqr.Keyword:\n\t\t// Return a seen atom.\n\t\tif atom, ok := seen[HashCQR(q)]; ok {\n\t\t\treturn atom, seen, nil\n\t\t}\n\n\t\tvar docs []string\n\n\t\tq.QueryString = strings.Join(strings.Fields(q.QueryString), \" \")\n\n\t\t// Perform a phase match.\n\t\tif strings.Contains(q.QueryString, \" \") {\n\t\t\tterms := strings.Split(q.QueryString, \" \")\n\t\t\tvar atoms []logicalTreeNode\n\t\t\tfor _, field := range q.Fields {\n\t\t\t\tfor _, term := range terms {\n\t\t\t\t\tdocIDs := index.DocumentIDs(field, term)\n\t\t\t\t\td := make(Documents, len(docIDs))\n\t\t\t\t\tfor _, docID := range docIDs {\n\t\t\t\t\t\td = append(d, index.DocumentMapping[docID])\n\t\t\t\t\t}\n\t\t\t\t\ta := NewAtom(cqr.NewKeyword(term, field), d)\n\t\t\t\t\tseen[a.Hash] = a\n\t\t\t\t\tatoms = append(atoms, a)\n\t\t\t\t}\n\t\t\t}\n\t\t\top := NewAdjOperator(1, true, &index)\n\t\t\tcombined, err := op.Combine(atoms)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, seen, err\n\t\t\t}\n\t\t\tdocs = append(docs, combined...)\n\t\t} else { // Just get the documents for a term.\n\t\t\tfor _, field := range q.Fields {\n\t\t\t\tfor _, docID := range index.DocumentIDs(field, q.QueryString) {\n\t\t\t\t\tdocs = append(docs, index.DocumentMapping[docID])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Create the new atom add it to the seen list.\n\t\ta := NewAtom(q, docs)\n\t\tseen[a.Hash] = a\n\t\treturn a, seen, nil\n\tcase cqr.BooleanQuery:\n\t\tvar operator Operator\n\t\tswitch strings.ToLower(q.Operator) {\n\t\tcase \"or\":\n\t\t\toperator = OrOperator\n\t\tcase \"and\":\n\t\t\toperator = AndOperator\n\t\tcase \"not\":\n\t\t\toperator = NotOperator\n\t\tcase \"adj\":\n\t\t\tvar n float64\n\t\t\tvar inOrder bool\n\t\t\tif distance, ok := q.Options[\"distance\"].(float64); ok {\n\t\t\t\tn = distance\n\t\t\t}\n\t\t\tif o, ok := q.Options[\"in_order\"].(bool); ok {\n\t\t\t\tinOrder = o\n\t\t\t}\n\t\t\toperator = NewAdjOperator(int32(n), inOrder, &index)\n\t\tdefault:\n\t\t\toperator = OrOperator\n\t\t}\n\n\t\t// Otherwise, we can just perform the operation with a typical operator.\n\t\tclauses := make([]logicalTreeNode, len(q.Children))\n\t\tfor i, child := range q.Children {\n\t\t\tvar err error\n\t\t\tclauses[i], seen, err = constructTree(child, index, seen)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, seen, err\n\t\t\t}\n\t\t}\n\t\tc, err := NewCombinator(q, operator, clauses...)\n\t\treturn c, seen, err\n\t}\n\treturn nil, nil, errors.New(\"supplied query is not supported\")\n}", "func (o WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementOutput) TextTransformations() WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementRegexMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementOrStatementStatementRegexMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementRegexMatchStatement) []WebAclRuleStatementNotStatementStatementOrStatementStatementRegexMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementRegexMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatement) []WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementSqliMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementOutput) TextTransformations() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatement) []WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatement) []WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementRegexMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatement) []WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementXssMatchStatementTextTransformationArrayOutput)\n}", "func (s *SpeechRecognitionResultText) TypeInfo() tdp.Type {\n\ttyp := tdp.Type{\n\t\tName: \"speechRecognitionResultText\",\n\t\tID: SpeechRecognitionResultTextTypeID,\n\t}\n\tif s == nil {\n\t\ttyp.Null = true\n\t\treturn typ\n\t}\n\ttyp.Fields = []tdp.Field{\n\t\t{\n\t\t\tName: \"Text\",\n\t\t\tSchemaName: \"text\",\n\t\t},\n\t}\n\treturn typ\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementByteMatchStatementTextTransformationArrayOutput)\n}", "func doTextProcessor(p proc.TextProcessor, label string, c *Chunk, msg string) *Chunk {\n\tres := p.Run(c.Data)\n\n\tfor _, match := range res.Matches {\n\t\tformattedMsg := fmt.Sprintf(msg)\n\t\tc.Matches = append(c.Matches, NewMatch(match.Match, label, match.Indices, formattedMsg))\n\t\tc.Score += 1\n\t}\n\n\treturn c\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementByteMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatement) []WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementByteMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementByteMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatement) []WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementSqliMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementXssMatchStatement) []WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementTextTransformationArrayOutput)\n}", "func NewTextCore(enc zapcore.Encoder, ws zapcore.WriteSyncer, enab zapcore.LevelEnabler) zapcore.Core {\n\treturn &textIOCore{\n\t\tLevelEnabler: enab,\n\t\tenc: enc,\n\t\tout: ws,\n\t}\n}", "func (a *atom) MarshalText() ([]byte, error) {\n\tif a == nil {\n\t\treturn nil, nil\n\t}\n\treturn []byte(a.Raw()), nil\n}", "func (a ASTNode) Text() string {\n\tif a.t != tval {\n\t\tpanic(ConfErr{a.pos, errors.New(\"Not a basic value\")})\n\t}\n\tv := a.val.(string)\n\tif strings.HasPrefix(v, \"\\\"\") {\n\t\tu, err := strconv.Unquote(v)\n\t\tif err != nil {\n\t\t\tpanic(ConfErr{a.pos, err})\n\t\t}\n\t\tv = u\n\t}\n\treturn v\n}", "func (client *Client) Query(text string) ([]string, error) {\n\tif ContainsCh(text) { // 汉字\n\t\treturn client.CliCh.Query(text, AND)\n\t}\n\treturn client.CliEn.Query(text, AND)\n\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementTextTransformation {\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementXssMatchStatementTextTransformationArrayOutput)\n}", "func (sqt *SQLQueryTranslator) Translate(query *query.QueryCypher) (*SQLTranslation, error) {\n\tconstrainedNodes := make(map[int]bool)\n\n\tfilterExpressions := AndOrExpression{And: true}\n\twhereExpressions := AndOrExpression{And: true}\n\tfor _, x := range query.QuerySinglePartQuery.QueryMatches {\n\t\tparser := NewPatternParser(&sqt.QueryGraph)\n\t\tfor _, y := range x.PatternElements {\n\t\t\terr := parser.ParsePatternElement(&y, MatchScope)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tif x.Where != nil {\n\t\t\twhereVisitor := NewQueryWhereVisitor(&sqt.QueryGraph)\n\t\t\twhereExpression, err := whereVisitor.ParseExpression(x.Where)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor _, v := range whereVisitor.Variables {\n\t\t\t\ttypeAndIndex, err := sqt.QueryGraph.FindVariable(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tconstrainedNodes[typeAndIndex.Index] = true\n\t\t\t}\n\n\t\t\t// We only append the expression if it's not empty\n\t\t\tif whereExpression != \"\" {\n\t\t\t\twhereExpressions.Children = append(whereExpressions.Children,\n\t\t\t\t\tAndOrExpression{And: true, Expression: whereExpression})\n\t\t\t}\n\t\t}\n\t}\n\n\t// Build the constraints for the patterns in MATCH clause\n\texpr, f, err := buildSQLConstraintsFromPatterns(&sqt.QueryGraph, constrainedNodes, MatchScope)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to build SQL constraints from patterns in the MATCH clause: %v\", err)\n\t}\n\tfrom := f\n\n\tif expr.Expression != \"\" || len(expr.Children) > 0 {\n\t\tfilterExpressions.Children = append(filterExpressions.Children, *expr)\n\t}\n\n\tif whereExpressions.Expression != \"\" || len(whereExpressions.Children) > 0 {\n\t\tfilterExpressions.Children = append(filterExpressions.Children, whereExpressions)\n\t}\n\n\tprojections := make([]SQLProjection, 0)\n\tprojectionTypes := make([]Projection, 0)\n\tgroupByIndices := []int{}\n\tgroupByRequired := false\n\tvariableIndices := []int{}\n\n\tfor i, p := range query.QuerySinglePartQuery.ProjectionBody.ProjectionItems {\n\t\tprojectionVisitor := NewProjectionVisitor(&sqt.QueryGraph)\n\t\terr := projectionVisitor.ParseExpression(&p.Expression)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, proj := range projectionVisitor.Projections {\n\t\t\tif proj.Function != \"\" {\n\t\t\t\tprojections = append(projections, SQLProjection{\n\t\t\t\t\tFunction: &SQLFunction{Name: proj.Function, Distinct: proj.Distinct},\n\t\t\t\t\tVariable: proj.Variable})\n\t\t\t\tgroupByRequired = true\n\t\t\t} else if proj.Variable != \"\" {\n\t\t\t\tprojections = append(projections, SQLProjection{Variable: proj.Variable})\n\t\t\t\tvariableIndices = append(variableIndices, i)\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"Unable to detect type of projection\")\n\t\t\t}\n\t\t}\n\n\t\tprojectionTypes = append(projectionTypes, Projection{\n\t\t\tAlias: p.Alias,\n\t\t\tExpressionType: projectionVisitor.ExpressionType,\n\t\t})\n\t}\n\t// If group by is required, we group by all variables except the aggregation functions\n\tif groupByRequired {\n\t\tgroupByIndices = variableIndices\n\t}\n\n\tlimit := 0\n\tif query.QuerySinglePartQuery.ProjectionBody.Limit != nil {\n\t\tlimitVisitor := NewQueryLimitVisitor(&sqt.QueryGraph)\n\t\terr := limitVisitor.ParseExpression(\n\t\t\tquery.QuerySinglePartQuery.ProjectionBody.Limit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlimit = int(limitVisitor.Limit)\n\t}\n\n\toffset := 0\n\tif query.QuerySinglePartQuery.ProjectionBody.Skip != nil {\n\t\tif limit == 0 {\n\t\t\treturn nil, fmt.Errorf(\"SKIP must be used in combination with limit\")\n\t\t}\n\t\tskipVisitor := NewQuerySkipVisitor(&sqt.QueryGraph)\n\t\terr := skipVisitor.ParseExpression(\n\t\t\tquery.QuerySinglePartQuery.ProjectionBody.Skip)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\toffset = int(skipVisitor.Skip)\n\t}\n\n\tvar sqlQuery string\n\n\tinnerSQL := SQLStructure{\n\t\tDistinct: query.QuerySinglePartQuery.ProjectionBody.Distinct,\n\t\tProjections: projections,\n\t\tFromEntries: from,\n\t\tWhereExpression: filterExpressions,\n\t\tGroupByIndices: groupByIndices,\n\t\tLimit: limit,\n\t\tOffset: offset,\n\t}\n\n\tsqlQuery, err = buildSQLSelect(innerSQL)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &SQLTranslation{\n\t\tQuery: sqlQuery,\n\t\tProjectionTypes: projectionTypes,\n\t}, nil\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o TransformationResponsePtrOutput) Query() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TransformationResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Query\n\t}).(pulumi.StringPtrOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchOutput) QueryString() WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatch) *WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementPtrOutput) TextTransformations() WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v *WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementXssMatchStatement) []WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementTextTransformation {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementNotStatementStatementXssMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput)\n}", "func (q *TextQuery) GetQuery() interface{} {\n\treturn q\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchOutput) QueryString() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatch) *WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementTextTransformation {\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementRegexMatchStatementTextTransformationArrayOutput)\n}", "func (t *Tess) Text() string {\n\tcText := C.TessBaseAPIGetUTF8Text(t.tba)\n\tdefer C.free(unsafe.Pointer(cText))\n\ttext := C.GoString(cText)\n\treturn text\n}", "func Tconv(t *Type, flag FmtFlag) string", "func NewContractInfoQuery() *ContractInfoQuery {\n\theader := proto.QueryHeader{}\n\tquery := newQuery(true, &header)\n\tpb := proto.ContractGetInfoQuery{Header: &header}\n\tquery.pb.Query = &proto.Query_ContractGetInfo{\n\t\tContractGetInfo: &pb,\n\t}\n\n\tquery.SetMaxQueryPayment(NewHbar(2))\n\n\treturn &ContractInfoQuery{\n\t\tQuery: query,\n\t\tpb: &pb,\n\t}\n}", "func (o WebAclRuleStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementOutput) TextTransformations() WebAclRuleStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatement) []WebAclRuleStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformation {\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementNotStatementStatementOrStatementStatementRegexPatternSetReferenceStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementTextTransformation {\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementAndStatementStatementSqliMatchStatementTextTransformationArrayOutput)\n}", "func (o WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchOutput) QueryString() WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatch) *WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryString {\n\t\treturn v.QueryString\n\t}).(WebAclRuleStatementOrStatementStatementAndStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchQueryStringPtrOutput)\n}", "func (p *fsPath) AsPattern() *Pattern {\n\tif anew, ok := p.TryPattern(); !ok {\n\t\tpanic(\"newPattern: Match returned an ErrBadPattern-error!\")\n\t} else {\n\t\treturn anew\n\t}\n}", "func Text(expected, actual interface{}) Truth {\n\tmustBeCleanStart()\n\treturn Truth{\n\t\tValue:fmt.Sprintf(\"%v\", expected) == fmt.Sprintf(\"%v\", actual),\n\t\tDump:fmt.Sprintf(\"%#v vs. %#v\", expected, actual),\n\t}\n}", "func (o WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementOutput) TextTransformations() WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementTextTransformationArrayOutput {\n\treturn o.ApplyT(func(v WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatement) []WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementTextTransformation {\n\t\treturn v.TextTransformations\n\t}).(WebAclRuleStatementAndStatementStatementOrStatementStatementOrStatementStatementXssMatchStatementTextTransformationArrayOutput)\n}", "func (u *__Comment_Updater) Text_Like(val string) *__Comment_Updater {\n\tw := whereClause{}\n\tvar insWhere []interface{}\n\tinsWhere = append(insWhere, val)\n\tw.args = insWhere\n\tw.condition = \" Text LIKE \" + u.nextDollar()\n\tu.wheres = append(u.wheres, w)\n\n\treturn u\n}", "func (p PatternExprPair) Pattern() Pattern {\n\treturn p.pattern\n}" ]
[ "0.44653547", "0.40759063", "0.4058076", "0.40355238", "0.4020524", "0.4006181", "0.39993784", "0.39698073", "0.39609438", "0.3935596", "0.3901916", "0.39011815", "0.38950545", "0.38773555", "0.386563", "0.3861176", "0.38457578", "0.3833284", "0.3831979", "0.38072672", "0.38059607", "0.3785698", "0.37788945", "0.3776474", "0.37756595", "0.3773582", "0.37733933", "0.37631154", "0.3751946", "0.37518328", "0.37505874", "0.37477973", "0.37477848", "0.3747213", "0.37419933", "0.37331462", "0.37311473", "0.37265804", "0.3720628", "0.37181556", "0.3713512", "0.37000003", "0.36846474", "0.36694893", "0.36644828", "0.36610505", "0.36586842", "0.36575595", "0.36566955", "0.36561942", "0.36421025", "0.36397898", "0.36379042", "0.36341336", "0.3626637", "0.36217117", "0.36137027", "0.36128157", "0.3612304", "0.36090487", "0.3608861", "0.3607088", "0.36038905", "0.3602391", "0.35976928", "0.35939234", "0.35910878", "0.35886663", "0.35829023", "0.358007", "0.35786596", "0.3575389", "0.3574612", "0.35648808", "0.35616028", "0.3559071", "0.3552", "0.35490227", "0.3547422", "0.35468718", "0.35395756", "0.3538929", "0.3538743", "0.3537005", "0.35357162", "0.35342938", "0.35244808", "0.3519153", "0.35176504", "0.35158336", "0.3514176", "0.3508268", "0.35077104", "0.35076264", "0.35007164", "0.3497795", "0.34919974", "0.34915447", "0.349015", "0.34858212" ]
0.7166795
0
ReadResponse reads a server response into the received o.
func (o *AddRemoteRDSNodeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewAddRemoteRDSNodeOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil default: result := NewAddRemoteRDSNodeDefault(response.Code()) if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } if response.Code()/100 == 2 { return result, nil } return nil, result } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *ResourceHandler) ReadResponse(dataOut unsafe.Pointer, bytesToRead int32, bytesRead *int32, callback *Callback) int32 {\n\treturn lookupResourceHandlerProxy(d.Base()).ReadResponse(d, dataOut, bytesToRead, bytesRead, callback)\n}", "func (o *GetServerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetServerOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *InteractionBindReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewInteractionBindOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewInteractionBindNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 500:\n\t\tresult := NewInteractionBindInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *InteractionUnbindReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewInteractionUnbindOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewInteractionUnbindNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 500:\n\t\tresult := NewInteractionUnbindInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (r *ResponseReader) ReadResponse(req *Request) (res *Response, err error) {\n\tres = CreateEmptyResponse(req)\n\t_, err = readFirstLine(r, res)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = readHeaders(r, res)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t_, err = readBodyContent(r, res)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn res, nil\n}", "func (c *Conn) ReadResponse(rmsg *Response) error {\n\tdata, err := c.ReadDataUnit()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcolor.Printf(\"@{c}<!-- RESPONSE -->\\n%s\\n\\n\", string(data))\n\terr = xml.Unmarshal(data, rmsg)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// color.Fprintf(os.Stderr, \"@{y}%s\\n\", spew.Sprintf(\"%+v\", msg))\n\tif len(rmsg.Results) != 0 {\n\t\tr := rmsg.Results[0]\n\t\tif r.IsError() {\n\t\t\treturn r\n\t\t}\n\t}\n\treturn nil\n}", "func (o *VerifyConnectionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewVerifyConnectionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *GetAvailableReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetAvailableOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *ClosePositionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewClosePositionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewClosePositionBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 401:\n\t\tresult := NewClosePositionUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewClosePositionNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 405:\n\t\tresult := NewClosePositionMethodNotAllowed()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *DescribeServerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewDescribeServerOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewDescribeServerBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewDescribeServerNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 409:\n\t\tresult := NewDescribeServerConflict()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewDescribeServerInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *GetServerSessionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetServerSessionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetServerSessionBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewGetServerSessionUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetServerSessionNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewGetServerSessionInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested GET /dsmcontroller/namespaces/{namespace}/servers/{podName}/session returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (o *StartReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewStartOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (resp *PharosResponse) readResponse() {\n\tif !resp.hasBeenRead && resp.Response != nil && resp.Response.Body != nil {\n\t\tresp.data, resp.Error = ioutil.ReadAll(resp.Response.Body)\n\t\tresp.Response.Body.Close()\n\t\tresp.hasBeenRead = true\n\t}\n}", "func (o *HelloWorldReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewHelloWorldOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewHelloWorldBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewHelloWorldInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (reader *BasicRpcReader) ReadResponse(r io.Reader, method string, requestID int32, resp proto.Message) error {\n\trrh := &hadoop.RpcResponseHeaderProto{}\n\terr := readRPCPacket(r, rrh, resp)\n\tif err != nil {\n\t\treturn err\n\t} else if int32(rrh.GetCallId()) != requestID {\n\t\treturn errors.New(\"unexpected sequence number\")\n\t} else if rrh.GetStatus() != hadoop.RpcResponseHeaderProto_SUCCESS {\n\t\treturn &NamenodeError{\n\t\t\tmethod: method,\n\t\t\tmessage: rrh.GetErrorMsg(),\n\t\t\tcode: int(rrh.GetErrorDetail()),\n\t\t\texception: rrh.GetExceptionClassName(),\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o *UpdateAntivirusServerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewUpdateAntivirusServerNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tresult := NewUpdateAntivirusServerDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *HasEventsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewHasEventsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewHasEventsUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewHasEventsForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetV2Reader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetV2OK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewGetV2InternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *SaveReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewSaveNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 500:\n\t\tresult := NewSaveInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *TestWriteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewTestWriteOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewTestWriteUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *AllConnectionsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewAllConnectionsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewAllConnectionsBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewAllConnectionsNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *SendDataToDeviceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewSendDataToDeviceOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewSendDataToDeviceBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewSendDataToDeviceInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *HealthNoopReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewHealthNoopOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PutOutOfRotationReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewPutOutOfRotationNoContent()\n\t\tresult.HttpResponse = response\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\terrorResult := kbcommon.NewKillbillError(response.Code())\n\t\tif err := consumer.Consume(response.Body(), &errorResult); err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, errorResult\n\t}\n}", "func (o *GetReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *StatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewStatusOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewStatusUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewStatusForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *ReplaceServerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewReplaceServerOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 202:\n\t\tresult := NewReplaceServerAccepted()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewReplaceServerBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewReplaceServerNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\tresult := NewReplaceServerDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func ReadResponse(r *bfe_bufio.Reader, req *Request) (*Response, error) {\n\ttp := textproto.NewReader(r)\n\tresp := &Response{\n\t\tRequest: req,\n\t}\n\n\t// Parse the first line of the response.\n\tline, err := tp.ReadLine()\n\tif err != nil {\n\t\tif err == io.EOF {\n\t\t\terr = io.ErrUnexpectedEOF\n\t\t}\n\t\treturn nil, err\n\t}\n\tf := strings.SplitN(line, \" \", 3)\n\tif len(f) < 2 {\n\t\treturn nil, &badStringError{\"malformed HTTP response\", line}\n\t}\n\treasonPhrase := \"\"\n\tif len(f) > 2 {\n\t\treasonPhrase = f[2]\n\t}\n\tresp.Status = f[1] + \" \" + reasonPhrase\n\tresp.StatusCode, err = strconv.Atoi(f[1])\n\tif err != nil {\n\t\treturn nil, &badStringError{\"malformed HTTP status code\", f[1]}\n\t}\n\n\tresp.Proto = f[0]\n\tvar ok bool\n\tif resp.ProtoMajor, resp.ProtoMinor, ok = ParseHTTPVersion(resp.Proto); !ok {\n\t\treturn nil, &badStringError{\"malformed HTTP version\", resp.Proto}\n\t}\n\n\t// Parse the response headers.\n\tmimeHeader, err := tp.ReadMIMEHeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Header = Header(mimeHeader)\n\n\tfixPragmaCacheControl(resp.Header)\n\n\terr = readTransfer(resp, r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (o *PostChatroomsChannelHashReadReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPostChatroomsChannelHashReadOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 403:\n\t\tresult := NewPostChatroomsChannelHashReadForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *TogglePacketGeneratorsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewTogglePacketGeneratorsCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *FrontPutBinaryReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewFrontPutBinaryOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *SystemPingReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewSystemPingOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 500:\n\t\tresult := NewSystemPingInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *SendDummyAlertReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewSendDummyAlertOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewSendDummyAlertBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewSendDummyAlertNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetViewsConnectionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetViewsConnectionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetViewsConnectionBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *SyncCopyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewSyncCopyOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewSyncCopyDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *PostPatientsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPostPatientsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewPostPatientsBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 405:\n\t\tresult := NewPostPatientsMethodNotAllowed()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (c *Conn) readResponse(res *response_) error {\n\terr := c.readDataUnit()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = IgnoreEOF(scanResponse.Scan(c.decoder, res))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif res.Result.IsError() {\n\t\treturn res.Result\n\t}\n\treturn nil\n}", "func (o *AllConnectionsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n switch response.Code() {\n \n case 200:\n result := NewAllConnectionsOK()\n if err := result.readResponse(response, consumer, o.formats); err != nil {\n return nil, err\n }\n return result, nil\n \n case 400:\n result := NewAllConnectionsBadRequest()\n if err := result.readResponse(response, consumer, o.formats); err != nil {\n return nil, err\n }\n return nil, result\n \n case 404:\n result := NewAllConnectionsNotFound()\n if err := result.readResponse(response, consumer, o.formats); err != nil {\n return nil, err\n }\n return nil, result\n \n default:\n return nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n }\n}", "func (o *GetMsgVpnReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetMsgVpnOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tresult := NewGetMsgVpnDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (r *Response) Read(p []byte) (n int, err error) {\n\n\tif r.Error != nil {\n\t\treturn -1, r.Error\n\t}\n\n\treturn r.RawResponse.Body.Read(p)\n}", "func (o *PostPciLinksMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewPostPciLinksMoidCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPostPciLinksMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *THSRAPIODFare2121Reader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewTHSRAPIODFare2121OK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 299:\n\t\tresult := NewTHSRAPIODFare2121Status299()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 304:\n\t\tresult := NewTHSRAPIODFare2121NotModified()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *PostGatewayConnectNetaddressReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewPostGatewayConnectNetaddressNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPostGatewayConnectNetaddressDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *DNSGetReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewDNSGetOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewDNSGetDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *GetGreetStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetGreetStatusOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PostAPIV2EventsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewPostAPIV2EventsNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPostAPIV2EventsBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 403:\n\t\tresult := NewPostAPIV2EventsForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *CreateAntivirusServerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewCreateAntivirusServerOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tresult := NewCreateAntivirusServerDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *PostCarsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewPostCarsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 405:\n\t\tresult := NewPostCarsMethodNotAllowed()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *LogReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewLogOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewLogNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *ChatGetConnectedReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewChatGetConnectedOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewChatGetConnectedBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 401:\n\t\tresult := NewChatGetConnectedUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewChatGetConnectedNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *WebModifyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewWebModifyOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 202:\n\t\tresult := NewWebModifyAccepted()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewWebModifyDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *GetHyperflexServerModelsMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetHyperflexServerModelsMoidOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetHyperflexServerModelsMoidNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\tresult := NewGetHyperflexServerModelsMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *KillQueryReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewKillQueryNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewKillQueryBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewKillQueryNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 422:\n\t\tresult := NewKillQueryUnprocessableEntity()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetProgressionViewReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetProgressionViewOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewGetProgressionViewBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *UpdateRackTopoReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUpdateRackTopoOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewUpdateRackTopoBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *UtilTestReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUtilTestOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *GetByUIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetByUIDOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetByUIDNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetMeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetMeOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewGetMeDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *Delete1Reader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewDelete1NoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewDelete1NotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *RevokeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewRevokeOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 401:\n\t\tresult := NewRevokeUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewRevokeNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PostGatewayDisconnectNetaddressReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewPostGatewayDisconnectNetaddressNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPostGatewayDisconnectNetaddressDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *GetProtocolsUsingGETReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetProtocolsUsingGETOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *DestroySessionUsingPOSTReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewDestroySessionUsingPOSTOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *CompleteTransactionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewCompleteTransactionNoContent()\n\t\tresult.HttpResponse = response\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\terrorResult := kbcommon.NewKillbillError(response.Code())\n\t\tif err := consumer.Consume(response.Body(), &errorResult); err != nil && err != io.EOF {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, errorResult\n\t}\n}", "func (o *GetMapNameEventsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetMapNameEventsOK(o.writer)\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetMapNameEventsNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *RecoveryReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewRecoveryOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewRecoveryInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetPeersReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetPeersOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 403:\n\t\tresult := NewGetPeersForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *InstallEventsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewInstallEventsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *SetMemoRequiredReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewSetMemoRequiredOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewSetMemoRequiredBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewSetMemoRequiredInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *UpdateRackTopoReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUpdateRackTopoOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewUpdateRackTopoBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewUpdateRackTopoNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewUpdateRackTopoInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *GetVoicesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetVoicesOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PatchHyperflexServerModelsMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewPatchHyperflexServerModelsMoidCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPatchHyperflexServerModelsMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *BounceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tresult := NewBounceDefault(response.Code())\n\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\treturn nil, err\n\t}\n\tif response.Code()/100 == 2 {\n\t\treturn result, nil\n\t}\n\treturn nil, result\n}", "func (o *PostHyperflexHxdpVersionsMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewPostHyperflexHxdpVersionsMoidCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPostHyperflexHxdpVersionsMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *GetObmsLibraryIdentifierReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetObmsLibraryIdentifierOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewGetObmsLibraryIdentifierNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\tresult := NewGetObmsLibraryIdentifierDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *DeleteApplianceRestoresMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewDeleteApplianceRestoresMoidOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewDeleteApplianceRestoresMoidNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\tresult := NewDeleteApplianceRestoresMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *UserQuerySessionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUserQuerySessionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewUserQuerySessionBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 500:\n\t\tresult := NewUserQuerySessionInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested GET /sessionbrowser/namespaces/{namespace}/gamesession returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (o *GetDiscoverReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetDiscoverOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (r *overwriteConsumerReader) ReadResponse(resp runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tif r.forStatusCode == ForAllStatusCodes || resp.Code() == r.forStatusCode {\n\t\treturn r.requestReader.ReadResponse(resp, r.consumer)\n\t}\n\n\treturn r.requestReader.ReadResponse(resp, consumer)\n}", "func (o *UnclaimTrafficFilterLinkIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUnclaimTrafficFilterLinkIDOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewUnclaimTrafficFilterLinkIDBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 500:\n\t\tresult := NewUnclaimTrafficFilterLinkIDInternalServerError()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *GetDebugRequestReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetDebugRequestOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewGetDebugRequestNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *ChangeaspecificSpeedDialReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 204:\n\t\tresult := NewChangeaspecificSpeedDialNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PostMemoryArraysMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewPostMemoryArraysMoidCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPostMemoryArraysMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (c *Client) readResponse(conn net.Conn) ([]byte, error) {\n\tif c.Timeout > 0 {\n\t\t_ = conn.SetReadDeadline(time.Now().Add(c.Timeout))\n\t}\n\n\tproto := \"udp\"\n\tif _, ok := conn.(*net.TCPConn); ok {\n\t\tproto = \"tcp\"\n\t}\n\n\tif proto == \"udp\" {\n\t\tbufSize := c.UDPSize\n\t\tif bufSize == 0 {\n\t\t\tbufSize = dns.MinMsgSize\n\t\t}\n\t\tresponse := make([]byte, bufSize)\n\t\tn, err := conn.Read(response)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn response[:n], nil\n\t}\n\n\t// If we got here, this is a TCP connection\n\t// so we should read a 2-byte prefix first\n\treturn readPrefixed(conn)\n}", "func (o *PayReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewPayOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 400:\n\t\tresult := NewPayBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewPayNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 409:\n\t\tresult := NewPayConflict()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\tdata, err := ioutil.ReadAll(response.Body())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"Requested POST /platform/public/namespaces/{namespace}/payment/orders/{paymentOrderNo}/pay returns an error %d: %s\", response.Code(), string(data))\n\t}\n}", "func (o *CountReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewCountOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 400:\n\t\tresult := NewCountBadRequest()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *PostNodesIdentifierObmIdentifyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 201:\n\t\tresult := NewPostNodesIdentifierObmIdentifyCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewPostNodesIdentifierObmIdentifyNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\tresult := NewPostNodesIdentifierObmIdentifyDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *GetInterpreterReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetInterpreterOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewGetInterpreterNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *DeleteEventsEventIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 204:\n\t\tresult := NewDeleteEventsEventIDNoContent()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 401:\n\t\tresult := NewDeleteEventsEventIDUnauthorized()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tcase 404:\n\t\tresult := NewDeleteEventsEventIDNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *UtilityServiceReadyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewUtilityServiceReadyOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewUtilityServiceReadyDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *HTTPGetPersistenceItemDataReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewHTTPGetPersistenceItemDataOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewHTTPGetPersistenceItemDataNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *SubscriptionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewSubscriptionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *PostEquipmentIoExpandersMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 201:\n\t\tresult := NewPostEquipmentIoExpandersMoidCreated()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewPostEquipmentIoExpandersMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *FrontSessionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewFrontSessionOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (pr *PushedRequest) ReadResponse(ctx context.Context) (*http.Response, error) {\n\tselect {\n\tcase <-ctx.Done():\n\t\tpr.Cancel()\n\t\tpr.pushedStream.bufPipe.CloseWithError(ctx.Err())\n\t\treturn nil, ctx.Err()\n\tcase <-pr.pushedStream.peerReset:\n\t\treturn nil, pr.pushedStream.resetErr\n\tcase resErr := <-pr.pushedStream.resc:\n\t\tif resErr.err != nil {\n\t\t\tfmt.Println(resErr.err.Error())\n\t\t\tpr.Cancel()\n\t\t\tpr.pushedStream.bufPipe.CloseWithError(resErr.err)\n\t\t\treturn nil, resErr.err\n\t\t}\n\t\tresErr.res.Request = pr.Promise\n\t\tresErr.res.TLS = pr.pushedStream.cc.tlsState\n\t\treturn resErr.res, resErr.err\n\t}\n}", "func (o *GetZippedReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tresult := NewGetZippedDefault(response.Code())\n\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\treturn nil, err\n\t}\n\tif response.Code()/100 == 2 {\n\t\treturn result, nil\n\t}\n\treturn nil, result\n}", "func (o *DeleteFirmwareUpgradesMoidReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewDeleteFirmwareUpgradesMoidOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 404:\n\t\tresult := NewDeleteFirmwareUpgradesMoidNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\tresult := NewDeleteFirmwareUpgradesMoidDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *GetEtherPhysicalPortsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetEtherPhysicalPortsOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tdefault:\n\t\tresult := NewGetEtherPhysicalPortsDefault(response.Code())\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif response.Code()/100 == 2 {\n\t\t\treturn result, nil\n\t\t}\n\t\treturn nil, result\n\t}\n}", "func (o *ZoneStreamReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewZoneStreamOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}", "func (o *ByNamespaceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewByNamespaceOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\n\tcase 404:\n\t\tresult := NewByNamespaceNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"unknown error\", response, response.Code())\n\t}\n}", "func (o *GetRequestTrackerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {\n\tswitch response.Code() {\n\tcase 200:\n\t\tresult := NewGetRequestTrackerOK()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\tcase 403:\n\t\tresult := NewGetRequestTrackerForbidden()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tcase 404:\n\t\tresult := NewGetRequestTrackerNotFound()\n\t\tif err := result.readResponse(response, consumer, o.formats); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, result\n\tdefault:\n\t\treturn nil, runtime.NewAPIError(\"response status code does not match any response statuses defined for this endpoint in the swagger spec\", response, response.Code())\n\t}\n}" ]
[ "0.7640225", "0.7607834", "0.75210214", "0.7509121", "0.74803215", "0.74724656", "0.7433606", "0.74244606", "0.7375357", "0.7367311", "0.73589337", "0.73551553", "0.7350114", "0.7347274", "0.7346054", "0.733966", "0.7336042", "0.73239547", "0.7315819", "0.73155594", "0.7310195", "0.730769", "0.72904205", "0.7287086", "0.72826135", "0.72742283", "0.7274111", "0.72655845", "0.726384", "0.7262403", "0.7255057", "0.72496617", "0.72492456", "0.72479755", "0.72409135", "0.7224629", "0.722366", "0.7219326", "0.7216009", "0.72122216", "0.72110355", "0.72099286", "0.7209348", "0.72004783", "0.71978456", "0.719778", "0.71926844", "0.7177653", "0.71745974", "0.71737057", "0.716626", "0.7155474", "0.71500206", "0.7149536", "0.7148374", "0.7143972", "0.7143686", "0.7141745", "0.71397567", "0.713703", "0.7136677", "0.7136661", "0.7135863", "0.7135147", "0.71337897", "0.71312535", "0.7124361", "0.7123878", "0.71200526", "0.7120036", "0.7119569", "0.71148854", "0.7104891", "0.7100936", "0.70989054", "0.70989", "0.70984536", "0.70977753", "0.709657", "0.70961034", "0.70941985", "0.70932794", "0.70886916", "0.70850074", "0.7083912", "0.7080819", "0.7078785", "0.70775825", "0.70765215", "0.7076268", "0.7070042", "0.70699906", "0.7068155", "0.7068122", "0.7066828", "0.70625323", "0.70621973", "0.70599294", "0.70577264", "0.7054454", "0.70509636" ]
0.0
-1
NewAddRemoteRDSNodeOK creates a AddRemoteRDSNodeOK with default headers values
func NewAddRemoteRDSNodeOK() *AddRemoteRDSNodeOK { return &AddRemoteRDSNodeOK{} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewAddRemoteRDSNodeDefault(code int) *AddRemoteRDSNodeDefault {\n\treturn &AddRemoteRDSNodeDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (c *CAPI) AddNode(req *btcjson.AddNodeCmd, resp None) (e error) {\n\tnrh := RPCHandlers\n\tres := nrh[\"addnode\"].Result()\n\tres.Params = req\n\tnrh[\"addnode\"].Call <- res\n\tselect {\n\tcase resp = <-res.Ch.(chan None):\n\tcase <-time.After(c.Timeout):\n\tcase <-c.quit.Wait():\n\t} \n\treturn \n}", "func (o *AddRemoteRDSNodeOKBodyRemoteRDS) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (r *CAPIClient) AddNode(cmd ...*btcjson.AddNodeCmd) (res None, e error) {\n\tvar c *btcjson.AddNodeCmd\n\tif len(cmd) > 0 {\n\t\tc = cmd[0]\n\t}\n\tif e = r.Call(\"CAPI.AddNode\", c, &res); E.Chk(e) {\n\t}\n\treturn\n}", "func (ctx Context) AddNode(count int, hardwareprofile, softwareprofile string) (AddNodeResult, error) {\n\tvar result AddNodeResult\n\n\t// we trust the signature\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\taddInput := AddNodeInput{inner{count, hardwareprofile, softwareprofile}}\n\tinput, errMarshal := json.Marshal(addInput)\n\tif errMarshal != nil {\n\t\treturn result, errMarshal\n\t}\n\turl := fmt.Sprintf(\"https://%s:8443/v1/nodes\", ctx.Address)\n\treq, errRequest := http.NewRequest(\"POST\", url, bytes.NewBuffer(input))\n\tif errRequest != nil {\n\t\treturn result, errRequest\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.SetBasicAuth(ctx.User, ctx.Password)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer resp.Body.Close()\n\n\tdecoder := json.NewDecoder(resp.Body)\n\tif err := decoder.Decode(&result); err != nil {\n\t\treturn result, err\n\t}\n\treturn result, nil\n}", "func (o *AddRemoteRDSNodeOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateRemoteRDS(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (sdk *SDK) NewNode(prefer *cloudsvr.PreferAttrs) (*cloudsvr.CloudNode, *cloudsvr.PreferAttrs, error) {\n\n\tvar (\n\t\tpassword, _ = utils.GenPassword(24)\n\t\treq = &CreateInstanceRequest{\n\t\t\tImageID: OsImage,\n\t\t\tPassword: password,\n\t\t\tInstanceName: NodeName,\n\t\t\tInstanceChargeType: \"PostPaid\", // require RMB 100+\n\t\t\tSecurityGroupID: \"whatever\", // will be automatic rewrite\n\t\t\tInternetChargeType: \"PayByTraffic\", // traffic payment\n\t\t\tInternetMaxBandwidthOut: \"100\", // 100M\n\t\t\tLabels: NodeLabels,\n\t\t}\n\t)\n\n\t// if prefered attributes set, use prefer region & instance-type\n\tif prefer != nil && prefer.Valid() == nil {\n\t\tvar (\n\t\t\treg = prefer.RegionOrZone\n\t\t\ttyp = prefer.InstanceType\n\t\t)\n\t\tlog.Printf(\"create aliyun ecs by using prefered region %s, instance type %s ...\", reg, typ)\n\n\t\treq.RegionID = reg // cn-beijing\n\t\treq.InstanceType = typ // ecs.n4.large\n\n\t\tcreated, err := sdk.createNode(req)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tlog.Printf(\"created prefered aliyun ecs succeed: %s\", created.ID)\n\t\treturn created, prefer, nil\n\t}\n\n\tlog.Infoln(\"creating aliyun ecs by trying all regions & types ...\")\n\n\t// if prefered created failed, or without prefer region & instance-type\n\t// try best on all region & instance-types to create the new aliyun ecs\n\tvar (\n\t\tregions []RegionType // all of aliyun regions\n\t\ttypes []InstanceTypeItemType // all of instance types within given range of mems & cpus\n\t\terr error\n\t\tcreated *cloudsvr.CloudNode\n\t)\n\n\t// list all regions\n\tregions, err = sdk.ListRegions()\n\tif err != nil {\n\t\tlog.Errorf(\"sdk.NewNode.ListRegions() error: %v\", err)\n\t\treturn nil, nil, err\n\t}\n\n\t// list specified range of instance types\n\ttypes, err = sdk.ListInstanceTypes(2, 4, 2, 8) // TODO range of given cpus/mems ranges\n\tif err != nil {\n\t\tlog.Errorf(\"sdk.NewNode.ListInstanceTypes() error: %v\", err)\n\t\treturn nil, nil, err\n\t}\n\n\tvar (\n\t\tuseRegionID, useInsType string\n\t)\n\t// range all regions & types to try to create ecs instance\n\tfor _, reg := range regions {\n\t\tfor _, typ := range types {\n\t\t\treq.RegionID = reg.RegionID // cn-beijing\n\t\t\treq.InstanceType = typ.InstanceTypeID // ecs.n4.large\n\n\t\t\t// if created succeed, directly return\n\t\t\tcreated, err = sdk.createNode(req)\n\t\t\tif err == nil {\n\t\t\t\tuseRegionID, useInsType = reg.RegionID, typ.InstanceTypeID\n\t\t\t\tgoto END\n\t\t\t}\n\n\t\t\tif sdk.isFatalError(err) {\n\t\t\t\tlog.Errorf(\"create aliyun ecs got fatal error, stop retry: %v\", err)\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\n\t\t\tlog.Warnf(\"create aliyun ecs failed: %v, will retry another region or type\", err)\n\t\t}\n\t}\n\nEND:\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tlog.Printf(\"created aliyun ecs %s at %s and type is %s\", created.ID, useRegionID, useInsType)\n\treturn created, &cloudsvr.PreferAttrs{RegionOrZone: useRegionID, InstanceType: useInsType}, nil\n}", "func newnode(id byte, name string, value string) *xmlx.Node {\n\tnode := xmlx.NewNode(id)\n\tif name != \"\" {\n\t\tnode.Name = xml.Name{\n\t\t\tLocal: name,\n\t\t}\n\t}\n\tif value != \"\" {\n\t\tnode.Value = value\n\t}\n\treturn node\n}", "func (cc *ContrailCommand) CreateNode(host vcenter.ESXIHost) error {\n\tlog.Debug(\"Create Node:\", cc.AuthToken)\n\tnodeResource := contrailCommandNodeSync{\n\t\tResources: []*nodeResources{\n\t\t\t{\n\t\t\t\tKind: \"node\",\n\t\t\t\tData: &nodeData{\n\t\t\t\t\tNodeType: \"esxi\",\n\t\t\t\t\tUUID: host.UUID,\n\t\t\t\t\tHostname: host.Hostname,\n\t\t\t\t\tFqName: []string{\"default-global-system-config\", host.Hostname},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tjsonData, err := json.Marshal(nodeResource)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Sending Request\")\n\tresp, _, err := cc.sendRequest(\"/sync\", string(jsonData), \"POST\") //nolint: bodyclose\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Got status : \", resp.StatusCode)\n\tswitch resp.StatusCode {\n\tdefault:\n\t\treturn fmt.Errorf(\"resource creation failed, %d\", resp.StatusCode)\n\tcase 200, 201:\n\t}\n\treturn nil\n}", "func (tapestry *Tapestry) addNode(remote Node, newnode Node) (neighbours []Node, err error) {\n\terr = makeRemoteNodeCall(remote, \"AddNode\", NodeRequest{remote, newnode}, &neighbours)\n\treturn\n}", "func NewRemote(v gointerfaces.Version, logger log.Logger, remoteKV remote.KVClient) remoteOpts {\n\treturn remoteOpts{bucketsCfg: mdbx.WithChaindataTables, version: v, log: logger, remoteKV: remoteKV}\n}", "func AddNode(c *cli.Context) error {\n\n\t/*\n\t * (0) Check flags\n\t */\n\n\tclusterName := c.String(\"name\")\n\tnodeCount := c.Int(\"count\")\n\n\tclusterSpec := &ClusterSpec{\n\t\tAgentArgs: nil,\n\t\tAPIPort: apiPort{},\n\t\tAutoRestart: false,\n\t\tClusterName: clusterName,\n\t\tEnv: nil,\n\t\tNodeToLabelSpecMap: nil,\n\t\tImage: \"\",\n\t\tNodeToPortSpecMap: nil,\n\t\tPortAutoOffset: 0,\n\t\tServerArgs: nil,\n\t\tVolumes: &Volumes{},\n\t}\n\n\t/* (0.1)\n\t * --role\n\t * Role of the node that has to be created.\n\t * One of (server|master), (agent|worker)\n\t */\n\tnodeRole := c.String(\"role\")\n\tif nodeRole == \"worker\" {\n\t\tnodeRole = \"agent\"\n\t}\n\tif nodeRole == \"master\" {\n\t\tnodeRole = \"server\"\n\t}\n\n\t// TODO: support adding server nodes\n\tif nodeRole != \"worker\" && nodeRole != \"agent\" {\n\t\treturn fmt.Errorf(\"Adding nodes of type '%s' is not supported\", nodeRole)\n\t}\n\n\t/* (0.2)\n\t * --image, -i\n\t * The k3s image used for the k3d node containers\n\t */\n\t// TODO: use the currently running image by default\n\timage := c.String(\"image\")\n\t// if no registry was provided, use the default docker.io\n\tif len(strings.Split(image, \"/\")) <= 2 {\n\t\timage = fmt.Sprintf(\"%s/%s\", DefaultRegistry, image)\n\t}\n\tclusterSpec.Image = image\n\n\t/* (0.3)\n\t * --env, -e <key1=val1>[,<keyX=valX]\n\t * Environment variables that will be passed to the node containers\n\t */\n\tclusterSpec.Env = []string{}\n\tclusterSpec.Env = append(clusterSpec.Env, c.StringSlice(\"env\")...)\n\n\t/* (0.4)\n\t * --arg, -x <argument>\n\t * Argument passed in to the k3s server/agent command\n\t */\n\tclusterSpec.ServerArgs = append(clusterSpec.ServerArgs, c.StringSlice(\"arg\")...)\n\tclusterSpec.AgentArgs = append(clusterSpec.AgentArgs, c.StringSlice(\"arg\")...)\n\n\t/* (0.5)\n\t * --volume, -v\n\t * Add volume mounts\n\t */\n\tvolumeSpec, err := NewVolumes(c.StringSlice(\"volume\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\t// TODO: volumeSpec.DefaultVolumes = append(volumeSpec.DefaultVolumes, \"%s:/images\", imageVolume.Name)\n\tclusterSpec.Volumes = volumeSpec\n\n\t/* (0.5) BREAKOUT\n\t * --k3s <url>\n\t * Connect to a non-dockerized k3s server\n\t */\n\n\tif c.IsSet(\"k3s\") {\n\t\tlog.Infof(\"Adding %d %s-nodes to k3s cluster %s...\\n\", nodeCount, nodeRole, c.String(\"k3s\"))\n\t\tif _, err := createClusterNetwork(clusterName); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := addNodeToK3s(c, clusterSpec, nodeRole); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t/*\n\t * (1) Check cluster\n\t */\n\n\tctx := context.Background()\n\tdocker, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())\n\tif err != nil {\n\t\tlog.Errorln(\"Failed to create docker client\")\n\t\treturn err\n\t}\n\n\tfilters := filters.NewArgs()\n\tfilters.Add(\"label\", fmt.Sprintf(\"cluster=%s\", clusterName))\n\tfilters.Add(\"label\", \"app=k3d\")\n\n\t/*\n\t * (1.1) Verify, that the cluster (i.e. the server) that we want to connect to, is running\n\t */\n\tfilters.Add(\"label\", \"component=server\")\n\n\tserverList, err := docker.ContainerList(ctx, types.ContainerListOptions{\n\t\tFilters: filters,\n\t})\n\tif err != nil || len(serverList) == 0 {\n\t\tlog.Errorf(\"Failed to get server container for cluster '%s'\", clusterName)\n\t\treturn err\n\t}\n\n\t/*\n\t * (1.2) Extract cluster information from server container\n\t */\n\tserverContainer, err := docker.ContainerInspect(ctx, serverList[0].ID)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to inspect server container '%s' to get cluster secret\", serverList[0].ID)\n\t\treturn err\n\t}\n\n\t/*\n\t * (1.2.1) Extract cluster secret from server container's labels\n\t */\n\tclusterSecretEnvVar := \"\"\n\tfor _, envVar := range serverContainer.Config.Env {\n\t\tif envVarSplit := strings.SplitN(envVar, \"=\", 2); envVarSplit[0] == \"K3S_CLUSTER_SECRET\" {\n\t\t\tclusterSecretEnvVar = envVar\n\t\t}\n\t}\n\tif clusterSecretEnvVar == \"\" {\n\t\treturn fmt.Errorf(\"Failed to get cluster secret from server container\")\n\t}\n\n\tclusterSpec.Env = append(clusterSpec.Env, clusterSecretEnvVar)\n\n\t/*\n\t * (1.2.2) Extract API server Port from server container's cmd\n\t */\n\tserverListenPort := \"\"\n\tfor cmdIndex, cmdPart := range serverContainer.Config.Cmd {\n\t\tif cmdPart == \"--https-listen-port\" {\n\t\t\tserverListenPort = serverContainer.Config.Cmd[cmdIndex+1]\n\t\t}\n\t}\n\tif serverListenPort == \"\" {\n\t\treturn fmt.Errorf(\"Failed to get https-listen-port from server container\")\n\t}\n\n\tserverURLEnvVar := fmt.Sprintf(\"K3S_URL=https://%s:%s\", strings.TrimLeft(serverContainer.Name, \"/\"), serverListenPort)\n\tclusterSpec.Env = append(clusterSpec.Env, serverURLEnvVar)\n\n\t/*\n\t * (1.3) Get the docker network of the cluster that we want to connect to\n\t */\n\tfilters.Del(\"label\", \"component=server\")\n\n\tnetworkList, err := docker.NetworkList(ctx, types.NetworkListOptions{\n\t\tFilters: filters,\n\t})\n\tif err != nil || len(networkList) == 0 {\n\t\tlog.Errorf(\"Failed to find network for cluster '%s'\", clusterName)\n\t\treturn err\n\t}\n\n\t/*\n\t * (2) Now identify any existing worker nodes IF we're adding a new one\n\t */\n\thighestExistingWorkerSuffix := 0 // needs to be outside conditional because of bad branching\n\n\tif nodeRole == \"agent\" {\n\t\tfilters.Add(\"label\", \"component=worker\")\n\n\t\tworkerList, err := docker.ContainerList(ctx, types.ContainerListOptions{\n\t\t\tFilters: filters,\n\t\t\tAll: true,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Errorln(\"Failed to list worker node containers\")\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, worker := range workerList {\n\t\t\tsplit := strings.Split(worker.Names[0], \"-\")\n\t\t\tcurrSuffix, err := strconv.Atoi(split[len(split)-1])\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(\"Failed to get highest worker suffix\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif currSuffix > highestExistingWorkerSuffix {\n\t\t\t\thighestExistingWorkerSuffix = currSuffix\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * (3) Create the nodes with configuration that automatically joins them to the cluster\n\t */\n\n\tlog.Infof(\"Adding %d %s-nodes to k3d cluster %s...\\n\", nodeCount, nodeRole, clusterName)\n\n\tif err := createNodes(clusterSpec, nodeRole, highestExistingWorkerSuffix+1, nodeCount); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *AddRemoteRDSNodeBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (rm *resourceManager) newCreateRequestPayload(\n\tctx context.Context,\n\tr *resource,\n) (*svcsdk.CreateVpnConnectionInput, error) {\n\tres := &svcsdk.CreateVpnConnectionInput{}\n\n\tif r.ko.Spec.CustomerGatewayID != nil {\n\t\tres.SetCustomerGatewayId(*r.ko.Spec.CustomerGatewayID)\n\t}\n\tif r.ko.Spec.DryRun != nil {\n\t\tres.SetDryRun(*r.ko.Spec.DryRun)\n\t}\n\tif r.ko.Spec.Options != nil {\n\t\tf2 := &svcsdk.VpnConnectionOptionsSpecification{}\n\t\tif r.ko.Spec.Options.EnableAcceleration != nil {\n\t\t\tf2.SetEnableAcceleration(*r.ko.Spec.Options.EnableAcceleration)\n\t\t}\n\t\tif r.ko.Spec.Options.LocalIPv4NetworkCIDR != nil {\n\t\t\tf2.SetLocalIpv4NetworkCidr(*r.ko.Spec.Options.LocalIPv4NetworkCIDR)\n\t\t}\n\t\tif r.ko.Spec.Options.LocalIPv6NetworkCIDR != nil {\n\t\t\tf2.SetLocalIpv6NetworkCidr(*r.ko.Spec.Options.LocalIPv6NetworkCIDR)\n\t\t}\n\t\tif r.ko.Spec.Options.RemoteIPv4NetworkCIDR != nil {\n\t\t\tf2.SetRemoteIpv4NetworkCidr(*r.ko.Spec.Options.RemoteIPv4NetworkCIDR)\n\t\t}\n\t\tif r.ko.Spec.Options.RemoteIPv6NetworkCIDR != nil {\n\t\t\tf2.SetRemoteIpv6NetworkCidr(*r.ko.Spec.Options.RemoteIPv6NetworkCIDR)\n\t\t}\n\t\tif r.ko.Spec.Options.StaticRoutesOnly != nil {\n\t\t\tf2.SetStaticRoutesOnly(*r.ko.Spec.Options.StaticRoutesOnly)\n\t\t}\n\t\tif r.ko.Spec.Options.TunnelInsideIPVersion != nil {\n\t\t\tf2.SetTunnelInsideIpVersion(*r.ko.Spec.Options.TunnelInsideIPVersion)\n\t\t}\n\t\tif r.ko.Spec.Options.TunnelOptions != nil {\n\t\t\tf2f7 := []*svcsdk.VpnTunnelOptionsSpecification{}\n\t\t\tfor _, f2f7iter := range r.ko.Spec.Options.TunnelOptions {\n\t\t\t\tf2f7elem := &svcsdk.VpnTunnelOptionsSpecification{}\n\t\t\t\tif f2f7iter.DPDTimeoutAction != nil {\n\t\t\t\t\tf2f7elem.SetDPDTimeoutAction(*f2f7iter.DPDTimeoutAction)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.DPDTimeoutSeconds != nil {\n\t\t\t\t\tf2f7elem.SetDPDTimeoutSeconds(*f2f7iter.DPDTimeoutSeconds)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.IKEVersions != nil {\n\t\t\t\t\tf2f7elemf2 := []*svcsdk.IKEVersionsRequestListValue{}\n\t\t\t\t\tfor _, f2f7elemf2iter := range f2f7iter.IKEVersions {\n\t\t\t\t\t\tf2f7elemf2elem := &svcsdk.IKEVersionsRequestListValue{}\n\t\t\t\t\t\tif f2f7elemf2iter.Value != nil {\n\t\t\t\t\t\t\tf2f7elemf2elem.SetValue(*f2f7elemf2iter.Value)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf2f7elemf2 = append(f2f7elemf2, f2f7elemf2elem)\n\t\t\t\t\t}\n\t\t\t\t\tf2f7elem.SetIKEVersions(f2f7elemf2)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.Phase1DHGroupNumbers != nil {\n\t\t\t\t\tf2f7elemf3 := []*svcsdk.Phase1DHGroupNumbersRequestListValue{}\n\t\t\t\t\tfor _, f2f7elemf3iter := range f2f7iter.Phase1DHGroupNumbers {\n\t\t\t\t\t\tf2f7elemf3elem := &svcsdk.Phase1DHGroupNumbersRequestListValue{}\n\t\t\t\t\t\tif f2f7elemf3iter.Value != nil {\n\t\t\t\t\t\t\tf2f7elemf3elem.SetValue(*f2f7elemf3iter.Value)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf2f7elemf3 = append(f2f7elemf3, f2f7elemf3elem)\n\t\t\t\t\t}\n\t\t\t\t\tf2f7elem.SetPhase1DHGroupNumbers(f2f7elemf3)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.Phase1EncryptionAlgorithms != nil {\n\t\t\t\t\tf2f7elemf4 := []*svcsdk.Phase1EncryptionAlgorithmsRequestListValue{}\n\t\t\t\t\tfor _, f2f7elemf4iter := range f2f7iter.Phase1EncryptionAlgorithms {\n\t\t\t\t\t\tf2f7elemf4elem := &svcsdk.Phase1EncryptionAlgorithmsRequestListValue{}\n\t\t\t\t\t\tif f2f7elemf4iter.Value != nil {\n\t\t\t\t\t\t\tf2f7elemf4elem.SetValue(*f2f7elemf4iter.Value)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf2f7elemf4 = append(f2f7elemf4, f2f7elemf4elem)\n\t\t\t\t\t}\n\t\t\t\t\tf2f7elem.SetPhase1EncryptionAlgorithms(f2f7elemf4)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.Phase1IntegrityAlgorithms != nil {\n\t\t\t\t\tf2f7elemf5 := []*svcsdk.Phase1IntegrityAlgorithmsRequestListValue{}\n\t\t\t\t\tfor _, f2f7elemf5iter := range f2f7iter.Phase1IntegrityAlgorithms {\n\t\t\t\t\t\tf2f7elemf5elem := &svcsdk.Phase1IntegrityAlgorithmsRequestListValue{}\n\t\t\t\t\t\tif f2f7elemf5iter.Value != nil {\n\t\t\t\t\t\t\tf2f7elemf5elem.SetValue(*f2f7elemf5iter.Value)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf2f7elemf5 = append(f2f7elemf5, f2f7elemf5elem)\n\t\t\t\t\t}\n\t\t\t\t\tf2f7elem.SetPhase1IntegrityAlgorithms(f2f7elemf5)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.Phase1LifetimeSeconds != nil {\n\t\t\t\t\tf2f7elem.SetPhase1LifetimeSeconds(*f2f7iter.Phase1LifetimeSeconds)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.Phase2DHGroupNumbers != nil {\n\t\t\t\t\tf2f7elemf7 := []*svcsdk.Phase2DHGroupNumbersRequestListValue{}\n\t\t\t\t\tfor _, f2f7elemf7iter := range f2f7iter.Phase2DHGroupNumbers {\n\t\t\t\t\t\tf2f7elemf7elem := &svcsdk.Phase2DHGroupNumbersRequestListValue{}\n\t\t\t\t\t\tif f2f7elemf7iter.Value != nil {\n\t\t\t\t\t\t\tf2f7elemf7elem.SetValue(*f2f7elemf7iter.Value)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf2f7elemf7 = append(f2f7elemf7, f2f7elemf7elem)\n\t\t\t\t\t}\n\t\t\t\t\tf2f7elem.SetPhase2DHGroupNumbers(f2f7elemf7)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.Phase2EncryptionAlgorithms != nil {\n\t\t\t\t\tf2f7elemf8 := []*svcsdk.Phase2EncryptionAlgorithmsRequestListValue{}\n\t\t\t\t\tfor _, f2f7elemf8iter := range f2f7iter.Phase2EncryptionAlgorithms {\n\t\t\t\t\t\tf2f7elemf8elem := &svcsdk.Phase2EncryptionAlgorithmsRequestListValue{}\n\t\t\t\t\t\tif f2f7elemf8iter.Value != nil {\n\t\t\t\t\t\t\tf2f7elemf8elem.SetValue(*f2f7elemf8iter.Value)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf2f7elemf8 = append(f2f7elemf8, f2f7elemf8elem)\n\t\t\t\t\t}\n\t\t\t\t\tf2f7elem.SetPhase2EncryptionAlgorithms(f2f7elemf8)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.Phase2IntegrityAlgorithms != nil {\n\t\t\t\t\tf2f7elemf9 := []*svcsdk.Phase2IntegrityAlgorithmsRequestListValue{}\n\t\t\t\t\tfor _, f2f7elemf9iter := range f2f7iter.Phase2IntegrityAlgorithms {\n\t\t\t\t\t\tf2f7elemf9elem := &svcsdk.Phase2IntegrityAlgorithmsRequestListValue{}\n\t\t\t\t\t\tif f2f7elemf9iter.Value != nil {\n\t\t\t\t\t\t\tf2f7elemf9elem.SetValue(*f2f7elemf9iter.Value)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf2f7elemf9 = append(f2f7elemf9, f2f7elemf9elem)\n\t\t\t\t\t}\n\t\t\t\t\tf2f7elem.SetPhase2IntegrityAlgorithms(f2f7elemf9)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.Phase2LifetimeSeconds != nil {\n\t\t\t\t\tf2f7elem.SetPhase2LifetimeSeconds(*f2f7iter.Phase2LifetimeSeconds)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.PreSharedKey != nil {\n\t\t\t\t\tf2f7elem.SetPreSharedKey(*f2f7iter.PreSharedKey)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.RekeyFuzzPercentage != nil {\n\t\t\t\t\tf2f7elem.SetRekeyFuzzPercentage(*f2f7iter.RekeyFuzzPercentage)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.RekeyMarginTimeSeconds != nil {\n\t\t\t\t\tf2f7elem.SetRekeyMarginTimeSeconds(*f2f7iter.RekeyMarginTimeSeconds)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.ReplayWindowSize != nil {\n\t\t\t\t\tf2f7elem.SetReplayWindowSize(*f2f7iter.ReplayWindowSize)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.StartupAction != nil {\n\t\t\t\t\tf2f7elem.SetStartupAction(*f2f7iter.StartupAction)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.TunnelInsideCIDR != nil {\n\t\t\t\t\tf2f7elem.SetTunnelInsideCidr(*f2f7iter.TunnelInsideCIDR)\n\t\t\t\t}\n\t\t\t\tif f2f7iter.TunnelInsideIPv6CIDR != nil {\n\t\t\t\t\tf2f7elem.SetTunnelInsideIpv6Cidr(*f2f7iter.TunnelInsideIPv6CIDR)\n\t\t\t\t}\n\t\t\t\tf2f7 = append(f2f7, f2f7elem)\n\t\t\t}\n\t\t\tf2.SetTunnelOptions(f2f7)\n\t\t}\n\t\tres.SetOptions(f2)\n\t}\n\tif r.ko.Spec.TagSpecifications != nil {\n\t\tf3 := []*svcsdk.TagSpecification{}\n\t\tfor _, f3iter := range r.ko.Spec.TagSpecifications {\n\t\t\tf3elem := &svcsdk.TagSpecification{}\n\t\t\tif f3iter.ResourceType != nil {\n\t\t\t\tf3elem.SetResourceType(*f3iter.ResourceType)\n\t\t\t}\n\t\t\tif f3iter.Tags != nil {\n\t\t\t\tf3elemf1 := []*svcsdk.Tag{}\n\t\t\t\tfor _, f3elemf1iter := range f3iter.Tags {\n\t\t\t\t\tf3elemf1elem := &svcsdk.Tag{}\n\t\t\t\t\tif f3elemf1iter.Key != nil {\n\t\t\t\t\t\tf3elemf1elem.SetKey(*f3elemf1iter.Key)\n\t\t\t\t\t}\n\t\t\t\t\tif f3elemf1iter.Value != nil {\n\t\t\t\t\t\tf3elemf1elem.SetValue(*f3elemf1iter.Value)\n\t\t\t\t\t}\n\t\t\t\t\tf3elemf1 = append(f3elemf1, f3elemf1elem)\n\t\t\t\t}\n\t\t\t\tf3elem.SetTags(f3elemf1)\n\t\t\t}\n\t\t\tf3 = append(f3, f3elem)\n\t\t}\n\t\tres.SetTagSpecifications(f3)\n\t}\n\tif r.ko.Spec.TransitGatewayID != nil {\n\t\tres.SetTransitGatewayId(*r.ko.Spec.TransitGatewayID)\n\t}\n\tif r.ko.Spec.Type != nil {\n\t\tres.SetType(*r.ko.Spec.Type)\n\t}\n\tif r.ko.Spec.VPNGatewayID != nil {\n\t\tres.SetVpnGatewayId(*r.ko.Spec.VPNGatewayID)\n\t}\n\n\treturn res, nil\n}", "func newAddnode() *cobra.Command {\n\tvar cluster []string\n\tvar address string\n\t//var role string\n\tvar timeout time.Duration\n\n\troles := map[string]int{\n\t\tclient.Voter.String(): int(Voter),\n\t\tclient.Spare.String(): int(Spare),\n\t\tclient.StandBy.String(): int(Standby),\n\t}\n\tchoices := &FlagChoice{choices: mapKeys(roles), chosen: client.Voter.String()}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"add\",\n\t\tShort: \"Add a node to the cluster.\",\n\t\tArgs: cobra.MinimumNArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tid, err := strconv.ParseUint(args[0], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\t\t\trole, err := nodeRole(choices.chosen)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\t\tdefer cancel()\n\n\t\t\tclient, err := getLeader(ctx, &globalKeys, cluster)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\n\t\t\tif err := nodeAdd(ctx, client, id, role, address); err != nil {\n\t\t\t\tlog.Fatalln(\"error adding node:\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.StringSliceVarP(&cluster, \"cluster\", \"c\", clusterList(), \"addresses of existing cluster nodes\")\n\tflags.StringVarP(&address, \"address\", \"a\", envy.StringDefault(\"DQLITED_ADDRESS\", \"127.0.0.1:9181\"), \"address of the node (default is 127.0.0.1:918<ID>)\")\n\tflags.VarP(choices, \"role\", \"r\", \"server role\")\n\tflags.DurationVarP(&timeout, \"timeout\", \"t\", time.Minute*5, \"time to wait for connection to complete\")\n\n\treturn cmd\n}", "func newNode(cluster *Cluster, nv *nodeValidator) *Node {\n\treturn &Node{\n\t\tcluster: cluster,\n\t\tname: nv.name,\n\t\taliases: nv.aliases,\n\t\taddress: nv.address,\n\t\tuseNewInfo: nv.useNewInfo,\n\n\t\t// Assign host to first IP alias because the server identifies nodes\n\t\t// by IP address (not hostname).\n\t\thost: nv.aliases[0],\n\t\tconnections: NewAtomicQueue(cluster.clientPolicy.ConnectionQueueSize),\n\t\tconnectionCount: NewAtomicInt(0),\n\t\thealth: NewAtomicInt(_FULL_HEALTH),\n\t\tpartitionGeneration: NewAtomicInt(-1),\n\t\treferenceCount: NewAtomicInt(0),\n\t\trefreshCount: NewAtomicInt(0),\n\t\tresponded: NewAtomicBool(false),\n\t\tactive: NewAtomicBool(true),\n\n\t\tsupportsFloat: NewAtomicBool(nv.supportsFloat),\n\t\tsupportsBatchIndex: NewAtomicBool(nv.supportsBatchIndex),\n\t\tsupportsReplicasAll: NewAtomicBool(nv.supportsReplicasAll),\n\t\tsupportsGeo: NewAtomicBool(nv.supportsGeo),\n\t}\n}", "func (zic *ZoneInterconnectHandler) AddRemoteZoneNode(node *corev1.Node) error {\n\tstart := time.Now()\n\tklog.Infof(\"Creating interconnect resources for remote zone node %s for the network %s\", node.Name, zic.GetNetworkName())\n\n\tnodeID := util.GetNodeID(node)\n\tif nodeID == -1 {\n\t\t// Don't consider this node as cluster-manager has not allocated node id yet.\n\t\treturn fmt.Errorf(\"failed to get node id for node - %s\", node.Name)\n\t}\n\n\t// Get the chassis id.\n\tchassisId, err := util.ParseNodeChassisIDAnnotation(node)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse node chassis-id for node - %s, error: %w\", node.Name, types.NewSuppressedError(err))\n\t}\n\n\tif err := zic.createRemoteZoneNodeResources(node, nodeID, chassisId); err != nil {\n\t\treturn fmt.Errorf(\"creating interconnect resources for remote zone node %s for the network %s failed : err - %w\", node.Name, zic.GetNetworkName(), err)\n\t}\n\tklog.Infof(\"Creating Interconnect resources for node %v took: %s\", node.Name, time.Since(start))\n\treturn nil\n}", "func (client *Client) AddShardingNodeWithOptions(request *AddShardingNodeRequest, runtime *util.RuntimeOptions) (_result *AddShardingNodeResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AutoPay)) {\n\t\tquery[\"AutoPay\"] = request.AutoPay\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.BusinessInfo)) {\n\t\tquery[\"BusinessInfo\"] = request.BusinessInfo\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.CouponNo)) {\n\t\tquery[\"CouponNo\"] = request.CouponNo\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ForceTrans)) {\n\t\tquery[\"ForceTrans\"] = request.ForceTrans\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.InstanceId)) {\n\t\tquery[\"InstanceId\"] = request.InstanceId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerAccount)) {\n\t\tquery[\"OwnerAccount\"] = request.OwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerId)) {\n\t\tquery[\"OwnerId\"] = request.OwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerAccount)) {\n\t\tquery[\"ResourceOwnerAccount\"] = request.ResourceOwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerId)) {\n\t\tquery[\"ResourceOwnerId\"] = request.ResourceOwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SecurityToken)) {\n\t\tquery[\"SecurityToken\"] = request.SecurityToken\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ShardCount)) {\n\t\tquery[\"ShardCount\"] = request.ShardCount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SourceBiz)) {\n\t\tquery[\"SourceBiz\"] = request.SourceBiz\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.VSwitchId)) {\n\t\tquery[\"VSwitchId\"] = request.VSwitchId\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"AddShardingNode\"),\n\t\tVersion: tea.String(\"2015-01-01\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &AddShardingNodeResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func addNode(address, username, password, name, bundle string, approve bool) (string, error) {\n\tvar ret string\n\n\t// Build the request body.\n\tenrolBody := types.NodeEnrollmentBody{\n\t\tAddress: address,\n\t\tName: name,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tAutoApprove: !approve, // user specifies if they dont want it\n\t\tCallHome: false,\n\t}\n\tif bundle != \"\" {\n\t\tenrolBody.Bundle = bundle\n\t\tenrolBody.Hostname = name\n\t\tenrolBody.CallHome = true\n\t}\n\trequest := types.EnrollmentRequest{\n\t\tEnrollment: enrolBody,\n\t}\n\treqJSON, err := json.Marshal(&request)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\turl, err := client.GetURL(nodeURI)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\treq, err := client.BuildReq(&reqJSON, url, http.MethodPost, true)\n\trawResp, err := client.HTTPClient().Do(req)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\t_, err = client.ParseReq(rawResp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\treturn \"Node added successfully\\n\", nil\n}", "func createNewNodeNetworkObject(writer *bufio.Writer, sourceOsmNode *osm.Node) {\n\ttags := sourceOsmNode.TagMap()\n\n\t// Punktnetzwerk 'Fahrrad'\n\tnewOsmNode := *sourceOsmNode // copy content (don't modify origin/source node)\n\tnewOsmNode.ID = 0\n\tnewOsmNode.Tags = []osm.Tag{} // remove all source tags\n\trefValue, found := tags[\"icn_ref\"]\n\tif found {\n\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_bicycle\"}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\twriteNewNodeObject(writer, &newOsmNode)\n\t} else {\n\t\trefValue, found = tags[\"ncn_ref\"]\n\t\tif found {\n\t\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_bicycle\"}\n\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\twriteNewNodeObject(writer, &newOsmNode)\n\t\t} else {\n\t\t\trefValue, found = tags[\"rcn_ref\"]\n\t\t\tif found {\n\t\t\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_bicycle\"}\n\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\twriteNewNodeObject(writer, &newOsmNode)\n\t\t\t} else {\n\t\t\t\trefValue, found = tags[\"lcn_ref\"]\n\t\t\t\tif found {\n\t\t\t\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_bicycle\"}\n\t\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\t\twriteNewNodeObject(writer, &newOsmNode)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Punktnetzwerk 'Wandern'\n\tnewOsmNode = *sourceOsmNode // copy content (don't modify origin/source node)\n\tnewOsmNode.ID = 0\n\tnewOsmNode.Tags = []osm.Tag{} // remove all source tags\n\trefValue, found = tags[\"iwn_ref\"]\n\tif found {\n\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_hiking\"}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\twriteNewNodeObject(writer, &newOsmNode)\n\t} else {\n\t\trefValue, found = tags[\"nwn_ref\"]\n\t\tif found {\n\t\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_hiking\"}\n\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\twriteNewNodeObject(writer, &newOsmNode)\n\t\t} else {\n\t\t\trefValue, found = tags[\"rwn_ref\"]\n\t\t\tif found {\n\t\t\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_hiking\"}\n\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\twriteNewNodeObject(writer, &newOsmNode)\n\t\t\t} else {\n\t\t\t\trefValue, found = tags[\"lwn_ref\"]\n\t\t\t\tif found {\n\t\t\t\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_hiking\"}\n\t\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\t\twriteNewNodeObject(writer, &newOsmNode)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Punktnetzwerk 'Inline-Skaten'\n\tnewOsmNode = *sourceOsmNode // copy content (don't modify origin/source node)\n\tnewOsmNode.ID = 0\n\tnewOsmNode.Tags = []osm.Tag{} // remove all source tags\n\trefValue, found = tags[\"rin_ref\"]\n\tif found {\n\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_inline_skates\"}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\twriteNewNodeObject(writer, &newOsmNode)\n\t}\n\n\t// Punktnetzwerk 'Reiten'\n\tnewOsmNode = *sourceOsmNode // copy content (don't modify origin/source node)\n\tnewOsmNode.ID = 0\n\tnewOsmNode.Tags = []osm.Tag{} // remove all source tags\n\trefValue, found = tags[\"rhn_ref\"]\n\tif found {\n\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_horse\"}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\twriteNewNodeObject(writer, &newOsmNode)\n\t}\n\n\t// Punktnetzwerk 'Kanu'\n\tnewOsmNode = *sourceOsmNode // copy content (don't modify origin/source node)\n\tnewOsmNode.ID = 0\n\tnewOsmNode.Tags = []osm.Tag{} // remove all source tags\n\trefValue, found = tags[\"rpn_ref\"]\n\tif found {\n\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_canoe\"}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\twriteNewNodeObject(writer, &newOsmNode)\n\t}\n\n\t// Punktnetzwerk 'Motorboot'\n\tnewOsmNode = *sourceOsmNode // copy content (don't modify origin/source node)\n\tnewOsmNode.ID = 0\n\tnewOsmNode.Tags = []osm.Tag{} // remove all source tags\n\trefValue, found = tags[\"rmn_ref\"]\n\tif found {\n\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_motorboat\"}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\twriteNewNodeObject(writer, &newOsmNode)\n\t}\n}", "func (auth *EdgeSampleAuth) AddNodeCredentials(key string, secret string) {\n\tauth.NodeCredentials = NodeCredentials{key, secret} \n}", "func newResponseNode(model string, hash string, version *big.Int, sim *backends.SimulatedBackend) {\n\topts := mqtt.NewClientOptions().AddBroker(\"tcp://localhost:1883\")\n\tclient := mqtt.NewClient(opts)\n\ttoken := client.Connect()\n\tif token.Wait() && token.Error() != nil {\n\t\tlog.Fatalln(token.Error())\n\t}\n\n\tvar messageHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {\n\t\tcontract, _ := contracts.NewVerifier(common.HexToAddress(string(msg.Payload())), sim)\n\t\tsendResponse(sim, contract, hash, version)\n\t}\n\ttoken = client.Subscribe(model, 0, messageHandler)\n\tif token.Wait() && token.Error() != nil {\n\t\tlog.Fatalln(token.Error())\n\t}\n}", "func CreateBucket(w http.ResponseWriter, r *http.Request) *appError {\n decoder := json.NewDecoder(r.Body)\n var ecsBucket ECSBucket\n err := decoder.Decode(&ecsBucket)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n headers := make(map[string][]string)\n if ecsBucket.ReplicationGroup != \"\" {\n headers[\"x-emc-vpool\"] = []string{ecsBucket.ReplicationGroup}\n }\n if ecsBucket.MetadataSearch != \"\" {\n headers[\"x-emc-metadata-search\"] = []string{ecsBucket.MetadataSearch}\n }\n if ecsBucket.EnableADO {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"false\"}\n }\n if ecsBucket.EnableFS {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableCompliance {\n headers[\"x-emc-compliance-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-compliance-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableEncryption {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"false\"}\n }\n retentionEnabled := false\n headers[\"x-emc-retention-period\"] = []string{\"0\"}\n if ecsBucket.Retention != \"\" {\n days, err := strconv.ParseInt(ecsBucket.Retention, 10, 64)\n if err == nil {\n if days > 0 {\n seconds := days * 24 * 3600\n headers[\"x-emc-retention-period\"] = []string{int64toString(seconds)}\n retentionEnabled = true\n }\n }\n }\n var expirationCurrentVersions int64\n expirationCurrentVersions = 0\n if ecsBucket.ExpirationCurrentVersions != \"\" {\n days, err := strconv.ParseInt(ecsBucket.ExpirationCurrentVersions, 10, 64)\n if err == nil {\n expirationCurrentVersions = days\n }\n }\n var expirationNonCurrentVersions int64\n expirationNonCurrentVersions = 0\n if ecsBucket.ExpirationNonCurrentVersions != \"\" {\n days, err := strconv.ParseInt(ecsBucket.ExpirationNonCurrentVersions, 10, 64)\n if err == nil && ecsBucket.EnableVersioning {\n expirationNonCurrentVersions = days\n }\n }\n var bucketCreateResponse Response\n if ecsBucket.Api == \"s3\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = s3Request(s3, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: err.Error()}\n }\n versioningStatusOK := true\n lifecyclePolicyStatusOK := true\n // If the bucket has been created\n if bucketCreateResponse.Code == 200 {\n if !retentionEnabled && ecsBucket.EnableVersioning {\n // Enable versioning\n enableVersioningHeaders := map[string][]string{}\n enableVersioningHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n versioningConfiguration := `\n <VersioningConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n <Status>Enabled</Status>\n <MfaDelete>Disabled</MfaDelete>\n </VersioningConfiguration>\n `\n enableVersioningResponse, _ := s3Request(s3, ecsBucket.Name, \"PUT\", \"/?versioning\", enableVersioningHeaders, versioningConfiguration)\n if enableVersioningResponse.Code != 200 {\n versioningStatusOK = false\n }\n }\n if expirationCurrentVersions > 0 || expirationNonCurrentVersions > 0 {\n lifecyclePolicyHeaders := map[string][]string{}\n lifecyclePolicyHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n lifecyclePolicyConfiguration := `\n <LifecycleConfiguration>\n <Rule>\n <ID>expiration</ID>\n <Prefix></Prefix>\n <Status>Enabled</Status>\n `\n if expirationCurrentVersions > 0 && expirationNonCurrentVersions > 0 {\n // Enable expiration for both current and non current versions\n lifecyclePolicyConfiguration += \"<Expiration><Days>\" + ecsBucket.ExpirationCurrentVersions + \"</Days></Expiration>\"\n lifecyclePolicyConfiguration += \"<NoncurrentVersionExpiration><NoncurrentDays>\" + ecsBucket.ExpirationNonCurrentVersions + \"</NoncurrentDays></NoncurrentVersionExpiration>\"\n } else {\n if expirationCurrentVersions > 0 {\n // Enable expiration for current versions only\n lifecyclePolicyConfiguration += \"<Expiration><Days>\" + ecsBucket.ExpirationCurrentVersions + \"</Days></Expiration>\"\n }\n if expirationNonCurrentVersions > 0 {\n // Enable expiration for non current versions only\n // To fix a bug in ECS 3.0 where an expiration for non current version can't be set if there's no expiration set for current versions\n lifecyclePolicyConfiguration += \"<Expiration><Days>1000000</Days></Expiration>\"\n lifecyclePolicyConfiguration += \"<NoncurrentVersionExpiration><NoncurrentDays>\" + ecsBucket.ExpirationNonCurrentVersions + \"</NoncurrentDays></NoncurrentVersionExpiration>\"\n }\n }\n lifecyclePolicyConfiguration += `\n </Rule>\n </LifecycleConfiguration>\n `\n lifecyclePolicyResponse, _ := s3Request(s3, ecsBucket.Name, \"PUT\", \"/?lifecycle\", lifecyclePolicyHeaders, lifecyclePolicyConfiguration)\n if lifecyclePolicyResponse.Code != 200 {\n lifecyclePolicyStatusOK = false\n }\n }\n if versioningStatusOK && lifecyclePolicyStatusOK {\n rendering.JSON(w, http.StatusOK, \"\")\n } else {\n message := \"\"\n if !versioningStatusOK {\n message += \" Versioning can't be enabled.\"\n }\n if !lifecyclePolicyStatusOK {\n message += \" Expiration can't be set.\"\n }\n rendering.JSON(w, http.StatusOK, message)\n }\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"swift\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = swiftRequest(ecsBucket.Endpoint, s3.AccessKey, ecsBucket.Password, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: err.Error()}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, ecsBucket.Name)\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"atmos\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = atmosRequest(ecsBucket.Endpoint, s3.AccessKey, s3.SecretKey, \"\", \"PUT\", \"/rest/subtenant\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: err.Error()}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, bucketCreateResponse.ResponseHeaders[\"Subtenantid\"][0])\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n }\n\n return nil\n}", "func (zic *ZoneInterconnectHandler) AddRemoteZoneNode(node *corev1.Node) error {\n\tklog.Infof(\"Creating interconnect resources for remote zone node %s for the network %s\", node.Name, zic.GetNetworkName())\n\n\tnodeID := util.GetNodeID(node)\n\tif nodeID == -1 {\n\t\t// Don't consider this node as cluster-manager has not allocated node id yet.\n\t\treturn fmt.Errorf(\"failed to get node id for node - %s\", node.Name)\n\t}\n\n\t// Get the chassis id.\n\tchassisId, err := util.ParseNodeChassisIDAnnotation(node)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse node chassis-id for node - %s, error: %w\", node.Name, err)\n\t}\n\n\tif err := zic.createRemoteZoneNodeResources(node, nodeID, chassisId); err != nil {\n\t\treturn fmt.Errorf(\"creating interconnect resources for remote zone node %s for the network %s failed : err - %w\", node.Name, zic.GetNetworkName(), err)\n\t}\n\n\treturn nil\n}", "func RegisterNode(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Register Node called\")\n\tdecoder := json.NewDecoder(r.Body)\n\tvar signedNode models.SignedPeer\n\terr := decoder.Decode(&signedNode)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to decode request to register node. Incorrect format\")\n\t}\n\tvar nodeListJSON string\n\tpeerNode, ok := nodeList[signedNode.PeerNode.PeerId]\n\tif !ok {\n\t\tif(signedNode.PeerNode.VerifyPeerSignature(signedNode.SignedPeerNode)){\n\t\t\tfmt.Println(\"Signature Verified for new user. Register Successful\")\n\t\t\tnodeList[signedNode.PeerNode.PeerId] = signedNode.PeerNode\n\t\t\tnodeListJSON = nodeList.GetNodeListJSON()\n\t\t}else{\n\t\t\tnodeListJSON = \"{}\"\n\t\t}\n\t}else{\n\t\tfmt.Println(\"Peer Id already registered with this uuid.\")\n\t\tif(peerNode.VerifyPeerSignature(signedNode.SignedPeerNode)){\n\t\t\tfmt.Println(\"Verified with old public key. Updating key pair\")\n\t\t\tnodeList[signedNode.PeerNode.PeerId] = signedNode.PeerNode\n\t\t\tnodeListJSON = nodeList.GetNodeListJSON()\n\t\t}else{\n\t\t\tnodeListJSON = \"{}\"\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(nodeListJSON))\n}", "func (p *Pacemaker) AddNode(rid uint64, cli TiKVClient) {\n\tlg.Debug(\"add tikv client to txn\", zap.Uint64(\"txnid\", p.txnid))\n\tp.Lock()\n\tif _, ok := p.kvnodes[rid]; !ok {\n\t\tp.kvnodes[rid] = cli\n\t}\n\tp.Unlock()\n}", "func CreateBucket(w http.ResponseWriter, r *http.Request) *appError {\n decoder := json.NewDecoder(r.Body)\n var ecsBucket ECSBucket\n err := decoder.Decode(&ecsBucket)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n headers := make(map[string][]string)\n if ecsBucket.ReplicationGroup != \"\" {\n headers[\"x-emc-vpool\"] = []string{ecsBucket.ReplicationGroup}\n }\n if ecsBucket.MetadataSearch != \"\" {\n headers[\"x-emc-metadata-search\"] = []string{ecsBucket.MetadataSearch}\n }\n if ecsBucket.EnableADO {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-is-stale-allowed\"] = []string{\"false\"}\n }\n if ecsBucket.EnableFS {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-file-system-access-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableCompliance {\n headers[\"x-emc-compliance-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-compliance-enabled\"] = []string{\"false\"}\n }\n if ecsBucket.EnableEncryption {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"true\"}\n } else {\n headers[\"x-emc-server-side-encryption-enabled\"] = []string{\"false\"}\n }\n var bucketCreateResponse Response\n if ecsBucket.Api == \"s3\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = s3Request(s3, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n if bucketCreateResponse.Code == 200 {\n rendering.JSON(w, http.StatusOK, ecsBucket.Name)\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"swift\" {\n bucketCreateResponse, err = swiftRequest(ecsBucket.Endpoint, ecsBucket.User, ecsBucket.Password, ecsBucket.Name, \"PUT\", \"/\", headers, \"\")\n log.Print(bucketCreateResponse)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, ecsBucket.Name)\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n } else if ecsBucket.Api == \"atmos\" {\n s3, err := getS3(r)\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n bucketCreateResponse, err = atmosRequest(ecsBucket.Endpoint, s3.AccessKey, s3.SecretKey, \"\", \"PUT\", \"/rest/subtenant\", headers, \"\")\n if err != nil {\n log.Print(err)\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n if bucketCreateResponse.Code >= 200 && bucketCreateResponse.Code < 300 {\n rendering.JSON(w, http.StatusOK, bucketCreateResponse.ResponseHeaders[\"Subtenantid\"][0])\n } else {\n return &appError{err: err, status: http.StatusInternalServerError, xml: bucketCreateResponse.Body}\n }\n }\n\n return nil\n}", "func newServiceNode(port int, httpport int, wsport int, modules ...string) (*node.Node, error) {\n\tcfg := &node.DefaultConfig\n\tcfg.P2P.ListenAddr = fmt.Sprintf(\":%d\", port)\n\tcfg.P2P.EnableMsgEvents = true\n\tcfg.P2P.NoDiscovery = true\n\tcfg.IPCPath = ipcpath\n\tcfg.DataDir = fmt.Sprintf(\"%s%d\", datadirPrefix, port)\n\tif httpport > 0 {\n\t\tcfg.HTTPHost = node.DefaultHTTPHost\n\t\tcfg.HTTPPort = httpport\n\t}\n\tif wsport > 0 {\n\t\tcfg.WSHost = node.DefaultWSHost\n\t\tcfg.WSPort = wsport\n\t\tcfg.WSOrigins = []string{\"*\"}\n\t\tfor i := 0; i < len(modules); i++ {\n\t\t\tcfg.WSModules = append(cfg.WSModules, modules[i])\n\t\t}\n\t}\n\tstack, err := node.New(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ServiceNode create fail: %v\", err)\n\t}\n\treturn stack, nil\n}", "func newCbsNode(region string, volumeAttachLimit int64) (*cbsNode, error) {\n\tsecretID, secretKey, token, _ := util.GetSercet()\n\tcred := &common.Credential{\n\t\tSecretId: secretID,\n\t\tSecretKey: secretKey,\n\t\tToken: token,\n\t}\n\n\tclient, err := cbs.NewClient(cred, region, profile.NewClientProfile())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnode := cbsNode{\n\t\tmetadataClient: metadata.NewMetaData(http.DefaultClient),\n\t\tcbsClient: client,\n\t\tmounter: mount.SafeFormatAndMount{\n\t\t\tInterface: mount.New(\"\"),\n\t\t\tExec: exec.New(),\n\t\t},\n\t\tidempotent: util.NewIdempotent(),\n\t\tvolumeAttachLimit: volumeAttachLimit,\n\t}\n\treturn &node, nil\n}", "func (c *Client) Add(ctx context.Context, node NodeInfo) error {\n\trequest := protocol.Message{}\n\tresponse := protocol.Message{}\n\n\trequest.Init(4096)\n\tresponse.Init(4096)\n\n\tprotocol.EncodeAdd(&request, node.ID, node.Address)\n\n\tif err := c.protocol.Call(ctx, &request, &response); err != nil {\n\t\treturn err\n\t}\n\n\tif err := protocol.DecodeEmpty(&response); err != nil {\n\t\treturn err\n\t}\n\n\t// If the desired role is spare, there's nothing to do, since all newly\n\t// added nodes have the spare role.\n\tif node.Role == Spare {\n\t\treturn nil\n\t}\n\n\treturn c.Assign(ctx, node.ID, node.Role)\n}", "func (a API) AddNode(cmd *btcjson.AddNodeCmd) (e error) {\n\tRPCHandlers[\"addnode\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func AddReplicationTarget(nbmaster string, httpClient *http.Client, jwt string, stsName string, candId string)(int) {\n fmt.Printf(\"\\nSending a POST request to create with defaults...\\n\")\n\n\t//reader := bufio.NewReader(os.Stdin)\n\tIdSlice := strings.Split(candId, \":\")\n\n username := apiUtil.TakeInput(\"Enter target storage server username:\")\n\tpassword := apiUtil.TakeInput(\"Enter target storage server password:\")\n\n replicationtarget := map[string]interface{}{\n \"data\": map[string]interface{}{\n \"type\": \"replicationTargetRequest\",\n \"attributes\": map[string]interface{}{\n\t\t\t\t\"targetStorageServerInfo\": map[string]interface{}{\n \"targetMasterServer\": IdSlice[3],\n\t\t\t\t\t\"targetStorageServer\": IdSlice[1],\n\t\t\t\t\t\"targetStorageServerType\": IdSlice[0],\n\t\t\t\t\t\"targetMediaServer\": IdSlice[2]},\n\t\t\t\t\"targetStorageServerCredentials\": map[string]interface{}{\n\t\t\t\t\t\"userName\": username,\n\t\t\t\t\t\"password\": password}}}}\n\t\t\t\t\n\n\n stsRequest, _ := json.Marshal(replicationtarget)\n\n uri := \"https://\" + nbmaster + \":\" + port + \"/netbackup/\" + storageUri + storageServerUri + \"PureDisk:\" + stsName + replicationTargetsUri\n\n request, _ := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(stsRequest))\n request.Header.Add(\"Content-Type\", contentType);\n request.Header.Add(\"Authorization\", jwt);\n\n fmt.Println (\"Firing request: POST: \" + uri)\n response, err := httpClient.Do(request)\n\n if err != nil {\n fmt.Printf(\"The HTTP request failed with error: %s\\n\", err)\n panic(\"Unable to add replication target.\\n\")\n } else {\n if response.StatusCode != 201 {\n responseBody, _ := ioutil.ReadAll(response.Body)\n fmt.Printf(\"%s\\n\", responseBody)\n panic(\"Unable to add replication target.\\n\")\n } else {\n fmt.Printf(\"%s created successfully.\\n\", \"\");\n //responseDetails, _ := httputil.DumpResponse(response, true);\n apiUtil.AskForResponseDisplay(response.Body)\n }\n }\n\t\n\treturn response.StatusCode;\n}", "func (o *AddRemoteRDSNodeDefaultBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateDetails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceMplsTeGlobalAttributesSrlgs(ctx context.Context, name string, frinxOpenconfigMplsMplstesrlgtopSrlgsBodyParam FrinxOpenconfigMplsMplstesrlgtopSrlgsRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:mpls/frinx-openconfig-network-instance:te-global-attributes/frinx-openconfig-network-instance:srlgs/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigMplsMplstesrlgtopSrlgsBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func NewRemoteNode(addr string, port int) *RemoteNode {\n\tnode := &RemoteNode{BaseNode: NewBaseNode(), Address: addr, Port: port}\n\treturn node\n}", "func NewRemote(conn *server.Connection) *RemoteConfig {\n\treturn &RemoteConfig{\n\t\tconn: conn,\n\t\tfile: \".steer-revision\",\n\t}\n}", "func createNewNode(ctx context.Context, nodeName string, virtual bool, clientset kubernetes.Interface) (*corev1.Node, error) {\n\tresources := corev1.ResourceList{}\n\tresources[corev1.ResourceCPU] = *resource.NewScaledQuantity(5000, resource.Milli)\n\tresources[corev1.ResourceMemory] = *resource.NewScaledQuantity(5, resource.Mega)\n\tnode := &corev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: nodeName,\n\t\t},\n\t}\n\tif virtual {\n\t\tnode.Labels = map[string]string{\n\t\t\tconsts.TypeLabel: consts.TypeNode,\n\t\t}\n\t}\n\tnode.Status = corev1.NodeStatus{\n\t\tCapacity: resources,\n\t\tAllocatable: resources,\n\t\tConditions: []corev1.NodeCondition{\n\t\t\t0: {\n\t\t\t\tType: corev1.NodeReady,\n\t\t\t\tStatus: corev1.ConditionTrue,\n\t\t\t},\n\t\t},\n\t}\n\tnode, err := clientset.CoreV1().Nodes().Create(ctx, node, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn node, nil\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceMplsTeGlobalAttributesSrlgsSrlg(ctx context.Context, name string, srlgName string, frinxOpenconfigMplsMplstesrlgtopSrlgsSrlgBodyParam FrinxOpenconfigMplsMplstesrlgtopSrlgsSrlgRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:mpls/frinx-openconfig-network-instance:te-global-attributes/frinx-openconfig-network-instance:srlgs/frinx-openconfig-network-instance:srlg/{srlg-name}/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"srlg-name\"+\"}\", fmt.Sprintf(\"%v\", srlgName), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigMplsMplstesrlgtopSrlgsSrlgBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (config *AppConfig) CreateNode(newNode NodeAttributes) (node Node, err error) {\n\tendpoint := fmt.Sprintf(\"nodes/\")\n\n\tnewNodeBytes, err := json.Marshal(newNode)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// get json bytes from the panel.\n\tnodeBytes, err := config.queryApplicationAPI(endpoint, \"post\", newNodeBytes)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Get server info from the panel\n\t// Unmarshal the bytes to a usable struct.\n\terr = json.Unmarshal(nodeBytes, &node)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func createNode(w http.ResponseWriter, r *http.Request) {\n\tvar newNode* Nodo\n\t//leemos el body de la petición\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Datos Inválidos\")\n\t}\n\t//tomamos los valores del body y los colocamos en una variable de struct de Nodo\n\tjson.Unmarshal(reqBody, &newNode)\n\t//fmt.Printf(\"%d\",newNode.Carnet)\n\t//insertamos la raiz\n\traiz=crearNodo(raiz,newNode)\n\tescribir,err2:=json.Marshal(raiz)\n\tif err2 != nil {\n log.Fatal(err2)\n }\n\tdata := []byte(escribir)\n err = ioutil.WriteFile(\"persiste.json\", data, 0644)\n if err != nil {\n log.Fatal(err)\n }\n\tfmt.Println(\"----------------\")\n\t//preorden(raiz)\n\t//createDot(raiz)\n\t//Si todo ha salido bien, devolvemos un status code 201 y el arbol\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\trespuesta:= &Respuesta{Message:\"Alumno creado exitosamente\"}\n\tw.WriteHeader(http.StatusCreated)\n\tjson.NewEncoder(w).Encode(respuesta)\n\n}", "func (rm *resourceManager) newCreateRequestPayload(\n\tctx context.Context,\n\tr *resource,\n) (*svcsdk.CreateVpcPeeringConnectionInput, error) {\n\tres := &svcsdk.CreateVpcPeeringConnectionInput{}\n\n\tif r.ko.Spec.DryRun != nil {\n\t\tres.SetDryRun(*r.ko.Spec.DryRun)\n\t}\n\tif r.ko.Spec.PeerOwnerID != nil {\n\t\tres.SetPeerOwnerId(*r.ko.Spec.PeerOwnerID)\n\t}\n\tif r.ko.Spec.PeerRegion != nil {\n\t\tres.SetPeerRegion(*r.ko.Spec.PeerRegion)\n\t}\n\tif r.ko.Spec.PeerVPCID != nil {\n\t\tres.SetPeerVpcId(*r.ko.Spec.PeerVPCID)\n\t}\n\tif r.ko.Spec.TagSpecifications != nil {\n\t\tf4 := []*svcsdk.TagSpecification{}\n\t\tfor _, f4iter := range r.ko.Spec.TagSpecifications {\n\t\t\tf4elem := &svcsdk.TagSpecification{}\n\t\t\tif f4iter.ResourceType != nil {\n\t\t\t\tf4elem.SetResourceType(*f4iter.ResourceType)\n\t\t\t}\n\t\t\tif f4iter.Tags != nil {\n\t\t\t\tf4elemf1 := []*svcsdk.Tag{}\n\t\t\t\tfor _, f4elemf1iter := range f4iter.Tags {\n\t\t\t\t\tf4elemf1elem := &svcsdk.Tag{}\n\t\t\t\t\tif f4elemf1iter.Key != nil {\n\t\t\t\t\t\tf4elemf1elem.SetKey(*f4elemf1iter.Key)\n\t\t\t\t\t}\n\t\t\t\t\tif f4elemf1iter.Value != nil {\n\t\t\t\t\t\tf4elemf1elem.SetValue(*f4elemf1iter.Value)\n\t\t\t\t\t}\n\t\t\t\t\tf4elemf1 = append(f4elemf1, f4elemf1elem)\n\t\t\t\t}\n\t\t\t\tf4elem.SetTags(f4elemf1)\n\t\t\t}\n\t\t\tf4 = append(f4, f4elem)\n\t\t}\n\t\tres.SetTagSpecifications(f4)\n\t}\n\tif r.ko.Spec.VPCID != nil {\n\t\tres.SetVpcId(*r.ko.Spec.VPCID)\n\t}\n\n\treturn res, nil\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceMplsSignalingProtocolsRsvpTeGlobal(ctx context.Context, name string, frinxOpenconfigMplsRsvpRsvpglobalRsvpteGlobalBodyParam FrinxOpenconfigMplsRsvpRsvpglobalRsvpteGlobalRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:mpls/frinx-openconfig-network-instance:signaling-protocols/frinx-openconfig-network-instance:rsvp-te/frinx-openconfig-network-instance:global/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigMplsRsvpRsvpglobalRsvpteGlobalBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (rm *resourceManager) newCreateRequestPayload(\n\tr *resource,\n) (*svcsdk.CreateStageInput, error) {\n\tres := &svcsdk.CreateStageInput{}\n\n\tif r.ko.Spec.AccessLogSettings != nil {\n\t\tf0 := &svcsdk.AccessLogSettings{}\n\t\tif r.ko.Spec.AccessLogSettings.DestinationARN != nil {\n\t\t\tf0.SetDestinationArn(*r.ko.Spec.AccessLogSettings.DestinationARN)\n\t\t}\n\t\tif r.ko.Spec.AccessLogSettings.Format != nil {\n\t\t\tf0.SetFormat(*r.ko.Spec.AccessLogSettings.Format)\n\t\t}\n\t\tres.SetAccessLogSettings(f0)\n\t}\n\tif r.ko.Spec.APIID != nil {\n\t\tres.SetApiId(*r.ko.Spec.APIID)\n\t}\n\tif r.ko.Spec.AutoDeploy != nil {\n\t\tres.SetAutoDeploy(*r.ko.Spec.AutoDeploy)\n\t}\n\tif r.ko.Spec.ClientCertificateID != nil {\n\t\tres.SetClientCertificateId(*r.ko.Spec.ClientCertificateID)\n\t}\n\tif r.ko.Spec.DefaultRouteSettings != nil {\n\t\tf4 := &svcsdk.RouteSettings{}\n\t\tif r.ko.Spec.DefaultRouteSettings.DataTraceEnabled != nil {\n\t\t\tf4.SetDataTraceEnabled(*r.ko.Spec.DefaultRouteSettings.DataTraceEnabled)\n\t\t}\n\t\tif r.ko.Spec.DefaultRouteSettings.DetailedMetricsEnabled != nil {\n\t\t\tf4.SetDetailedMetricsEnabled(*r.ko.Spec.DefaultRouteSettings.DetailedMetricsEnabled)\n\t\t}\n\t\tif r.ko.Spec.DefaultRouteSettings.LoggingLevel != nil {\n\t\t\tf4.SetLoggingLevel(*r.ko.Spec.DefaultRouteSettings.LoggingLevel)\n\t\t}\n\t\tif r.ko.Spec.DefaultRouteSettings.ThrottlingBurstLimit != nil {\n\t\t\tf4.SetThrottlingBurstLimit(*r.ko.Spec.DefaultRouteSettings.ThrottlingBurstLimit)\n\t\t}\n\t\tif r.ko.Spec.DefaultRouteSettings.ThrottlingRateLimit != nil {\n\t\t\tf4.SetThrottlingRateLimit(*r.ko.Spec.DefaultRouteSettings.ThrottlingRateLimit)\n\t\t}\n\t\tres.SetDefaultRouteSettings(f4)\n\t}\n\tif r.ko.Spec.DeploymentID != nil {\n\t\tres.SetDeploymentId(*r.ko.Spec.DeploymentID)\n\t}\n\tif r.ko.Spec.Description != nil {\n\t\tres.SetDescription(*r.ko.Spec.Description)\n\t}\n\tif r.ko.Spec.RouteSettings != nil {\n\t\tf7 := map[string]*svcsdk.RouteSettings{}\n\t\tfor f7key, f7valiter := range r.ko.Spec.RouteSettings {\n\t\t\tf7val := &svcsdk.RouteSettings{}\n\t\t\tif f7valiter.DataTraceEnabled != nil {\n\t\t\t\tf7val.SetDataTraceEnabled(*f7valiter.DataTraceEnabled)\n\t\t\t}\n\t\t\tif f7valiter.DetailedMetricsEnabled != nil {\n\t\t\t\tf7val.SetDetailedMetricsEnabled(*f7valiter.DetailedMetricsEnabled)\n\t\t\t}\n\t\t\tif f7valiter.LoggingLevel != nil {\n\t\t\t\tf7val.SetLoggingLevel(*f7valiter.LoggingLevel)\n\t\t\t}\n\t\t\tif f7valiter.ThrottlingBurstLimit != nil {\n\t\t\t\tf7val.SetThrottlingBurstLimit(*f7valiter.ThrottlingBurstLimit)\n\t\t\t}\n\t\t\tif f7valiter.ThrottlingRateLimit != nil {\n\t\t\t\tf7val.SetThrottlingRateLimit(*f7valiter.ThrottlingRateLimit)\n\t\t\t}\n\t\t\tf7[f7key] = f7val\n\t\t}\n\t\tres.SetRouteSettings(f7)\n\t}\n\tif r.ko.Spec.StageName != nil {\n\t\tres.SetStageName(*r.ko.Spec.StageName)\n\t}\n\tif r.ko.Spec.StageVariables != nil {\n\t\tf9 := map[string]*string{}\n\t\tfor f9key, f9valiter := range r.ko.Spec.StageVariables {\n\t\t\tvar f9val string\n\t\t\tf9val = *f9valiter\n\t\t\tf9[f9key] = &f9val\n\t\t}\n\t\tres.SetStageVariables(f9)\n\t}\n\tif r.ko.Spec.Tags != nil {\n\t\tf10 := map[string]*string{}\n\t\tfor f10key, f10valiter := range r.ko.Spec.Tags {\n\t\t\tvar f10val string\n\t\t\tf10val = *f10valiter\n\t\t\tf10[f10key] = &f10val\n\t\t}\n\t\tres.SetTags(f10)\n\t}\n\n\treturn res, nil\n}", "func (s *Server) CreateNode(w http.ResponseWriter, req *http.Request) {\n\tconfig := peer.RandomNodeConfig()\n\terr := json.NewDecoder(req.Body).Decode(config)\n\tif err != nil && err != io.EOF {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tnode, err := s.network.NewNodeWithConfig(config)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\ts.JSON(w, http.StatusCreated, &node.ID)\n}", "func AddNewNode(root *Node, node *Node) *Node {\n\t// set the new node to red\n\tnode.Color = Red\n\n\troot = addOneNode(root, Left, node)\n\n\t// reset root color\n\troot.Color = Black\n\n\treturn root\n}", "func newTestRawNode(id uint64, peers []uint64, election, heartbeat int, storage Storage) *RawNode {\n\tcfg := newTestConfig(id, peers, election, heartbeat, storage)\n\trn, err := NewRawNode(cfg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn rn\n}", "func newRsaKeyPair(config CreateKeyPairConfig) (KeyPair, error) {\n\tif config.Bits == 0 {\n\t\tconfig.Bits = defaultRsaBits\n\t}\n\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, config.Bits)\n\tif err != nil {\n\t\treturn KeyPair{}, err\n\t}\n\n\tsshPublicKey, err := gossh.NewPublicKey(&privateKey.PublicKey)\n\tif err != nil {\n\t\treturn KeyPair{}, err\n\t}\n\n\tprivatePemBlock, err := rawPemBlock(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\",\n\t\tHeaders: nil,\n\t\tBytes: x509.MarshalPKCS1PrivateKey(privateKey),\n\t})\n\tif err != nil {\n\t\treturn KeyPair{}, err\n\t}\n\n\treturn KeyPair{\n\t\tPrivateKeyPemBlock: privatePemBlock,\n\t\tPublicKeyAuthorizedKeysLine: authorizedKeysLine(sshPublicKey, config.Comment),\n\t\tComment: config.Comment,\n\t}, nil\n}", "func CreateDescribeDialogueNodeStatisticsRequest() (request *DescribeDialogueNodeStatisticsRequest) {\n\trequest = &DescribeDialogueNodeStatisticsRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"OutboundBot\", \"2019-12-26\", \"DescribeDialogueNodeStatistics\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateOrUpdate(ctx context.Context, client client.Interface, node *libapi.Node) (*libapi.Node, error) {\n\tif node.ResourceVersion != \"\" {\n\t\treturn client.Nodes().Update(ctx, node, options.SetOptions{})\n\t}\n\n\treturn client.Nodes().Create(ctx, node, options.SetOptions{})\n}", "func CreateRemote(peers []string) *RemoteCluster {\n\tnodes := make([]node, len(peers))\n\tfor i := range nodes {\n\t\tnodes[i].Addr = peers[i]\n\t\tnodes[i].ID = fmt.Sprintf(\"roach%d\", i)\n\t\tnodes[i].Name = nodes[i].ID\n\t}\n\treturn &RemoteCluster{\n\t\tuser: *login,\n\t\tcert: *keyFile,\n\t\tnodes: nodes,\n\t}\n}", "func createLocalNode() {\n\t// Initialize the internal table\n\tinternalTable = NewTable(config.maxKey)\n\n\t// Set the variables of this node.\n\tvar err error\n\tcaller, err = NewNodeCaller(config.callerPort)\n\tif err != nil {\n\t\tpanic(\"rpcCaller failed to initialize\")\n\t}\n\terr = initNodeCallee(config.calleePort)\n\tif err != nil {\n\t\tpanic(\"rpcCallee failed to initialize\")\n\t}\n\n\tmy.address = fmt.Sprintf(\"%s:%d\", config.addr, config.calleePort)\n\n\tmy.key = Hash(my.address, config.maxKey)\n\tlog.Printf(\"[NODE %d] Keyspace position %d was derived from address %s\\n\", my.key, my.key, my.address)\n\n\tpredecessor = nil\n\tsuccessor = &RemoteNode{\n\t\tAddress: my.address,\n\t\tKey: my.key,\n\t}\n\t// Initialize the finger table for the solo ring configuration\n\tfingers = make([]*RemoteNode, config.numFingers)\n\tlog.Printf(\"[NODE %d] Finger table size %d was derived from the keyspace size\\n\", my.key, config.numFingers)\n\tfor i := uint64(0); i < config.numFingers; i++ {\n\t\tfingers[i] = successor\n\t}\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceMplsSignalingProtocolsRsvpTeGlobalHellos(ctx context.Context, name string, frinxOpenconfigMplsRsvpMplsrsvphellosHellosBodyParam FrinxOpenconfigMplsRsvpMplsrsvphellosHellosRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:mpls/frinx-openconfig-network-instance:signaling-protocols/frinx-openconfig-network-instance:rsvp-te/frinx-openconfig-network-instance:global/frinx-openconfig-network-instance:hellos/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigMplsRsvpMplsrsvphellosHellosBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (c *Client) newHostgroup(hostgroup *Hostgroup) ([]byte, error) {\n\tnagiosURL, err := c.buildURL(\"hostgroup\", \"POST\", \"\", \"\", \"\", \"\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := setURLParams(hostgroup)\n\n\tbody, err := c.post(data, nagiosURL)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn body, nil\n}", "func newCreateClientTunnelReply(cidr *net.IPNet, tid int64) (f linkFrame) {\n f.method = CLIENT_TUN_NEW\n f.param = map[string]interface{} { K_CIDR : cidr.String() }\n f.response = tid\n return\n}", "func main() {\n\t// Env Vars\n\tawsRegion := os.Getenv(\"awsRegion\")\n\n\tsourceRDS := os.Getenv(\"sourceRDS\")\n\trestoreRDS := os.Getenv(\"restoreRDS\")\n\trdsSubnetGroup := os.Getenv(\"rdsSubnetGroup\")\n\trdsSecurityGroupId := os.Getenv(\"rdsSecurityGroupId\")\n\n\t// Optional restore date and time - defaults to latest available point in time\n\trestoreDate := os.Getenv(\"restoreDate\")\n\trestoreTime := os.Getenv(\"restoreTime\")\n\n\t// Optional instance type - defaults to db.t3.small\n\trdsInstanceType := os.Getenv(\"rdsInstanceType\")\n\n\t// Optional rds engine - defaults to aurora-mysql\n\trdsEngine := os.Getenv(\"rdsEngine\")\n\n\t// TODO: figure out how to add this to created cluster without too many conditionals\n\t // both on - db_cluster_parameter_group_name and db_parameter_group_name\n\n\t// Optional parameter group - defaults to default.aurora-mysql5.7\n\t//rdsParameterGroup := os.Getenv(\"rdsParameterGroup\")\n\n\t// Params\n\tvar restoreParams = map[string]string{\n\t\t\"awsRegion\": awsRegion,\n\t\t\"sourceRDS\": sourceRDS,\n\t\t\"restoreRDS\": restoreRDS,\n\t\t\"rdsSubnetGroup\": rdsSubnetGroup,\n\t\t\"rdsSecurityGroupId\": rdsSecurityGroupId,\n\t}\n\n\t// Init AWS Session and RDS Client\n\trdsClient, initErr := initRDSClient(awsRegion)\n\tif initErr != nil {\n\t\tfmt.Printf(\"Init Err: %v\", initErr)\n\t\tos.Exit(1)\n\t}\n\n\t// If date and time provided use it instead of last restorable time\n\tif restoreDate != \"\" {\n\t\tif restoreTime != \"\" {\n\t\t\trestoreParams[\"restoreFromTime\"] = restoreDate + \"T\" + restoreTime + \".000Z\"\n\t\t} else {\n\t\t\trestoreParams[\"restoreFromTime\"] = restoreDate + \"T01:00:00.000Z\"\n\t\t}\n\t\tfmt.Printf(\"Restore time set to %v\\n\", restoreParams[\"restoreFromTime\"])\n\t} else {\n\t\tfmt.Printf(\"Restore time set to latest available\\n\")\n\t}\n\n\t// If instance type provided change default\n\tif rdsInstanceType != \"\" {\n\t\trestoreParams[\"rdsInstanceType\"] = rdsInstanceType\n\t} else {\n\t\trestoreParams[\"rdsInstanceType\"] = \"db.t3.small\"\n\t}\n\n\t// If rds engine provided change default\n\tif rdsEngine != \"\" {\n\t\trestoreParams[\"rdsEngine\"] = rdsEngine\n\t} else {\n\t\trestoreParams[\"rdsEngine\"] = \"aurora-mysql\"\n\t}\n\n\t//// If rds parameter group provided change default\n\t//if rdsEngine != \"\" {\n\t\t//restoreParams[\"rdsParameterGroup\"] = rdsParameterGroup\n\t//} else {\n\t\t//restoreParams[\"rdsParameterGroup\"] = \"default.aurora-mysql5.7\"\n\t//}\n\n\t// Check if RDS instance exists, if it doesn't, skip Instance delete step\n\trdsInstanceExists, checkRDSInstanceExistsErr := rdsInstanceExists(rdsClient, restoreParams)\n\tif checkRDSInstanceExistsErr != nil {\n\t\tfmt.Printf(\"Check if RDS Instance exists Err: %v\", checkRDSInstanceExistsErr)\n\t\tos.Exit(1)\n\t}\n\n\t// Check if RDS instance exists, if it doesn't skip Instance delete step\n\tif rdsInstanceExists {\n\t\t// Delete RDS instance\n\t\tdeleteInstanceErr := deleteRDSInstance(rdsClient, restoreParams)\n\t\tif deleteInstanceErr != nil {\n\t\t\tfmt.Printf(\"Delete RDS Instance Err: %v\", deleteInstanceErr)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\twaitDeleteInstanceErr := waitUntilRDSInstanceDeleted(rdsClient, restoreParams)\n\t\tif waitDeleteInstanceErr != nil {\n\t\t\tfmt.Printf(\"Wait RDS Instance delete Err : %v\", waitDeleteInstanceErr)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t// Check if RDS cluster exists, if it doesn't, skip Cluster delete step\n\t// Should be executed only if Instance is deleted first, as instance deletion actually deletes cluster as well\n\trdsClusterExists, checkRDSClusterExistsErr := rdsClusterExists(rdsClient, restoreParams)\n\tif checkRDSClusterExistsErr != nil {\n\t\tfmt.Printf(\"Check if RDS Cluster exists Err: %v\", checkRDSClusterExistsErr)\n\t\tos.Exit(1)\n\t}\n\n\tif rdsClusterExists {\n\t\t// Delete RDS cluster\n\t\tdeleteClusterErr := deleteRDSCluster(rdsClient, restoreParams)\n\t\tif deleteClusterErr != nil {\n\t\t\tfmt.Printf(\"Delete RDS Cluster Err: %v\", deleteClusterErr)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\t// Wait until RDS Cluster is deleted\n\t\twaitDeleteClusterErr := waitUntilRDSClusterDeleted(rdsClient, restoreParams)\n\t\tif waitDeleteClusterErr != nil {\n\t\t\tfmt.Printf(\"Wait RDS Cluster delete Err : %v\", waitDeleteClusterErr)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t// Restore point in time RDS into a new cluster\n\trestoreErr := restorePointInTimeRDS(rdsClient, restoreParams)\n\tif restoreErr != nil {\n\t\tfmt.Printf(\"Restore Point-In-Time RDS Err: %v\", restoreErr)\n\t\tos.Exit(1)\n\t}\n\n\t// Wait until DB instance created\n\twaitClusterCreateErr := waitUntilRDSClusterCreated(rdsClient, restoreParams)\n\tif waitClusterCreateErr != nil {\n\t\tfmt.Printf(\"Wait RDS Cluster create Err: %v\", waitClusterCreateErr)\n\t\tos.Exit(1)\n\t}\n\n\t// Create RDS Instance in RDS Cluster\n\tcreateRDSInstanceErr := createRDSInstance(rdsClient, restoreParams)\n\tif createRDSInstanceErr != nil {\n\t\tfmt.Printf(\"Create RDS Instance Err: %v\", createRDSInstanceErr)\n\t\tos.Exit(1)\n\t}\n\n\t// Wait until DB instance created in RDS cluster\n\twaitInstanceCreateErr := waitUntilRDSInstanceCreated(rdsClient, restoreParams)\n\tif waitInstanceCreateErr != nil {\n\t\tfmt.Printf(\"Wait RDS Instance create Err: %v\", waitInstanceCreateErr)\n\t\tos.Exit(1)\n\t}\n}", "func createServer(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar newServer server\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t fmt.Println(err)\n\t\tfmt.Fprintf(w, \"Kindly enter data with the server's address, MSA and MTA network addresses only in order to create new server\")\n\t w.WriteHeader(http.StatusInternalServerError)\n\t return\n\t}\n\tnewServer.ID = strconv.Itoa(len(servers)+1)\n\n\tjson.Unmarshal(reqBody, &newServer)\n\tservers = append(servers, newServer)\n\tw.WriteHeader(http.StatusCreated)\n\n\tjson.NewEncoder(w).Encode(newServer)\n}", "func (client IdentityClient) createTagDefault(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/tagDefaults\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateTagDefaultResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func AddNode(address string) string {\n\turl := buildUrl(ADD_NODE)\n\tresp, e := Client.Get(url + \"?node=\" + address)\n\tif e != nil {\n\t\tfmt.Println(e)\n\t\treturn \"ERROR\"\n\t}\n\n\t//var data []byte\n\t//num, _ := resp.Body.Read(data)\n\tdefer resp.Body.Close()\n\n\tgetResp := new(GetResp)\n\n\tjson.NewDecoder(resp.Body).Decode(getResp)\n\t//json.Unmarshal(data, getResp)\n\tif getResp.Code == 200 {\n\t\treturn getResp.Data\n\t}\n\treturn getResp.Msg\n}", "func (*nodeR) NewStruct() *nodeR {\n\treturn &nodeR{}\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceMplsTeGlobalAttributesSrlgsSrlgConfig(ctx context.Context, name string, srlgName string, frinxOpenconfigMplsMplstesrlgtopSrlgsSrlgConfigBodyParam FrinxOpenconfigMplsMplstesrlgtopSrlgsSrlgConfigRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:mpls/frinx-openconfig-network-instance:te-global-attributes/frinx-openconfig-network-instance:srlgs/frinx-openconfig-network-instance:srlg/{srlg-name}/frinx-openconfig-network-instance:config/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"srlg-name\"+\"}\", fmt.Sprintf(\"%v\", srlgName), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigMplsMplstesrlgtopSrlgsSrlgConfigBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func RestPostVNet(c echo.Context) error {\n\n\tnsId := c.Param(\"nsId\")\n\n\tu := &vNetReq{}\n\tif err := c.Bind(u); err != nil {\n\t\treturn err\n\t}\n\n\t/*\n\t\taction := c.QueryParam(\"action\")\n\t\tfmt.Println(\"[POST VNet requested action: \" + action)\n\t\tif action == \"create\" {\n\t\t\tfmt.Println(\"[Creating VNet]\")\n\t\t\tcontent, _ := createVNet(nsId, u)\n\t\t\treturn c.JSON(http.StatusCreated, content)\n\n\t\t} else if action == \"register\" {\n\t\t\tfmt.Println(\"[Registering VNet]\")\n\t\t\tcontent, _ := registerVNet(nsId, u)\n\t\t\treturn c.JSON(http.StatusCreated, content)\n\n\t\t} else {\n\t\t\tmapA := map[string]string{\"message\": \"You must specify: action=create\"}\n\t\t\treturn c.JSON(http.StatusFailedDependency, &mapA)\n\t\t}\n\t*/\n\n\tfmt.Println(\"[POST VNet\")\n\tfmt.Println(\"[Creating VNet]\")\n\t//content, responseCode, body, err := createVNet(nsId, u)\n\tcontent, err := createVNet(nsId, u)\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\t/*\n\t\t\tmapA := map[string]string{\n\t\t\t\t\"message\": \"Failed to create a vNet\"}\n\t\t*/\n\t\t//return c.JSONBlob(responseCode, body)\n\t\tmapA := map[string]string{\"message\": err.Error()}\n\t\treturn c.JSON(http.StatusFailedDependency, &mapA)\n\t}\n\treturn c.JSON(http.StatusCreated, content)\n}", "func createNode(id int, myConf *Config, sm *State_Machine) cluster.Server {\n\tinitNode(id, myConf, sm)\n\t//Set up details about cluster nodes form json file.\n\tserver, err := cluster.New(id, \"config/cluster_config.json\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn server\n}", "func newConfig() (*config, error) {\n\tec2Metadata := ec2metadata.New(session.Must(session.NewSession()))\n\tregion, err := ec2Metadata.Region()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get region from ec2 metadata\")\n\t}\n\n\tinstanceID, err := ec2Metadata.GetMetadata(\"instance-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get instance id from ec2 metadata\")\n\t}\n\n\tmac, err := ec2Metadata.GetMetadata(\"mac\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get mac from ec2 metadata\")\n\t}\n\n\tsecurityGroups, err := ec2Metadata.GetMetadata(\"security-groups\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get security groups from ec2 metadata\")\n\t}\n\n\tinterfaces, err := ec2Metadata.GetMetadata(\"network/interfaces/macs\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get interfaces from ec2 metadata\")\n\t}\n\n\tsubnet, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/subnet-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get subnet from ec2 metadata\")\n\t}\n\n\tvpc, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/vpc-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get vpc from ec2 metadata\")\n\t}\n\n\treturn &config{region: region,\n\t\tsubnet: subnet,\n\t\tindex: int64(len(strings.Split(interfaces, \"\\n\"))),\n\t\tinstanceID: instanceID,\n\t\tsecurityGroups: strings.Split(securityGroups, \"\\n\"),\n\t\tvpc: vpc,\n\t}, nil\n}", "func newRequest(method, url string, body io.Reader, headers http.Header) (*http.Request, error) {\n\treq, err := http.NewRequest(method, url, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor key, value := range headers {\n\t\treq.Header.Add(key, value[0])\n\t}\n\treturn req, nil\n}", "func add_conn( node1 Node, node2 Node ) Conn {\n weight := 1\n innovation_num := 0\n conn := Conn{ node1, node2, weight, true, innovation_num } \n return( conn )\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceMplsTeGlobalAttributesSrlgsSrlgStaticSrlgMembers(ctx context.Context, name string, srlgName string, frinxOpenconfigMplsMplstesrlgtopSrlgsSrlgStaticSrlgMembersBodyParam FrinxOpenconfigMplsMplstesrlgtopSrlgsSrlgStaticSrlgMembersRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:mpls/frinx-openconfig-network-instance:te-global-attributes/frinx-openconfig-network-instance:srlgs/frinx-openconfig-network-instance:srlg/{srlg-name}/frinx-openconfig-network-instance:static-srlg-members/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"srlg-name\"+\"}\", fmt.Sprintf(\"%v\", srlgName), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigMplsMplstesrlgtopSrlgsSrlgStaticSrlgMembersBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (s *store) createMetaNode(addr, raftAddr string) error {\n\tval := &internal.CreateMetaNodeCommand{\n\t\tHTTPAddr: proto.String(addr),\n\t\tTCPAddr: proto.String(raftAddr),\n\t\tRand: proto.Uint64(uint64(rand.Int63())),\n\t}\n\tt := internal.Command_CreateMetaNodeCommand\n\tcmd := &internal.Command{Type: &t}\n\tif err := proto.SetExtension(cmd, internal.E_CreateMetaNodeCommand_Command, val); err != nil {\n\t\tpanic(err)\n\t}\n\n\tb, err := proto.Marshal(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.apply(b)\n}", "func CreateBucket(w http.ResponseWriter, r *http.Request) *appError {\n session, err := store.Get(r, \"session-name\")\n if err != nil {\n return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}\n }\n s3 := S3{\n EndPointString: session.Values[\"Endpoint\"].(string),\n AccessKey: session.Values[\"AccessKey\"].(string),\n SecretKey: session.Values[\"SecretKey\"].(string),\n Namespace: session.Values[\"Namespace\"].(string),\n }\n\n decoder := json.NewDecoder(r.Body)\n var bucket NewBucket\n err = decoder.Decode(&bucket)\n if err != nil {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Can't decode JSON data\"}\n }\n\n // Add the necessary headers for Metadata Search and Access During Outage\n createBucketHeaders := map[string][]string{}\n createBucketHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n createBucketHeaders[\"x-emc-is-stale-allowed\"] = []string{\"true\"}\n createBucketHeaders[\"x-emc-metadata-search\"] = []string{\"ObjectName,x-amz-meta-image-width;Integer,x-amz-meta-image-height;Integer,x-amz-meta-gps-latitude;Decimal,x-amz-meta-gps-longitude;Decimal\"}\n\n createBucketResponse, _ := s3Request(s3, bucket.Name, \"PUT\", \"/\", createBucketHeaders, \"\")\n\n // Enable CORS after the bucket creation to allow the web browser to send requests directly to ECS\n if createBucketResponse.Code == 200 {\n enableBucketCorsHeaders := map[string][]string{}\n enableBucketCorsHeaders[\"Content-Type\"] = []string{\"application/xml\"}\n corsConfiguration := `\n <CORSConfiguration>\n <CORSRule>\n <AllowedOrigin>*</AllowedOrigin>\n <AllowedHeader>*</AllowedHeader>\n <ExposeHeader>x-amz-meta-image-width</ExposeHeader>\n <ExposeHeader>x-amz-meta-image-height</ExposeHeader>\n <ExposeHeader>x-amz-meta-gps-latitude</ExposeHeader>\n <ExposeHeader>x-amz-meta-gps-longitude</ExposeHeader>\n <AllowedMethod>HEAD</AllowedMethod>\n <AllowedMethod>GET</AllowedMethod>\n <AllowedMethod>PUT</AllowedMethod>\n <AllowedMethod>POST</AllowedMethod>\n <AllowedMethod>DELETE</AllowedMethod>\n </CORSRule>\n </CORSConfiguration>\n `\n enableBucketCorsResponse, _ := s3Request(s3, bucket.Name, \"PUT\", \"/?cors\", enableBucketCorsHeaders, corsConfiguration)\n if enableBucketCorsResponse.Code == 200 {\n rendering.JSON(w, http.StatusOK, struct {\n CorsConfiguration string `json:\"cors_configuration\"`\n Bucket string `json:\"bucket\"`\n } {\n CorsConfiguration: corsConfiguration,\n Bucket: bucket.Name,\n })\n } else {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Bucket created, but CORS can't be enabled\"}\n }\n } else {\n return &appError{err: err, status: http.StatusBadRequest, json: \"Bucket can't be created\"}\n }\n return nil\n}", "func CreatePolicyWithDefaults(nbmaster string, httpClient *http.Client, jwt string) {\r\n fmt.Printf(\"\\nSending a POST request to create %s with defaults...\\n\", testPolicyName)\r\n\r\n policy := map[string]interface{}{\r\n \"data\": map[string]interface{}{\r\n \"type\": \"policy\",\r\n \"id\": testPolicyName,\r\n \"attributes\": map[string]interface{}{\r\n \"policy\": map[string]interface{}{\r\n \"policyName\": testPolicyName,\r\n \"policyType\": \"VMware\",\r\n \"policyAttributes\": map[string]interface{}{},\r\n \"clients\":[]interface{}{},\r\n \"schedules\":[]interface{}{},\r\n \"backupSelections\": map[string]interface{}{\r\n \"selections\": []interface{}{}}}}}}\r\n\r\n policyRequest, _ := json.Marshal(policy)\r\n\r\n uri := \"https://\" + nbmaster + \":\" + port + \"/netbackup/\" + policiesUri\r\n\r\n request, _ := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(policyRequest))\r\n request.Header.Add(\"Content-Type\", contentTypeV2);\r\n request.Header.Add(\"Authorization\", jwt);\r\n\r\n response, err := httpClient.Do(request)\r\n\r\n if err != nil {\r\n fmt.Printf(\"The HTTP request failed with error: %s\\n\", err)\r\n panic(\"Unable to create policy.\\n\")\r\n } else {\r\n if response.StatusCode != 204 {\r\n printErrorResponse(response)\r\n } else {\r\n fmt.Printf(\"%s created successfully.\\n\", testPolicyName);\r\n responseDetails, _ := httputil.DumpResponse(response, true);\r\n fmt.Printf(string(responseDetails))\r\n }\r\n }\r\n}", "func (s *MultipassServer) NewNodeGroup(ctx context.Context, request *apigrpc.NewNodeGroupRequest) (*apigrpc.NewNodeGroupReply, error) {\n\tglog.V(5).Infof(\"Call server NewNodeGroup: %v\", request)\n\n\tif s.Configuration.Optionals.NewNodeGroup {\n\t\treturn nil, fmt.Errorf(errNotImplemented)\n\t}\n\n\tif request.GetProviderID() != s.Configuration.ProviderID {\n\t\tglog.Errorf(errMismatchingProvider)\n\t\treturn nil, fmt.Errorf(errMismatchingProvider)\n\t}\n\n\tmachineType := s.Configuration.Machines[request.GetMachineType()]\n\n\tif machineType == nil {\n\t\tglog.Errorf(errMachineTypeNotFound, request.GetMachineType())\n\n\t\treturn &apigrpc.NewNodeGroupReply{\n\t\t\tResponse: &apigrpc.NewNodeGroupReply_Error{\n\t\t\t\tError: &apigrpc.Error{\n\t\t\t\t\tCode: cloudProviderError,\n\t\t\t\t\tReason: fmt.Sprintf(errMachineTypeNotFound, request.GetMachineType()),\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil\n\t}\n\n\tvar nodeGroupIdentifier string\n\n\tlabels := make(map[string]string)\n\tsystemLabels := make(map[string]string)\n\n\tif request.GetLabels() != nil {\n\t\tfor k2, v2 := range request.GetLabels() {\n\t\t\tlabels[k2] = v2\n\t\t}\n\t}\n\n\tif request.GetSystemLabels() != nil {\n\t\tfor k2, v2 := range request.GetSystemLabels() {\n\t\t\tsystemLabels[k2] = v2\n\t\t}\n\t}\n\n\tif len(request.GetNodeGroupID()) == 0 {\n\t\tnodeGroupIdentifier = s.generateNodeGroupName()\n\t} else {\n\t\tnodeGroupIdentifier = request.GetNodeGroupID()\n\t}\n\n\tlabels[nodeLabelGroupName] = nodeGroupIdentifier\n\n\targ := newNodeGroupArgument{\n\t\tnodeGroupIdentifier,\n\t\trequest.GetMinNodeSize(),\n\t\trequest.GetMaxNodeSize(),\n\t\trequest.GetMachineType(),\n\t\tlabels,\n\t\tsystemLabels,\n\t\tfalse,\n\t}\n\n\tnodeGroup, err := s.newNodeGroup(arg)\n\n\tif err != nil {\n\t\tglog.Errorf(errUnableToCreateNodeGroup, nodeGroupIdentifier, err)\n\n\t\treturn &apigrpc.NewNodeGroupReply{\n\t\t\tResponse: &apigrpc.NewNodeGroupReply_Error{\n\t\t\t\tError: &apigrpc.Error{\n\t\t\t\t\tCode: cloudProviderError,\n\t\t\t\t\tReason: fmt.Sprintf(errUnableToCreateNodeGroup, nodeGroupIdentifier, err),\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil\n\t}\n\n\treturn &apigrpc.NewNodeGroupReply{\n\t\tResponse: &apigrpc.NewNodeGroupReply_NodeGroup{\n\t\t\tNodeGroup: &apigrpc.NodeGroup{\n\t\t\t\tId: nodeGroup.NodeGroupIdentifier,\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func (r *Store) RCSAddRemote(ctx context.Context, name, remote, url string) error {\n\tstore, _ := r.getStore(name)\n\n\treturn store.Storage().AddRemote(ctx, remote, url)\n}", "func (e Endpoints) AddNode(ctx context.Context, token string, node registry.Node) (err error) {\n\trequest := AddNodeRequest{\n\t\tNode: node,\n\t\tToken: token,\n\t}\n\tresponse, err := e.AddNodeEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(AddNodeResponse).Err\n}", "func newNodeRegistry(log zerolog.Logger) *nodeRegistry {\n\treturn &nodeRegistry{\n\t\tlog: log,\n\t\tnodes: make(map[string]*nodeEntry),\n\t}\n}", "func newNode(hash string) Node {\n\treturn Node{hash: hash, parent: nil}\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceMplsSignalingProtocolsLdpGlobal(ctx context.Context, name string, frinxOpenconfigNetworkInstanceNetworkinstancesNetworkinstanceMplsSignalingprotocolsLdpGlobalBodyParam FrinxOpenconfigNetworkInstanceNetworkinstancesNetworkinstanceMplsSignalingprotocolsLdpGlobalRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:mpls/frinx-openconfig-network-instance:signaling-protocols/frinx-openconfig-network-instance:ldp/frinx-openconfig-network-instance:global/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigNetworkInstanceNetworkinstancesNetworkinstanceMplsSignalingprotocolsLdpGlobalBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (c *VrouterNode) Create(contrailClient contrailclient.ApiClient) error {\n\tvrouterInfoLog.Printf(\"Creating %s %s\", c.Hostname, nodeType)\n\tgscObjects := []*contrailtypes.GlobalSystemConfig{}\n\tgscObjectsList, err := contrailClient.List(\"global-system-config\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(gscObjectsList) == 0 {\n\t\tvrouterInfoLog.Println(\"no gscObject\")\n\t}\n\n\tfor _, gscObject := range gscObjectsList {\n\t\tobj, err := contrailClient.ReadListResult(\"global-system-config\", &gscObject)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgscObjects = append(gscObjects, obj.(*contrailtypes.GlobalSystemConfig))\n\t}\n\tfor _, gsc := range gscObjects {\n\t\tvirtualRouter := &contrailtypes.VirtualRouter{}\n\t\tvirtualRouter.SetVirtualRouterIpAddress(c.IPAddress)\n\t\tvirtualRouter.SetParent(gsc)\n\t\tvirtualRouter.SetName(c.Hostname)\n\t\tannotations := contrailclient.ConvertMapToContrailKeyValuePairs(c.Annotations)\n\t\tvirtualRouter.SetAnnotations(&annotations)\n\t\tif err := contrailClient.Create(virtualRouter); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn c.ensureVMIVhost0Interface(contrailClient)\n}", "func createNewEmptyNode() Node {\n\tnextNewId--\n\treturn Node{\n\t\tId: nextNewId,\n\t\tVisible: true,\n\t\tTimestamp: time.Now().Format(\"2006-01-02T15:04:05Z\"),\n\t\tVersion: \"1\",\n\t}\n}", "func newNode(nodestr string) (*Node, error) {\n\tif NodeCfg == nil {\n\t\tlog.Fatal(\"must set NodeCfg\")\n\t}\n\tnodestr = strings.TrimSpace(nodestr)\n\tif nodestr == \"\" {\n\t\terr := errors.New(\"nodestr is empty\")\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\tif match, err := regexp.MatchString(`\\d+/[^: ]+$`, nodestr); !match || err != nil {\n\t\terr := errors.New(fmt.Sprintln(\"bad format\", err, nodestr))\n\t\treturn nil, err\n\t}\n\tn := &Node{\n\t\tNodeConfig: NodeCfg,\n\t\tNodestr: strings.Replace(nodestr, \"+\", \"/\", -1),\n\t}\n\treturn n, nil\n}", "func newSSHDefaultConfig(userName, identity string) (*sshClientConfig, error) {\n\tconfig, err := sshDefaultConfig(userName, identity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &sshClientConfig{ClientConfig: config}, nil\n}", "func add_node( conn Conn ){\n conn.expressed = false\n\n innovation_num := 0\n node := Node{ is_hidden : true }\n conn1 := Conn{ conn.inNode, node, 1, true, innovation_num }\n conn2 := Conn{ node, conn.outNode, conn.weight, true, innovation_num }\n}", "func CreateNodeStatusWSHandler() *NodeStatusWSHandler {\n\treturn &NodeStatusWSHandler{\n\t\tregistry: ice9.CreateRegistry(),\n\t}\n}", "func resourceVolterraVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*APIClient)\n\n\tcreateMeta := &ves_io_schema.ObjectCreateMetaType{}\n\tcreateSpec := &ves_io_schema_virtual_network.CreateSpecType{}\n\tcreateReq := &ves_io_schema_virtual_network.CreateRequest{\n\t\tMetadata: createMeta,\n\t\tSpec: createSpec,\n\t}\n\n\tif v, ok := d.GetOk(\"annotations\"); ok && !isIntfNil(v) {\n\n\t\tms := map[string]string{}\n\n\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\tval := v.(string)\n\t\t\tms[k] = val\n\t\t}\n\t\tcreateMeta.Annotations = ms\n\t}\n\n\tif v, ok := d.GetOk(\"description\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Description =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"disable\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Disable =\n\t\t\tv.(bool)\n\t}\n\n\tif v, ok := d.GetOk(\"labels\"); ok && !isIntfNil(v) {\n\n\t\tms := map[string]string{}\n\n\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\tval := v.(string)\n\t\t\tms[k] = val\n\t\t}\n\t\tcreateMeta.Labels = ms\n\t}\n\n\tif v, ok := d.GetOk(\"name\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Name =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"namespace\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Namespace =\n\t\t\tv.(string)\n\t}\n\n\t//network_choice\n\n\tnetworkChoiceTypeFound := false\n\n\tif v, ok := d.GetOk(\"global_network\"); ok && !networkChoiceTypeFound {\n\n\t\tnetworkChoiceTypeFound = true\n\n\t\tif v.(bool) {\n\t\t\tnetworkChoiceInt := &ves_io_schema_virtual_network.CreateSpecType_GlobalNetwork{}\n\t\t\tnetworkChoiceInt.GlobalNetwork = &ves_io_schema.Empty{}\n\t\t\tcreateSpec.NetworkChoice = networkChoiceInt\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"legacy_type\"); ok && !networkChoiceTypeFound {\n\n\t\tnetworkChoiceTypeFound = true\n\t\tnetworkChoiceInt := &ves_io_schema_virtual_network.CreateSpecType_LegacyType{}\n\n\t\tcreateSpec.NetworkChoice = networkChoiceInt\n\n\t\tnetworkChoiceInt.LegacyType = ves_io_schema.VirtualNetworkType(ves_io_schema.VirtualNetworkType_value[v.(string)])\n\n\t}\n\n\tif v, ok := d.GetOk(\"site_local_inside_network\"); ok && !networkChoiceTypeFound {\n\n\t\tnetworkChoiceTypeFound = true\n\n\t\tif v.(bool) {\n\t\t\tnetworkChoiceInt := &ves_io_schema_virtual_network.CreateSpecType_SiteLocalInsideNetwork{}\n\t\t\tnetworkChoiceInt.SiteLocalInsideNetwork = &ves_io_schema.Empty{}\n\t\t\tcreateSpec.NetworkChoice = networkChoiceInt\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"site_local_network\"); ok && !networkChoiceTypeFound {\n\n\t\tnetworkChoiceTypeFound = true\n\n\t\tif v.(bool) {\n\t\t\tnetworkChoiceInt := &ves_io_schema_virtual_network.CreateSpecType_SiteLocalNetwork{}\n\t\t\tnetworkChoiceInt.SiteLocalNetwork = &ves_io_schema.Empty{}\n\t\t\tcreateSpec.NetworkChoice = networkChoiceInt\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"srv6_network\"); ok && !networkChoiceTypeFound {\n\n\t\tnetworkChoiceTypeFound = true\n\t\tnetworkChoiceInt := &ves_io_schema_virtual_network.CreateSpecType_Srv6Network{}\n\t\tnetworkChoiceInt.Srv6Network = &ves_io_schema_virtual_network.PerSiteSrv6NetworkType{}\n\t\tcreateSpec.NetworkChoice = networkChoiceInt\n\n\t\tsl := v.(*schema.Set).List()\n\t\tfor _, set := range sl {\n\t\t\tcs := set.(map[string]interface{})\n\n\t\t\tif v, ok := cs[\"access_network_rtargets\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\taccessNetworkRtargets := make([]*ves_io_schema.RouteTarget, len(sl))\n\t\t\t\tnetworkChoiceInt.Srv6Network.AccessNetworkRtargets = accessNetworkRtargets\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\taccessNetworkRtargets[i] = &ves_io_schema.RouteTarget{}\n\t\t\t\t\taccessNetworkRtargetsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\trtargetChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := accessNetworkRtargetsMapStrToI[\"asn2byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn2ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget = &ves_io_schema.RouteTarget2ByteAsn{}\n\t\t\t\t\t\taccessNetworkRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := accessNetworkRtargetsMapStrToI[\"asn4byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn4ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget = &ves_io_schema.RouteTarget4ByteAsn{}\n\t\t\t\t\t\taccessNetworkRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := accessNetworkRtargetsMapStrToI[\"ipv4_addr_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Ipv4AddrRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget = &ves_io_schema.RouteTargetIPv4Addr{}\n\t\t\t\t\t\taccessNetworkRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Address = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tdefaultVipChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"anycast_vip\"]; ok && !isIntfNil(v) && !defaultVipChoiceTypeFound {\n\n\t\t\t\tdefaultVipChoiceTypeFound = true\n\t\t\t\tdefaultVipChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_AnycastVip{}\n\n\t\t\t\tnetworkChoiceInt.Srv6Network.DefaultVipChoice = defaultVipChoiceInt\n\n\t\t\t\tdefaultVipChoiceInt.AnycastVip = v.(string)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"fleet_vip\"]; ok && !isIntfNil(v) && !defaultVipChoiceTypeFound {\n\n\t\t\t\tdefaultVipChoiceTypeFound = true\n\t\t\t\tdefaultVipChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_FleetVip{}\n\t\t\t\tdefaultVipChoiceInt.FleetVip = &ves_io_schema_virtual_network.AnyCastVIPFleetType{}\n\t\t\t\tnetworkChoiceInt.Srv6Network.DefaultVipChoice = defaultVipChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"vip_allocator\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tvipAllocatorInt := &ves_io_schema_views.ObjectRefType{}\n\t\t\t\t\t\tdefaultVipChoiceInt.FleetVip.VipAllocator = vipAllocatorInt\n\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tvaMapToStrVal := set.(map[string]interface{})\n\t\t\t\t\t\t\tif val, ok := vaMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tvipAllocatorInt.Name = val.(string)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif val, ok := vaMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tvipAllocatorInt.Namespace = val.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif val, ok := vaMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tvipAllocatorInt.Tenant = val.(string)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"interface_ip_vip\"]; ok && !isIntfNil(v) && !defaultVipChoiceTypeFound {\n\n\t\t\t\tdefaultVipChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tdefaultVipChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_InterfaceIpVip{}\n\t\t\t\t\tdefaultVipChoiceInt.InterfaceIpVip = &ves_io_schema.Empty{}\n\t\t\t\t\tnetworkChoiceInt.Srv6Network.DefaultVipChoice = defaultVipChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"enterprise_network_rtargets\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tenterpriseNetworkRtargets := make([]*ves_io_schema.RouteTarget, len(sl))\n\t\t\t\tnetworkChoiceInt.Srv6Network.EnterpriseNetworkRtargets = enterpriseNetworkRtargets\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\tenterpriseNetworkRtargets[i] = &ves_io_schema.RouteTarget{}\n\t\t\t\t\tenterpriseNetworkRtargetsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\trtargetChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := enterpriseNetworkRtargetsMapStrToI[\"asn2byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn2ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget = &ves_io_schema.RouteTarget2ByteAsn{}\n\t\t\t\t\t\tenterpriseNetworkRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := enterpriseNetworkRtargetsMapStrToI[\"asn4byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn4ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget = &ves_io_schema.RouteTarget4ByteAsn{}\n\t\t\t\t\t\tenterpriseNetworkRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := enterpriseNetworkRtargetsMapStrToI[\"ipv4_addr_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Ipv4AddrRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget = &ves_io_schema.RouteTargetIPv4Addr{}\n\t\t\t\t\t\tenterpriseNetworkRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Address = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"export_rtargets\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\texportRtargets := make([]*ves_io_schema.RouteTarget, len(sl))\n\t\t\t\tnetworkChoiceInt.Srv6Network.ExportRtargets = exportRtargets\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\texportRtargets[i] = &ves_io_schema.RouteTarget{}\n\t\t\t\t\texportRtargetsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\trtargetChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := exportRtargetsMapStrToI[\"asn2byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn2ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget = &ves_io_schema.RouteTarget2ByteAsn{}\n\t\t\t\t\t\texportRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := exportRtargetsMapStrToI[\"asn4byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn4ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget = &ves_io_schema.RouteTarget4ByteAsn{}\n\t\t\t\t\t\texportRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := exportRtargetsMapStrToI[\"ipv4_addr_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Ipv4AddrRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget = &ves_io_schema.RouteTargetIPv4Addr{}\n\t\t\t\t\t\texportRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Address = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"fleets\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tfleetsInt := make([]*ves_io_schema_views.ObjectRefType, len(sl))\n\t\t\t\tnetworkChoiceInt.Srv6Network.Fleets = fleetsInt\n\t\t\t\tfor i, ps := range sl {\n\n\t\t\t\t\tfMapToStrVal := ps.(map[string]interface{})\n\t\t\t\t\tfleetsInt[i] = &ves_io_schema_views.ObjectRefType{}\n\n\t\t\t\t\tif v, ok := fMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tfleetsInt[i].Name = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := fMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tfleetsInt[i].Namespace = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := fMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tfleetsInt[i].Tenant = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"internet_rtargets\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tinternetRtargets := make([]*ves_io_schema.RouteTarget, len(sl))\n\t\t\t\tnetworkChoiceInt.Srv6Network.InternetRtargets = internetRtargets\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\tinternetRtargets[i] = &ves_io_schema.RouteTarget{}\n\t\t\t\t\tinternetRtargetsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\trtargetChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := internetRtargetsMapStrToI[\"asn2byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn2ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget = &ves_io_schema.RouteTarget2ByteAsn{}\n\t\t\t\t\t\tinternetRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := internetRtargetsMapStrToI[\"asn4byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn4ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget = &ves_io_schema.RouteTarget4ByteAsn{}\n\t\t\t\t\t\tinternetRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := internetRtargetsMapStrToI[\"ipv4_addr_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Ipv4AddrRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget = &ves_io_schema.RouteTargetIPv4Addr{}\n\t\t\t\t\t\tinternetRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Address = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tnamespaceChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"no_namespace_network\"]; ok && !isIntfNil(v) && !namespaceChoiceTypeFound {\n\n\t\t\t\tnamespaceChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnamespaceChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_NoNamespaceNetwork{}\n\t\t\t\t\tnamespaceChoiceInt.NoNamespaceNetwork = &ves_io_schema.Empty{}\n\t\t\t\t\tnetworkChoiceInt.Srv6Network.NamespaceChoice = namespaceChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"srv6_network_ns_params\"]; ok && !isIntfNil(v) && !namespaceChoiceTypeFound {\n\n\t\t\t\tnamespaceChoiceTypeFound = true\n\t\t\t\tnamespaceChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_Srv6NetworkNsParams{}\n\t\t\t\tnamespaceChoiceInt.Srv6NetworkNsParams = &ves_io_schema_virtual_network.Srv6NetworkNsParametersType{}\n\t\t\t\tnetworkChoiceInt.Srv6Network.NamespaceChoice = namespaceChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnamespaceChoiceInt.Srv6NetworkNsParams.Namespace = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"remote_sid_stats_plen\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tnetworkChoiceInt.Srv6Network.RemoteSidStatsPlen = uint32(v.(int))\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"slice\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tsliceInt := &ves_io_schema_views.ObjectRefType{}\n\t\t\t\tnetworkChoiceInt.Srv6Network.Slice = sliceInt\n\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tsMapToStrVal := set.(map[string]interface{})\n\t\t\t\t\tif val, ok := sMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tsliceInt.Name = val.(string)\n\t\t\t\t\t}\n\t\t\t\t\tif val, ok := sMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tsliceInt.Namespace = val.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif val, ok := sMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tsliceInt.Tenant = val.(string)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tsnatPoolChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"fleet_snat_pool\"]; ok && !isIntfNil(v) && !snatPoolChoiceTypeFound {\n\n\t\t\t\tsnatPoolChoiceTypeFound = true\n\t\t\t\tsnatPoolChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_FleetSnatPool{}\n\t\t\t\tsnatPoolChoiceInt.FleetSnatPool = &ves_io_schema_virtual_network.SNATPoolFleetType{}\n\t\t\t\tnetworkChoiceInt.Srv6Network.SnatPoolChoice = snatPoolChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"snat_pool_allocator\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tsnatPoolAllocatorInt := &ves_io_schema_views.ObjectRefType{}\n\t\t\t\t\t\tsnatPoolChoiceInt.FleetSnatPool.SnatPoolAllocator = snatPoolAllocatorInt\n\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tspaMapToStrVal := set.(map[string]interface{})\n\t\t\t\t\t\t\tif val, ok := spaMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tsnatPoolAllocatorInt.Name = val.(string)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif val, ok := spaMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tsnatPoolAllocatorInt.Namespace = val.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif val, ok := spaMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tsnatPoolAllocatorInt.Tenant = val.(string)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"interface_ip_snat_pool\"]; ok && !isIntfNil(v) && !snatPoolChoiceTypeFound {\n\n\t\t\t\tsnatPoolChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tsnatPoolChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_InterfaceIpSnatPool{}\n\t\t\t\t\tsnatPoolChoiceInt.InterfaceIpSnatPool = &ves_io_schema.Empty{}\n\t\t\t\t\tnetworkChoiceInt.Srv6Network.SnatPoolChoice = snatPoolChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"site_snat_pool\"]; ok && !isIntfNil(v) && !snatPoolChoiceTypeFound {\n\n\t\t\t\tsnatPoolChoiceTypeFound = true\n\t\t\t\tsnatPoolChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_SiteSnatPool{}\n\t\t\t\tsnatPoolChoiceInt.SiteSnatPool = &ves_io_schema_virtual_network.SNATPoolSiteType{}\n\t\t\t\tnetworkChoiceInt.Srv6Network.SnatPoolChoice = snatPoolChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"node_snat_pool\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tnodeSnatPool := make(map[string]*ves_io_schema_virtual_network.SNATPoolType)\n\t\t\t\t\t\tsnatPoolChoiceInt.SiteSnatPool.NodeSnatPool = nodeSnatPool\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tnodeSnatPoolMapStrToI := set.(map[string]interface{})\n\t\t\t\t\t\t\tkey, ok := nodeSnatPoolMapStrToI[\"name\"]\n\t\t\t\t\t\t\tif ok && !isIntfNil(key) {\n\t\t\t\t\t\t\t\tnodeSnatPool[key.(string)] = &ves_io_schema_virtual_network.SNATPoolType{}\n\t\t\t\t\t\t\t\tval, _ := nodeSnatPoolMapStrToI[\"value\"]\n\n\t\t\t\t\t\t\t\tnodeSnatPoolVals := val.(*schema.Set).List()\n\t\t\t\t\t\t\t\tfor _, intVal := range nodeSnatPoolVals {\n\n\t\t\t\t\t\t\t\t\tnodeSnatPoolStaticMap := intVal.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\tif w, ok := nodeSnatPoolStaticMap[\"ipv4_prefixes\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\tnodeSnatPool[key.(string)].Ipv4Prefixes = nil\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif w, ok := nodeSnatPoolStaticMap[\"ipv6_prefixes\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\tnodeSnatPool[key.(string)].Ipv6Prefixes = nil\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// break after one loop\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//static_routes\n\tif v, ok := d.GetOk(\"static_routes\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.([]interface{})\n\t\tstaticRoutes := make([]*ves_io_schema_virtual_network.StaticRouteViewType, len(sl))\n\t\tcreateSpec.StaticRoutes = staticRoutes\n\t\tfor i, set := range sl {\n\t\t\tstaticRoutes[i] = &ves_io_schema_virtual_network.StaticRouteViewType{}\n\t\t\tstaticRoutesMapStrToI := set.(map[string]interface{})\n\n\t\t\tif v, ok := staticRoutesMapStrToI[\"attrs\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tattrsList := []ves_io_schema.RouteAttrType{}\n\t\t\t\tfor _, j := range v.([]interface{}) {\n\t\t\t\t\tattrsList = append(attrsList, ves_io_schema.RouteAttrType(ves_io_schema.RouteAttrType_value[j.(string)]))\n\t\t\t\t}\n\t\t\t\tstaticRoutes[i].Attrs = attrsList\n\n\t\t\t}\n\n\t\t\tif w, ok := staticRoutesMapStrToI[\"ip_prefixes\"]; ok && !isIntfNil(w) {\n\t\t\t\tls := make([]string, len(w.([]interface{})))\n\t\t\t\tfor i, v := range w.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tstaticRoutes[i].IpPrefixes = ls\n\t\t\t}\n\n\t\t\tnextHopChoiceTypeFound := false\n\n\t\t\tif v, ok := staticRoutesMapStrToI[\"default_gateway\"]; ok && !isIntfNil(v) && !nextHopChoiceTypeFound {\n\n\t\t\t\tnextHopChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnextHopChoiceInt := &ves_io_schema_virtual_network.StaticRouteViewType_DefaultGateway{}\n\t\t\t\t\tnextHopChoiceInt.DefaultGateway = &ves_io_schema.Empty{}\n\t\t\t\t\tstaticRoutes[i].NextHopChoice = nextHopChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := staticRoutesMapStrToI[\"interface\"]; ok && !isIntfNil(v) && !nextHopChoiceTypeFound {\n\n\t\t\t\tnextHopChoiceTypeFound = true\n\t\t\t\tnextHopChoiceInt := &ves_io_schema_virtual_network.StaticRouteViewType_Interface{}\n\t\t\t\tnextHopChoiceInt.Interface = &ves_io_schema_views.ObjectRefType{}\n\t\t\t\tstaticRoutes[i].NextHopChoice = nextHopChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnextHopChoiceInt.Interface.Name = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnextHopChoiceInt.Interface.Namespace = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"tenant\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnextHopChoiceInt.Interface.Tenant = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := staticRoutesMapStrToI[\"ip_address\"]; ok && !isIntfNil(v) && !nextHopChoiceTypeFound {\n\n\t\t\t\tnextHopChoiceTypeFound = true\n\t\t\t\tnextHopChoiceInt := &ves_io_schema_virtual_network.StaticRouteViewType_IpAddress{}\n\n\t\t\t\tstaticRoutes[i].NextHopChoice = nextHopChoiceInt\n\n\t\t\t\tnextHopChoiceInt.IpAddress = v.(string)\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//static_v6_routes\n\tif v, ok := d.GetOk(\"static_v6_routes\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.([]interface{})\n\t\tstaticV6Routes := make([]*ves_io_schema_virtual_network.StaticV6RouteViewType, len(sl))\n\t\tcreateSpec.StaticV6Routes = staticV6Routes\n\t\tfor i, set := range sl {\n\t\t\tstaticV6Routes[i] = &ves_io_schema_virtual_network.StaticV6RouteViewType{}\n\t\t\tstaticV6RoutesMapStrToI := set.(map[string]interface{})\n\n\t\t\tif v, ok := staticV6RoutesMapStrToI[\"attrs\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tattrsList := []ves_io_schema.RouteAttrType{}\n\t\t\t\tfor _, j := range v.([]interface{}) {\n\t\t\t\t\tattrsList = append(attrsList, ves_io_schema.RouteAttrType(ves_io_schema.RouteAttrType_value[j.(string)]))\n\t\t\t\t}\n\t\t\t\tstaticV6Routes[i].Attrs = attrsList\n\n\t\t\t}\n\n\t\t\tif w, ok := staticV6RoutesMapStrToI[\"ip_prefixes\"]; ok && !isIntfNil(w) {\n\t\t\t\tls := make([]string, len(w.([]interface{})))\n\t\t\t\tfor i, v := range w.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tstaticV6Routes[i].IpPrefixes = ls\n\t\t\t}\n\n\t\t\tnextHopChoiceTypeFound := false\n\n\t\t\tif v, ok := staticV6RoutesMapStrToI[\"default_gateway\"]; ok && !isIntfNil(v) && !nextHopChoiceTypeFound {\n\n\t\t\t\tnextHopChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnextHopChoiceInt := &ves_io_schema_virtual_network.StaticV6RouteViewType_DefaultGateway{}\n\t\t\t\t\tnextHopChoiceInt.DefaultGateway = &ves_io_schema.Empty{}\n\t\t\t\t\tstaticV6Routes[i].NextHopChoice = nextHopChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := staticV6RoutesMapStrToI[\"interface\"]; ok && !isIntfNil(v) && !nextHopChoiceTypeFound {\n\n\t\t\t\tnextHopChoiceTypeFound = true\n\t\t\t\tnextHopChoiceInt := &ves_io_schema_virtual_network.StaticV6RouteViewType_Interface{}\n\t\t\t\tnextHopChoiceInt.Interface = &ves_io_schema_views.ObjectRefType{}\n\t\t\t\tstaticV6Routes[i].NextHopChoice = nextHopChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnextHopChoiceInt.Interface.Name = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnextHopChoiceInt.Interface.Namespace = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"tenant\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnextHopChoiceInt.Interface.Tenant = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := staticV6RoutesMapStrToI[\"ip_address\"]; ok && !isIntfNil(v) && !nextHopChoiceTypeFound {\n\n\t\t\t\tnextHopChoiceTypeFound = true\n\t\t\t\tnextHopChoiceInt := &ves_io_schema_virtual_network.StaticV6RouteViewType_IpAddress{}\n\n\t\t\t\tstaticV6Routes[i].NextHopChoice = nextHopChoiceInt\n\n\t\t\t\tnextHopChoiceInt.IpAddress = v.(string)\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tlog.Printf(\"[DEBUG] Creating Volterra VirtualNetwork object with struct: %+v\", createReq)\n\n\tcreateVirtualNetworkResp, err := client.CreateObject(context.Background(), ves_io_schema_virtual_network.ObjectType, createReq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating VirtualNetwork: %s\", err)\n\t}\n\td.SetId(createVirtualNetworkResp.GetObjSystemMetadata().GetUid())\n\n\treturn resourceVolterraVirtualNetworkRead(d, meta)\n}", "func newNode(allc *Allocator, valAllc *Allocator, height uint8, key []byte, val []byte) (*node, uint32) {\n\ttruncatedSize := (DefaultMaxHeight - int(height)) * LayerSize\n\tkeyOffset := allc.putBytes(key)\n\tnodeOffset := allc.makeNode(uint32(truncatedSize))\n\tvalOffset := valAllc.putBytes(val)\n\tnode := allc.getNode(nodeOffset)\n\tnode.height = height\n\tnode.keyOffset = keyOffset\n\t// TODO key length should not exceed uint16 size, assert.\n\tnode.keySize = uint16(len(key))\n\tnode.encodeValue(valOffset, uint32(len(val)))\n\treturn node, nodeOffset\n}", "func (c *config) addRemote(name string, repo string) (output string, err error) {\n\tlog.Printf(\"adding remote: %v\\n\", name)\n\n\tdefaultCommand := []string{\"remote\", \"add\", name, repo, \"--fetch\"}\n\n\treturn c.command(defaultCommand...)\n}", "func makeNodeWithAddresses(name, internal, external string) *v1.Node {\n\tif name == \"\" {\n\t\treturn &v1.Node{}\n\t}\n\n\tnode := &v1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t\tStatus: v1.NodeStatus{\n\t\t\tAddresses: []v1.NodeAddress{},\n\t\t},\n\t}\n\n\tif internal != \"\" {\n\t\tnode.Status.Addresses = append(node.Status.Addresses,\n\t\t\tv1.NodeAddress{Type: v1.NodeInternalIP, Address: internal},\n\t\t)\n\t}\n\n\tif external != \"\" {\n\t\tnode.Status.Addresses = append(node.Status.Addresses,\n\t\t\tv1.NodeAddress{Type: v1.NodeExternalIP, Address: external},\n\t\t)\n\t}\n\n\treturn node\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) DeleteFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceMplsTeGlobalAttributesSrlgsSrlg(ctx context.Context, name string, srlgName string, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:mpls/frinx-openconfig-network-instance:te-global-attributes/frinx-openconfig-network-instance:srlgs/frinx-openconfig-network-instance:srlg/{srlg-name}/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"srlg-name\"+\"}\", fmt.Sprintf(\"%v\", srlgName), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceMplsSignalingProtocolsRsvpTeGlobalHellosConfig(ctx context.Context, name string, frinxOpenconfigMplsRsvpMplsrsvphellosHellosConfigBodyParam FrinxOpenconfigMplsRsvpMplsrsvphellosHellosConfigRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:mpls/frinx-openconfig-network-instance:signaling-protocols/frinx-openconfig-network-instance:rsvp-te/frinx-openconfig-network-instance:global/frinx-openconfig-network-instance:hellos/frinx-openconfig-network-instance:config/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigMplsRsvpMplsrsvphellosHellosConfigBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceMplsSignalingProtocolsLdpTargeted(ctx context.Context, name string, frinxOpenconfigMplsLdpMplsldptargetedtopTargetedBodyParam FrinxOpenconfigMplsLdpMplsldptargetedtopTargetedRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:mpls/frinx-openconfig-network-instance:signaling-protocols/frinx-openconfig-network-instance:ldp/frinx-openconfig-network-instance:targeted/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigMplsLdpMplsldptargetedtopTargetedBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (sdk *SDK) createNode(req *CreateInstanceRequest) (*cloudsvr.CloudNode, error) {\n\tvar err error\n\n\t// create ecs firstly\n\tecsID, err := sdk.NewEcs(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs create failed: %v\", err)\n\t}\n\tlog.Printf(\"aliyun ecs %s created at %s\", ecsID, req.RegionID)\n\n\t// if create succeed, but other operations failed, clean up the newly created ecs instance to prevent garbage left\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"aliyun cloud node creation failed, clean up the newly created ecs instance %s. [%v]\", ecsID, err)\n\t\t\tsdk.RemoveNode(&cloudsvr.CloudNode{ID: ecsID, RegionOrZoneID: req.RegionID})\n\t\t}\n\t}()\n\n\t// now ecs is stopped, we assign an public ip to it\n\tip, err := sdk.AssignEcsPublicIP(ecsID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs %s assign public ip failed: %v\", ecsID, err)\n\t}\n\tlog.Printf(\"aliyun ecs %s assgined public ipaddress %s\", ecsID, ip)\n\n\t// start ecs\n\tif err = sdk.StartEcs(ecsID); err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs %s start failed: %v\", ecsID, err)\n\t}\n\tlog.Printf(\"aliyun ecs %s starting\", ecsID)\n\n\t// wait ecs to be running\n\tif err = sdk.WaitEcs(req.RegionID, ecsID, \"Running\", time.Second*300); err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs %s waitting to be running failed: %v\", ecsID, err)\n\t}\n\tlog.Printf(\"aliyun ecs %s is Running now\", ecsID)\n\n\treturn &cloudsvr.CloudNode{\n\t\tID: ecsID,\n\t\tRegionOrZoneID: req.RegionID,\n\t\tInstanceType: req.InstanceType,\n\t\tCloudSvrType: sdk.Type(),\n\t\tIPAddr: ip,\n\t\tPort: \"22\",\n\t\tUser: \"root\",\n\t\tPassword: req.Password,\n\t}, nil\n}", "func newSSHAgentConfig(userName string) (*sshClientConfig, error) {\n\tagent, err := newAgent()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig, err := sshAgentConfig(userName, agent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &sshClientConfig{\n\t\tagent: agent,\n\t\tClientConfig: config,\n\t}, nil\n}", "func (srhrce StatelessReplicaHealthReportCreatedEvent) AsNodeAddedEvent() (*NodeAddedEvent, bool) {\n\treturn nil, false\n}", "func (conn Connection) newRequest(method, cmd string, body io.Reader) *http.Request {\n\t// req, err := conn.jhReq(method, cmd, body)\n\treq, err := http.NewRequest(method, conn.HubURL+cmd, body)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Coulnd't generate HTTP request - %s\\n\", err.Error()))\n\t}\n\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"token %s\", conn.Token))\n\n\treturn req\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceMplsSignalingProtocolsRsvpTeNeighbors(ctx context.Context, name string, frinxOpenconfigMplsRsvpRsvpglobalRsvpteNeighborsBodyParam FrinxOpenconfigMplsRsvpRsvpglobalRsvpteNeighborsRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:mpls/frinx-openconfig-network-instance:signaling-protocols/frinx-openconfig-network-instance:rsvp-te/frinx-openconfig-network-instance:neighbors/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigMplsRsvpRsvpglobalRsvpteNeighborsBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceMplsSignalingProtocolsRsvpTe(ctx context.Context, name string, frinxOpenconfigNetworkInstanceNetworkinstancesNetworkinstanceMplsSignalingprotocolsRsvpTeBodyParam FrinxOpenconfigNetworkInstanceNetworkinstancesNetworkinstanceMplsSignalingprotocolsRsvpTeRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:mpls/frinx-openconfig-network-instance:signaling-protocols/frinx-openconfig-network-instance:rsvp-te/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigNetworkInstanceNetworkinstancesNetworkinstanceMplsSignalingprotocolsRsvpTeBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (c *VrouterNode) Create(contrailClient ApiClient) error {\n\tgscObjects := []*contrailTypes.GlobalSystemConfig{}\n\tgscObjectsList, err := contrailClient.List(\"global-system-config\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(gscObjectsList) == 0 {\n\t\tfmt.Println(\"no gscObject\")\n\t}\n\n\tfor _, gscObject := range gscObjectsList {\n\t\tobj, err := contrailClient.ReadListResult(\"global-system-config\", &gscObject)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgscObjects = append(gscObjects, obj.(*contrailTypes.GlobalSystemConfig))\n\t}\n\tfor _, gsc := range gscObjects {\n\t\tvncNode := &contrailTypes.VirtualRouter{}\n\t\tvncNode.SetVirtualRouterIpAddress(c.IPAddress)\n\t\tvncNode.SetParent(gsc)\n\t\tvncNode.SetName(c.Hostname)\n\t\tif err := contrailClient.Create(vncNode); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\treturn nil\n}", "func CreateAddPrometheusRemoteWriteRequest() (request *AddPrometheusRemoteWriteRequest) {\n\trequest = &AddPrometheusRemoteWriteRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"ARMS\", \"2019-08-08\", \"AddPrometheusRemoteWrite\", \"arms\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func createLBRPNode(node *k8sNode) error {\n\tlog.Debugf(\"Creating %s\", k8switchName)\n\n\t// port connected to br0\n\ttoStack := k8switch.Ports{Name: \"toStack\"}\n\n\t// port connected to physical nic (through k8sfilter)\n\ttoNodePort := k8switch.Ports{Name: \"toNodePort\", Type_: \"NODEPORT\"}\n\n\tports := []k8switch.Ports{toStack, toNodePort}\n\n\tserviceClusterIPRange := os.Getenv(\"POLYCUBE_SERVICE_CLUSTERIP_RANGE\")\n\tif serviceClusterIPRange == \"\" {\n\t\tlog.Warningf(\"POLYCUBE_SERVICE_CLUSTERIP_RANGE not found, defaulting to %s\",\n\t\tserviceClusterIPRangeDefault)\n\t\t\tserviceClusterIPRange = serviceClusterIPRangeDefault\n\t}\n\n\tlb := k8switch.K8switch{\n\t\tName: k8switchName,\n\t\tPorts: ports,\n\t\tClusterIpSubnet: serviceClusterIPRange,\n\t\tClientSubnet: node.GetPodCIDR().String(),\n\t\tVirtualClientSubnet: node.GetVPodCIDR().String()}\n\n\tif _, err := k8switchAPI.CreateK8switchByID(k8switchName, lb); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Debugf(\"%s created\", k8switchName)\n\treturn nil\n}", "func (nop *NodeOperations) AddNodes() http.Handler {\n\treturn httptransport.NewServer(\n\t\tfunc(ctx context.Context, request interface{}) (interface{}, error) {\n\n\t\t\treq := request.(*resourceManager.AddNodeToK8SClusterRequest)\n\n\t\t\tresponse, err := nop.RcManager.AddNodes(ctx, req)\n\t\t\tif err != nil {\n\t\t\t\tst, ok := status.FromError(err)\n\t\t\t\tif ok {\n\t\t\t\t\tlogrus.WithField(\"add_node\", \"add_node\").Error(st.Message())\n\t\t\t\t\tif st.Message() == rmerrors.ErrClusterIsLocked.Error() {\n\t\t\t\t\t\treturn nil, errorlib.Wrap(\"CLOP0006\", errUnableToAddNodesForOngoingOperations)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlogrus.WithError(err).Error(\"failed to add nodes\")\n\t\t\t\treturn nil, errorlib.Wrap(\"1\", errUnableToAddNodes)\n\t\t\t}\n\t\t\treturn proto_marshaller.Marshal(response)\n\t\t},\n\t\tfunc(_ context.Context, r *http.Request) (interface{}, error) {\n\t\t\tparams := mux.Vars(r)\n\n\t\t\tvar addNodeReq AddNodeRequest\n\t\t\terr := json.NewDecoder(r.Body).Decode(&addNodeReq)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.WithError(err).Error(\"failed to decode add node request\")\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tclusterId := params[\"cluster_id\"]\n\t\t\tif clusterId == \"\" {\n\t\t\t\treturn nil, errors.New(\"cluster id is a required field\")\n\t\t\t}\n\n\t\t\treturn &resourceManager.AddNodeToK8SClusterRequest{\n\t\t\t\tClusterId: clusterId,\n\t\t\t\tK8SSpec: &resourceManager.AddNodeK8SSpec{\n\t\t\t\t\tWorkerInstanceCount: addNodeReq.WorkerInstanceCount,\n\t\t\t\t\tInstanceSize: addNodeReq.WorkerInstanceSize,\n\t\t\t\t\tStorageSize: addNodeReq.StorageSize,\n\t\t\t\t\tWorkerInstanceIps: addNodeReq.WorkerIps,\n\t\t\t\t},\n\t\t\t\tCreatedBy: addNodeReq.CreatedBy,\n\t\t\t}, err\n\t\t},\n\t\tproto_marshaller.EncodeProtoMessageResponseJSON,\n\t)\n}", "func (o *AddRemoteRDSNodeDefault) Code() int {\n\treturn o._statusCode\n}", "func AddNode(namespace string, clusterName string, req *app.NodeReq) (*model.NodeList, error) {\n\n\t// validate namespace\n\tif err := verifyNamespace(namespace); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get a cluster-entity\n\tcluster := model.NewCluster(namespace, clusterName)\n\tif exists, err := cluster.Select(); err != nil {\n\t\treturn nil, err\n\t} else if exists == false {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Could not be found a cluster '%s'. (namespace=%s)\", clusterName, namespace))\n\t} else if cluster.Status.Phase != model.ClusterPhaseProvisioned {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Unable to add a node. status is '%s'.\", cluster.Status.Phase))\n\t}\n\n\t// get a MCIS\n\tmcis := tumblebug.NewMCIS(namespace, cluster.MCIS)\n\tif exists, err := mcis.GET(); err != nil {\n\t\treturn nil, err\n\t} else if !exists {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Can't be found a MCIS '%s'.\", cluster.MCIS))\n\t}\n\tlogger.Infof(\"[%s.%s] The inquiry has been completed..\", namespace, clusterName)\n\n\tmcisName := cluster.MCIS\n\n\tif cluster.ServiceType == app.ST_SINGLE {\n\t\tif len(mcis.VMs) > 0 {\n\t\t\tconnection := mcis.VMs[0].Config\n\t\t\tfor _, worker := range req.Worker {\n\t\t\t\tif worker.Connection != connection {\n\t\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"The new node must be the same connection config. (connection=%s)\", worker.Connection))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"There is no VMs. (cluster=%s)\", clusterName))\n\t\t}\n\t}\n\n\t// get a provisioner\n\tprovisioner := provision.NewProvisioner(cluster)\n\n\t/*\n\t\tif err := provisioner.BuildAllMachines(); err != nil {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to build provisioner's map: %v\", err))\n\t\t}\n\t*/\n\n\t// get join command\n\tworkerJoinCmd, err := provisioner.NewWorkerJoinCommand()\n\tif err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to get join-command (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Worker join-command inquiry has been completed. (command=%s)\", namespace, clusterName, workerJoinCmd)\n\n\tvar workerCSP app.CSP\n\n\t// create a MCIR & MCIS-vm\n\tidx := cluster.NextNodeIndex(app.WORKER)\n\tvar vmgroupid []string\n\tfor _, worker := range req.Worker {\n\t\tmcir := NewMCIR(namespace, app.WORKER, *worker)\n\t\treason, msg := mcir.CreateIfNotExist()\n\t\tif reason != \"\" {\n\t\t\treturn nil, errors.New(msg)\n\t\t} else {\n\t\t\tfor i := 0; i < mcir.vmCount; i++ {\n\t\t\t\tname := lang.GenerateNewNodeName(string(app.WORKER), idx)\n\t\t\t\tif i == 0 {\n\t\t\t\t\tworkerCSP = mcir.csp\n\t\t\t\t}\n\t\t\t\tvm := mcir.NewVM(namespace, name, mcisName, \"\", worker.RootDisk.Type, worker.RootDisk.Size)\n\t\t\t\tif err := vm.POST(); err != nil {\n\t\t\t\t\tcleanUpNodes(*provisioner)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tvmgroupid = append(vmgroupid, name)\n\t\t\t\tprovisioner.AppendWorkerNodeMachine(name+\"-1\", mcir.csp, mcir.region, mcir.zone, mcir.credential)\n\t\t\t\tidx = idx + 1\n\t\t\t}\n\t\t}\n\t}\n\t// Pull out the added VMlist\n\tif _, err := mcis.GET(); err != nil {\n\t\treturn nil, err\n\t}\n\tvms := []tumblebug.VM{}\n\tfor _, mcisvm := range mcis.VMs {\n\t\tfor _, grupid := range vmgroupid {\n\t\t\tif mcisvm.VmGroupId == grupid {\n\t\t\t\tmcisvm.Namespace = namespace\n\t\t\t\tmcisvm.McisName = mcisName\n\t\t\t\tvms = append(vms, mcisvm)\n\t\t\t}\n\t\t}\n\t}\n\tlogger.Infof(\"[%s.%s] MCIS(vm) creation has been completed. (len=%d)\", namespace, clusterName, len(vms))\n\n\t// save nodes metadata\n\tif nodes, err := provisioner.BindVM(vms); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tcluster.Nodes = append(cluster.Nodes, nodes...)\n\t\tif err := cluster.PutStore(); err != nil {\n\t\t\tcleanUpNodes(*provisioner)\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity. (cause='%v')\", err))\n\t\t}\n\t}\n\n\t// kubernetes provisioning : bootstrap\n\ttime.Sleep(2 * time.Second)\n\tif err := provisioner.Bootstrap(); err != nil {\n\t\tcleanUpNodes(*provisioner)\n\t\treturn nil, errors.New(fmt.Sprintf(\"Bootstrap failed. (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Bootstrap has been completed.\", namespace, clusterName)\n\n\t// kubernetes provisioning : worker node join\n\tfor _, machine := range provisioner.WorkerNodeMachines {\n\t\tif err := machine.JoinWorker(&workerJoinCmd); err != nil {\n\t\t\tcleanUpNodes(*provisioner)\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Fail to worker-node join. (node=%s)\", machine.Name))\n\t\t}\n\t}\n\tlogger.Infof(\"[%s.%s] Woker-nodes join has been completed.\", namespace, clusterName)\n\n\t/* FIXME: after joining, check the worker is ready */\n\n\t// assign node labels (topology.cloud-barista.github.io/csp , topology.kubernetes.io/region, topology.kubernetes.io/zone)\n\tif err = provisioner.AssignNodeLabelAnnotation(); err != nil {\n\t\tlogger.Warnf(\"[%s.%s] Failed to assign node labels (cause='%v')\", namespace, clusterName, err)\n\t} else {\n\t\tlogger.Infof(\"[%s.%s] Node label assignment has been completed.\", namespace, clusterName)\n\t}\n\n\t// kubernetes provisioning : add some actions for cloud-controller-manager\n\tif provisioner.Cluster.ServiceType == app.ST_SINGLE {\n\t\tif workerCSP == app.CSP_AWS {\n\t\t\t// check whether AWS IAM roles exists and are same\n\t\t\tvar bFail bool = false\n\t\t\tvar bEmptyOrDiff bool = false\n\t\t\tvar msgError string\n\t\t\tvar awsWorkerRole string\n\n\t\t\tawsWorkerRole = req.Worker[0].Role\n\t\t\tif awsWorkerRole == \"\" {\n\t\t\t\tbEmptyOrDiff = true\n\t\t\t}\n\n\t\t\tif bEmptyOrDiff == false {\n\t\t\t\tfor _, worker := range req.Worker {\n\t\t\t\t\tif awsWorkerRole != worker.Role {\n\t\t\t\t\t\tbEmptyOrDiff = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif bEmptyOrDiff == true {\n\t\t\t\tbFail = true\n\t\t\t\tmsgError = \"Role should be assigned\"\n\t\t\t} else {\n\t\t\t\tif err := awsPrepareCCM(req.Worker[0].Connection, clusterName, vms, provisioner, \"\", awsWorkerRole); err != nil {\n\t\t\t\t\tbFail = true\n\t\t\t\t\tmsgError = \"Failed to prepare cloud-controller-manager\"\n\t\t\t\t} else {\n\t\t\t\t\t// Success\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif bFail == true {\n\t\t\t\tcleanUpNodes(*provisioner)\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity: %v)\", msgError))\n\t\t\t} else {\n\t\t\t\t// Success\n\t\t\t\tlogger.Infof(\"[%s.%s] CCM ready has been completed.\", namespace, clusterName)\n\t\t\t}\n\t\t}\n\t}\n\n\t// save nodes metadata & update status\n\tfor _, node := range cluster.Nodes {\n\t\tnode.CreatedTime = lang.GetNowUTC()\n\t}\n\tif err := cluster.PutStore(); err != nil {\n\t\tcleanUpNodes(*provisioner)\n\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity. (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Nodes creation has been completed.\", namespace, clusterName)\n\n\tnodes := model.NewNodeList(namespace, clusterName)\n\tnodes.Items = cluster.Nodes\n\treturn nodes, nil\n}" ]
[ "0.6163938", "0.5139537", "0.4930724", "0.4848558", "0.4843541", "0.48335683", "0.48124602", "0.4799629", "0.4758989", "0.47470647", "0.47069877", "0.46792316", "0.4665263", "0.46608558", "0.46495008", "0.46242318", "0.4592622", "0.4582136", "0.45796773", "0.4575715", "0.45686665", "0.45571074", "0.4530229", "0.4526263", "0.44904533", "0.4489002", "0.44734016", "0.44680786", "0.44662443", "0.44503367", "0.4444655", "0.444239", "0.443906", "0.44329822", "0.44261563", "0.44229797", "0.4421242", "0.44148785", "0.44145167", "0.44136977", "0.44067004", "0.43894708", "0.43821526", "0.43820754", "0.4381639", "0.4373969", "0.43564627", "0.435558", "0.43447998", "0.4341733", "0.4332884", "0.43310744", "0.4329027", "0.4317986", "0.43124422", "0.43077233", "0.4307365", "0.42839384", "0.4281572", "0.42759523", "0.42751652", "0.4274506", "0.42730194", "0.42714012", "0.4265589", "0.42598388", "0.4258994", "0.42524812", "0.42417172", "0.42415926", "0.4236537", "0.42361912", "0.42150694", "0.42064428", "0.41974708", "0.41971332", "0.41934884", "0.41913322", "0.41898915", "0.41869286", "0.41852215", "0.41837323", "0.4178585", "0.41763633", "0.41761717", "0.4168295", "0.4163605", "0.41634458", "0.4159435", "0.41555104", "0.414874", "0.41486198", "0.41476205", "0.41476065", "0.41427517", "0.41417202", "0.413827", "0.41345417", "0.4130143", "0.41260675" ]
0.6088182
1
NewAddRemoteRDSNodeDefault creates a AddRemoteRDSNodeDefault with default headers values
func NewAddRemoteRDSNodeDefault(code int) *AddRemoteRDSNodeDefault { return &AddRemoteRDSNodeDefault{ _statusCode: code, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client IdentityClient) createTagDefault(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/tagDefaults\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response CreateTagDefaultResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func newSSHDefaultConfig(userName, identity string) (*sshClientConfig, error) {\n\tconfig, err := sshDefaultConfig(userName, identity)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &sshClientConfig{ClientConfig: config}, nil\n}", "func NewDefaultNode() *Node {\n\treturn &Node{\n\t\tPort: DefaultRedisPort,\n\t\tSlots: []Slot{},\n\t\tMigratingSlots: map[Slot]string{},\n\t\tImportingSlots: map[Slot]string{},\n\t}\n}", "func newNetworkDef() libvirtxml.Network {\n\tconst defNetworkXML = `\n\t\t<network>\n\t\t <name>default</name>\n\t\t <forward mode='nat'>\n\t\t <nat>\n\t\t <port start='1024' end='65535'/>\n\t\t </nat>\n\t\t </forward>\n\t\t</network>`\n\tif d, err := newDefNetworkFromXML(defNetworkXML); err != nil {\n\t\tpanic(fmt.Sprintf(\"Unexpected error while parsing default network definition: %s\", err))\n\t} else {\n\t\treturn d\n\t}\n}", "func (o *AddOrUpdateNodePoolConfigItemParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func (o *AddRemoteRDSNodeDefaultBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateDetails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (p *provider) AddDefaults(spec v1alpha1.MachineSpec) (v1alpha1.MachineSpec, error) {\n\treturn spec, nil\n}", "func (sess *reconcileStackSession) addDefaultPermalink(stack *pulumiv1alpha1.Stack) error {\n\tnamespacedName := types.NamespacedName{Name: stack.Name, Namespace: stack.Namespace}\n\terr := sess.getLatestResource(stack, namespacedName)\n\tif err != nil {\n\t\tsess.logger.Error(err, \"Failed to get latest Stack to update Stack Permalink URL\", \"Stack.Name\", stack.Spec.Stack)\n\t\treturn err\n\t}\n\tif stack.Status.LastUpdate == nil {\n\t\tstack.Status.LastUpdate = &pulumiv1alpha1.StackUpdateState{\n\t\t\tPermalink: pulumiv1alpha1.Permalink(fmt.Sprintf(\"%s/%s\", consoleURL, stack.Spec.Stack)),\n\t\t}\n\t} else {\n\t\tstack.Status.LastUpdate.Permalink = pulumiv1alpha1.Permalink(fmt.Sprintf(\"%s/%s\", consoleURL, stack.Name))\n\t}\n\terr = sess.updateResourceStatus(stack)\n\tif err != nil {\n\t\tsess.logger.Error(err, \"Failed to update Stack status with default permalink\", \"Stack.Name\", stack.Spec.Stack)\n\t\treturn err\n\t}\n\tsess.logger.Info(\"Successfully updated Stack with default permalink\", \"Stack.Name\", stack.Spec.Stack)\n\treturn nil\n}", "func (d *DefaulterBuilder) AddDefault(f *ResourceFunction) {\n\tif !d.resource.Equals(f.Resource(), astmodel.EqualityOverrides{}) {\n\t\tpanic(\"cannot add default function on non-matching object types\")\n\t}\n\td.defaults = append(d.defaults, f)\n}", "func (r *RequestBody) AddDefaults() {\n\tif r.DomainScope == \"\" {\n\t\tr.DomainScope = \"annotated\"\n\t}\n\tif len(r.Background) > 0 && r.DomainScope != \"custom\" {\n\t\tr.DomainScope = \"custom\"\n\t}\n\n\tif r.Organism == \"\" {\n\t\tr.Organism = \"hsapiens\"\n\t}\n\n\tif r.SignificanceThresholdMethod == \"\" {\n\t\tr.SignificanceThresholdMethod = \"gSCS\"\n\t}\n\n\tif r.UserThreshold == 0 {\n\t\tr.UserThreshold = 0.01\n\t}\n}", "func (client IdentityClient) updateTagDefault(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPut, \"/tagDefaults/{tagDefaultId}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response UpdateTagDefaultResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func addingDefaultFieldsToSchema(crdName string, schemaRaw []byte) ([]byte, error) {\n\tvar schema struct {\n\t\tProperties map[string]interface{} `json:\"properties\"`\n\t}\n\t_ = json.Unmarshal(schemaRaw, &schema)\n\n\tif len(schema.Properties) < 1 {\n\t\tlogging.V(6).Info(\"crd schema has no properties\", \"name\", crdName)\n\t\treturn schemaRaw, nil\n\t}\n\n\tif schema.Properties[\"apiVersion\"] == nil {\n\t\tapiVersionDefRaw := `{\"description\":\"APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources\",\"type\":\"string\"}`\n\t\tapiVersionDef := make(map[string]interface{})\n\t\t_ = json.Unmarshal([]byte(apiVersionDefRaw), &apiVersionDef)\n\t\tschema.Properties[\"apiVersion\"] = apiVersionDef\n\t}\n\n\tif schema.Properties[\"metadata\"] == nil {\n\t\tmetadataDefRaw := `{\"$ref\":\"#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta\",\"description\":\"Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata\"}`\n\t\tmetadataDef := make(map[string]interface{})\n\t\t_ = json.Unmarshal([]byte(metadataDefRaw), &metadataDef)\n\t\tschema.Properties[\"metadata\"] = metadataDef\n\t}\n\n\tschemaWithDefaultFields, _ := json.Marshal(schema)\n\n\treturn schemaWithDefaultFields, nil\n}", "func CreatePolicyWithDefaults(nbmaster string, httpClient *http.Client, jwt string) {\r\n fmt.Printf(\"\\nSending a POST request to create %s with defaults...\\n\", testPolicyName)\r\n\r\n policy := map[string]interface{}{\r\n \"data\": map[string]interface{}{\r\n \"type\": \"policy\",\r\n \"id\": testPolicyName,\r\n \"attributes\": map[string]interface{}{\r\n \"policy\": map[string]interface{}{\r\n \"policyName\": testPolicyName,\r\n \"policyType\": \"VMware\",\r\n \"policyAttributes\": map[string]interface{}{},\r\n \"clients\":[]interface{}{},\r\n \"schedules\":[]interface{}{},\r\n \"backupSelections\": map[string]interface{}{\r\n \"selections\": []interface{}{}}}}}}\r\n\r\n policyRequest, _ := json.Marshal(policy)\r\n\r\n uri := \"https://\" + nbmaster + \":\" + port + \"/netbackup/\" + policiesUri\r\n\r\n request, _ := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(policyRequest))\r\n request.Header.Add(\"Content-Type\", contentTypeV2);\r\n request.Header.Add(\"Authorization\", jwt);\r\n\r\n response, err := httpClient.Do(request)\r\n\r\n if err != nil {\r\n fmt.Printf(\"The HTTP request failed with error: %s\\n\", err)\r\n panic(\"Unable to create policy.\\n\")\r\n } else {\r\n if response.StatusCode != 204 {\r\n printErrorResponse(response)\r\n } else {\r\n fmt.Printf(\"%s created successfully.\\n\", testPolicyName);\r\n responseDetails, _ := httputil.DumpResponse(response, true);\r\n fmt.Printf(string(responseDetails))\r\n }\r\n }\r\n}", "func DefaultConfig(hostname string) *Config {\n\treturn &Config{\n\t\thostname,\n\t\t8, // 8 vnodes\n\t\tsha1.New, // SHA1\n\t\ttime.Duration(5 * time.Second),\n\t\ttime.Duration(15 * time.Second),\n\t\t8, // 8 successors\n\t\tnil, // No delegate\n\t\t160, // 160bit hash function\n\t\t\"\",\n\t}\n}", "func NewCfnModuleDefaultVersion_Override(c CfnModuleDefaultVersion, scope constructs.Construct, id *string, props *CfnModuleDefaultVersionProps) {\n\t_init_.Initialize()\n\n\t_jsii_.Create(\n\t\t\"aws-cdk-lib.aws_cloudformation.CfnModuleDefaultVersion\",\n\t\t[]interface{}{scope, id, props},\n\t\tc,\n\t)\n}", "func NewDefault() *Config {\n\tname := fmt.Sprintf(\"ec2-%s-%s\", getTS()[:10], randutil.String(12))\n\tif v := os.Getenv(AWS_K8S_TESTER_EC2_PREFIX + \"NAME\"); v != \"\" {\n\t\tname = v\n\t}\n\treturn &Config{\n\t\tmu: new(sync.RWMutex),\n\n\t\tUp: false,\n\t\tDeletedResources: make(map[string]string),\n\n\t\tName: name,\n\t\tPartition: endpoints.AwsPartitionID,\n\t\tRegion: endpoints.UsWest2RegionID,\n\n\t\t// to be auto-generated\n\t\tConfigPath: \"\",\n\t\tRemoteAccessCommandsOutputPath: \"\",\n\n\t\tLogColor: true,\n\t\tLogColorOverride: \"\",\n\n\t\tLogLevel: logutil.DefaultLogLevel,\n\t\t// default, stderr, stdout, or file name\n\t\t// log file named with cluster name will be added automatically\n\t\tLogOutputs: []string{\"stderr\"},\n\n\t\tOnFailureDelete: true,\n\t\tOnFailureDeleteWaitSeconds: 120,\n\n\t\tS3: getDefaultS3(),\n\t\tRole: getDefaultRole(),\n\t\tVPC: getDefaultVPC(),\n\t\tRemoteAccessKeyCreate: true,\n\t\tRemoteAccessPrivateKeyPath: filepath.Join(os.TempDir(), randutil.String(10)+\".insecure.key\"),\n\n\t\tASGsFetchLogs: true,\n\t\tASGs: map[string]ASG{\n\t\t\tname + \"-asg\": {\n\t\t\t\tName: name + \"-asg\",\n\t\t\t\tSSM: &SSM{\n\t\t\t\t\tDocumentCreate: false,\n\t\t\t\t\tDocumentName: \"\",\n\t\t\t\t\tDocumentCommands: \"\",\n\t\t\t\t\tDocumentExecutionTimeoutSeconds: 3600,\n\t\t\t\t},\n\t\t\t\tRemoteAccessUserName: \"ec2-user\", // for AL2\n\t\t\t\tAMIType: AMITypeAL2X8664,\n\t\t\t\tImageID: \"\",\n\t\t\t\tImageIDSSMParameter: \"/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2\",\n\t\t\t\tInstanceType: DefaultNodeInstanceTypeCPU,\n\t\t\t\tVolumeSize: DefaultNodeVolumeSize,\n\t\t\t\tASGMinSize: 1,\n\t\t\t\tASGMaxSize: 1,\n\t\t\t\tASGDesiredCapacity: 1,\n\t\t\t},\n\t\t},\n\t}\n}", "func (s *DataStore) CreateDefaultNode(name string) (*longhorn.Node, error) {\n\trequireLabel, err := s.GetSettingAsBool(types.SettingNameCreateDefaultDiskLabeledNodes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnode := &longhorn.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t\tSpec: longhorn.NodeSpec{\n\t\t\tName: name,\n\t\t\tAllowScheduling: true,\n\t\t\tEvictionRequested: false,\n\t\t\tTags: []string{},\n\t\t\tInstanceManagerCPURequest: 0,\n\t\t},\n\t}\n\n\t// For newly added node, the customized default disks will be applied only if the setting is enabled.\n\tif !requireLabel {\n\t\t// Note: this part wasn't moved to the controller is because\n\t\t// this will be done only once.\n\t\t// If user remove all the disks on the node, the default disk\n\t\t// will not be recreated automatically\n\t\tdataPath, err := s.GetSettingValueExisted(types.SettingNameDefaultDataPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorageReservedPercentageForDefaultDisk, err := s.GetSettingAsInt(types.SettingNameStorageReservedPercentageForDefaultDisk)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdisks, err := types.CreateDefaultDisk(dataPath, storageReservedPercentageForDefaultDisk)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnode.Spec.Disks = disks\n\t}\n\n\treturn s.CreateNode(node)\n}", "func DefaultHeader(k, v string) Opt {\n\treturn func(c *Client) Opt {\n\t\told, found := c.header[k]\n\t\told = append([]string{}, old...) // clone\n\t\tc.header.Add(k, v)\n\t\treturn func(c *Client) Opt {\n\t\t\tif found {\n\t\t\t\tc.header[k] = old\n\t\t\t} else {\n\t\t\t\tc.header.Del(k)\n\t\t\t}\n\t\t\treturn DefaultHeader(k, v)\n\t\t}\n\t}\n}", "func DefaultConfig() *NodeConfig {\n\tcfg := &NodeConfig{\n\t\tName: \"\",\n\t\tEnvs: []string{\"LOGGER_LEVEL=debug\"},\n\t\tBinds: []string{\n\t\t\tfmt.Sprintf(\"hornet-testing-assets:%s:rw\", assetsDir),\n\t\t},\n\t\tNetwork: DefaultNetworkConfig(),\n\t\tSnapshot: DefaultSnapshotConfig(),\n\t\tCoordinator: DefaultCoordinatorConfig(),\n\t\tProtocol: DefaultProtocolConfig(),\n\t\tRestAPI: DefaultRestAPIConfig(),\n\t\tPlugins: DefaultPluginConfig(),\n\t\tProfiling: DefaultProfilingConfig(),\n\t\tDashboard: DefaultDashboardConfig(),\n\t\tReceipts: DefaultReceiptValidatorConfig(),\n\t\tMigrator: DefaultMigratorConfig(),\n\t\tAutopeering: DefaultAutopeeringConfig(),\n\t}\n\tcfg.ExposedPorts = nat.PortSet{\n\t\tnat.Port(fmt.Sprintf(\"%s/tcp\", strings.Split(cfg.RestAPI.BindAddress, \":\")[1])): {},\n\t\t\"6060/tcp\": {},\n\t\t\"8081/tcp\": {},\n\t}\n\treturn cfg\n}", "func AddDefaultHeader(headerName string, value string) {\n\tdefaultHeaders[headerName] = value\n}", "func NewGetNodeUpgradesDefault(code int) *GetNodeUpgradesDefault {\n\treturn &GetNodeUpgradesDefault{\n\t\t_statusCode: code,\n\t}\n}", "func NewDefaults() map[string]interface{} {\n\tdefaults := make(map[string]interface{})\n\n\tdefaults[authPostgresURI] = \"postgresql://postgres:postgres@localhost:5432/test?sslmode=disable\"\n\tdefaults[authMigrationVersion] = 0\n\n\tdefaults[gatewayAddr] = \":10000\"\n\tdefaults[gatewayEndpoint] = \"/graphql\"\n\tdefaults[gatewayServePlayground] = true\n\tdefaults[gatewayPlaygroundEndpoint] = \"/playground\"\n\tdefaults[gatewayEnableIntrospection] = true\n\n\tdefaults[seedUserLogin] = \"root\"\n\tdefaults[seedUserPassword] = \"root\"\n\tdefaults[seedRoleTitle] = \"ROOT\"\n\tdefaults[seedRoleSuper] = true\n\n\tdefaults[sessionAccessTokenTTL] = 1000000\n\tdefaults[sessionRefreshTokenTTl] = 5000000\n\n\treturn defaults\n}", "func Default() *Root {\n\tdef := Root{\n\t\tAPI: API{\n\t\t\tListenAddress: \"/ip6/::1/tcp/1234/http\",\n\t\t\tTimeout: Duration(30 * time.Second),\n\t\t},\n\t\tLibp2p: Libp2p{\n\t\t\tListenAddresses: []string{\n\t\t\t\t\"/ip4/0.0.0.0/tcp/0\",\n\t\t\t\t\"/ip6/::/tcp/0\",\n\t\t\t},\n\t\t},\n\t}\n\treturn &def\n}", "func (bbc *BasicBannerCreate) defaults() {\n\tif _, ok := bbc.mutation.CreatedAt(); !ok {\n\t\tv := basicbanner.DefaultCreatedAt()\n\t\tbbc.mutation.SetCreatedAt(v)\n\t}\n\tif _, ok := bbc.mutation.Order(); !ok {\n\t\tv := basicbanner.DefaultOrder\n\t\tbbc.mutation.SetOrder(v)\n\t}\n\tif _, ok := bbc.mutation.Status(); !ok {\n\t\tv := basicbanner.DefaultStatus\n\t\tbbc.mutation.SetStatus(v)\n\t}\n}", "func (wrc *WorkspaceRoleCreate) defaults() {\n\tif _, ok := wrc.mutation.CreatedAt(); !ok {\n\t\tv := workspacerole.DefaultCreatedAt()\n\t\twrc.mutation.SetCreatedAt(v)\n\t}\n\tif _, ok := wrc.mutation.UpdatedAt(); !ok {\n\t\tv := workspacerole.DefaultUpdatedAt()\n\t\twrc.mutation.SetUpdatedAt(v)\n\t}\n\tif _, ok := wrc.mutation.ID(); !ok {\n\t\tv := workspacerole.DefaultID()\n\t\twrc.mutation.SetID(v)\n\t}\n}", "func NewDefault() elton.Handler {\n\treturn New(Config{})\n}", "func (client IdentityClient) CreateTagDefault(ctx context.Context, request CreateTagDefaultRequest) (response CreateTagDefaultResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\n\tif !(request.OpcRetryToken != nil && *request.OpcRetryToken != \"\") {\n\t\trequest.OpcRetryToken = common.String(common.RetryToken())\n\t}\n\n\tociResponse, err = common.Retry(ctx, request, client.createTagDefault, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = CreateTagDefaultResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = CreateTagDefaultResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(CreateTagDefaultResponse); ok {\n\t\tcommon.EcContext.UpdateEndOfWindow(time.Duration(240 * time.Second))\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into CreateTagDefaultResponse\")\n\t}\n\treturn\n}", "func (c *AKSCluster) AddDefaultsToUpdate(r *components.UpdateClusterRequest) {\n\n\tif r.Azure == nil {\n\t\tlog.Info(\"'azure' field is empty.\")\n\t\tr.Azure = &banzaiAzureTypes.UpdateClusterAzure{}\n\t}\n\n\tif len(r.Azure.NodePools) == 0 {\n\t\tstoredPools := c.modelCluster.Azure.NodePools\n\t\tnodePools := make(map[string]*banzaiAzureTypes.NodePoolUpdate)\n\t\tfor _, np := range storedPools {\n\t\t\tnodePools[np.Name] = &banzaiAzureTypes.NodePoolUpdate{\n\t\t\t\tCount: np.Count,\n\t\t\t}\n\t\t}\n\t\tr.Azure.NodePools = nodePools\n\t}\n\n}", "func NewPostDomainServiceNameGlueRecordHostUpdateDefault(code int) *PostDomainServiceNameGlueRecordHostUpdateDefault {\n\treturn &PostDomainServiceNameGlueRecordHostUpdateDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceProtocolsProtocolBgpGlobalDefaultRouteDistance(ctx context.Context, name string, identifier string, protocolName string, frinxOpenconfigBgpBgpglobalbaseDefaultRouteDistanceBodyParam FrinxOpenconfigBgpBgpglobalbaseDefaultRouteDistanceRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:protocols/frinx-openconfig-network-instance:protocol/{identifier}/{protocol-name}/frinx-openconfig-network-instance:bgp/frinx-openconfig-network-instance:global/frinx-openconfig-network-instance:default-route-distance/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"identifier\"+\"}\", fmt.Sprintf(\"%v\", identifier), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"protocol-name\"+\"}\", fmt.Sprintf(\"%v\", protocolName), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigBgpBgpglobalbaseDefaultRouteDistanceBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func NewDefault() *instance {\n\treturn New(\n\t\t[]factory.Contract{\n\t\t\texampleMetadataFactory.New(),\n\t\t\tiotaMetadataFactory.New(),\n\t\t\tipfsMetadataFactory.New(),\n\t\t},\n\t)\n}", "func (bc *BouncerCreate) defaults() {\n\tif _, ok := bc.mutation.CreatedAt(); !ok {\n\t\tv := bouncer.DefaultCreatedAt()\n\t\tbc.mutation.SetCreatedAt(v)\n\t}\n\tif _, ok := bc.mutation.UpdatedAt(); !ok {\n\t\tv := bouncer.DefaultUpdatedAt()\n\t\tbc.mutation.SetUpdatedAt(v)\n\t}\n\tif _, ok := bc.mutation.IPAddress(); !ok {\n\t\tv := bouncer.DefaultIPAddress\n\t\tbc.mutation.SetIPAddress(v)\n\t}\n\tif _, ok := bc.mutation.Until(); !ok {\n\t\tv := bouncer.DefaultUntil()\n\t\tbc.mutation.SetUntil(v)\n\t}\n\tif _, ok := bc.mutation.LastPull(); !ok {\n\t\tv := bouncer.DefaultLastPull()\n\t\tbc.mutation.SetLastPull(v)\n\t}\n\tif _, ok := bc.mutation.AuthType(); !ok {\n\t\tv := bouncer.DefaultAuthType\n\t\tbc.mutation.SetAuthType(v)\n\t}\n}", "func AddDefaultUser() error {\n\t// Add the new user to the database\n\tdbQuery := `\n\t\tINSERT INTO users (auth0_id, user_name, email, password_hash, client_cert, display_name)\n\t\tVALUES ($1, $2, $3, $4, $5, $6)\n\t\tON CONFLICT (user_name)\n\t\t\tDO NOTHING`\n\t_, err := pdb.Exec(dbQuery, RandomString(16), \"default\", \"default@dbhub.io\", RandomString(16), \"\",\n\t\t\"Default system user\")\n\tif err != nil {\n\t\tlog.Printf(\"Error when adding the default user to the database: %v\\n\", err)\n\t\t// For now, don't bother logging a failure here. This *might* need changing later on\n\t\treturn err\n\t}\n\n\t// Log addition of the default user\n\tlog.Println(\"Default user added\")\n\treturn nil\n}", "func (a *FrinxOpenconfigNetworkInstanceApiService) PutFrinxOpenconfigNetworkInstanceNetworkInstancesNetworkInstanceProtocolsProtocolBgpGlobalDefaultRouteDistanceConfig(ctx context.Context, name string, identifier string, protocolName string, frinxOpenconfigBgpBgpglobalbaseDefaultroutedistanceConfigBodyParam FrinxOpenconfigBgpBgpglobalbaseDefaultroutedistanceConfigRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-network-instance:network-instances/frinx-openconfig-network-instance:network-instance/{name}/frinx-openconfig-network-instance:protocols/frinx-openconfig-network-instance:protocol/{identifier}/{protocol-name}/frinx-openconfig-network-instance:bgp/frinx-openconfig-network-instance:global/frinx-openconfig-network-instance:default-route-distance/frinx-openconfig-network-instance:config/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"identifier\"+\"}\", fmt.Sprintf(\"%v\", identifier), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"protocol-name\"+\"}\", fmt.Sprintf(\"%v\", protocolName), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &frinxOpenconfigBgpBgpglobalbaseDefaultroutedistanceConfigBodyParam\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func NewModuleDefaultVersion(ctx *pulumi.Context,\n\tname string, args *ModuleDefaultVersionArgs, opts ...pulumi.ResourceOption) (*ModuleDefaultVersion, error) {\n\tif args == nil {\n\t\targs = &ModuleDefaultVersionArgs{}\n\t}\n\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource ModuleDefaultVersion\n\terr := ctx.RegisterResource(\"aws-native:cloudformation:ModuleDefaultVersion\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (helper *vpnHelper) CreateDefaultUser() derrors.Error {\n\t//Create user\n\tcmd := exec.Command(command, cmdMode, defaultVPNServer, hub, cmdCmd, userCreateCmd, defaultVPNUser, group, realName, note)\n\tlog.Debug().Str(\"Server\", defaultVPNServer).Str(\"Username\", defaultVPNUser).Msg(\"Default user created in VPN Server\")\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\treturn derrors.NewGenericError(\"error executing UserCreate command\", err)\n\t}\n\n\t// Execute UserPasswordSet command for Username\n\tcmd = exec.Command(command, cmdMode, defaultVPNServer, hub, cmdCmd, userPasswordSetCmd, defaultVPNUser, userPassword+defaultVPNPassword)\n\tlog.Debug().Str(\"Server\", defaultVPNServer).Str(\"Username\", defaultVPNUser).Msg(\"Password for default user created\")\n\n\terr = cmd.Run()\n\tif err != nil {\n\t\treturn derrors.NewGenericError(\"error executing UserDelete userPasswordSet command\", err)\n\t}\n\n\treturn nil\n}", "func CreateConfig() *Config {\n return &Config{\n HeaderName: defaultHeader,\n }\n}", "func (e *RegisterRequest) SetDefaults() {\n}", "func newInstallOptionsWithDefaults() (*installOptions, error) {\n\tdefaults, err := l5dcharts.NewValues(false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tissuanceLifetime, err := time.ParseDuration(defaults.Identity.Issuer.IssuanceLifetime)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclockSkewAllowance, err := time.ParseDuration(defaults.Identity.Issuer.ClockSkewAllowance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &installOptions{\n\t\tclusterDomain: defaults.Global.ClusterDomain,\n\t\tcontrolPlaneVersion: version.Version,\n\t\tcontrollerReplicas: defaults.ControllerReplicas,\n\t\tcontrollerLogLevel: defaults.ControllerLogLevel,\n\t\tprometheusImage: defaults.PrometheusImage,\n\t\thighAvailability: defaults.Global.HighAvailability,\n\t\tcontrollerUID: defaults.ControllerUID,\n\t\tdisableH2Upgrade: !defaults.EnableH2Upgrade,\n\t\tdisableHeartbeat: defaults.DisableHeartBeat,\n\t\tcniEnabled: defaults.Global.CNIEnabled,\n\t\tomitWebhookSideEffects: defaults.OmitWebhookSideEffects,\n\t\trestrictDashboardPrivileges: defaults.RestrictDashboardPrivileges,\n\t\tcontrolPlaneTracing: defaults.Global.ControlPlaneTracing,\n\t\tsmiMetricsEnabled: defaults.SMIMetrics.Enabled,\n\t\tsmiMetricsImage: defaults.SMIMetrics.Image,\n\t\tproxyConfigOptions: &proxyConfigOptions{\n\t\t\tproxyVersion: version.Version,\n\t\t\tignoreCluster: false,\n\t\t\tproxyImage: defaults.Global.Proxy.Image.Name,\n\t\t\tinitImage: defaults.Global.ProxyInit.Image.Name,\n\t\t\tinitImageVersion: version.ProxyInitVersion,\n\t\t\tdebugImage: defaults.DebugContainer.Image.Name,\n\t\t\tdebugImageVersion: version.Version,\n\t\t\tdockerRegistry: defaultDockerRegistry,\n\t\t\timagePullPolicy: defaults.Global.ImagePullPolicy,\n\t\t\tignoreInboundPorts: nil,\n\t\t\tignoreOutboundPorts: nil,\n\t\t\tproxyUID: defaults.Global.Proxy.UID,\n\t\t\tproxyLogLevel: defaults.Global.Proxy.LogLevel,\n\t\t\tproxyControlPort: uint(defaults.Global.Proxy.Ports.Control),\n\t\t\tproxyAdminPort: uint(defaults.Global.Proxy.Ports.Admin),\n\t\t\tproxyInboundPort: uint(defaults.Global.Proxy.Ports.Inbound),\n\t\t\tproxyOutboundPort: uint(defaults.Global.Proxy.Ports.Outbound),\n\t\t\tproxyCPURequest: defaults.Global.Proxy.Resources.CPU.Request,\n\t\t\tproxyMemoryRequest: defaults.Global.Proxy.Resources.Memory.Request,\n\t\t\tproxyCPULimit: defaults.Global.Proxy.Resources.CPU.Limit,\n\t\t\tproxyMemoryLimit: defaults.Global.Proxy.Resources.Memory.Limit,\n\t\t\tenableExternalProfiles: defaults.Global.Proxy.EnableExternalProfiles,\n\t\t\twaitBeforeExitSeconds: defaults.Global.Proxy.WaitBeforeExitSeconds,\n\t\t},\n\t\tidentityOptions: &installIdentityOptions{\n\t\t\ttrustDomain: defaults.Global.IdentityTrustDomain,\n\t\t\tissuanceLifetime: issuanceLifetime,\n\t\t\tclockSkewAllowance: clockSkewAllowance,\n\t\t\tidentityExternalIssuer: false,\n\t\t},\n\n\t\theartbeatSchedule: func() string {\n\t\t\t// Some of the heartbeat Prometheus queries rely on 5m resolution, which\n\t\t\t// means at least 5 minutes of data available. Start the first CronJob 10\n\t\t\t// minutes after `linkerd install` is run, to give the user 5 minutes to\n\t\t\t// install.\n\t\t\tt := time.Now().Add(10 * time.Minute).UTC()\n\t\t\treturn fmt.Sprintf(\"%d %d * * * \", t.Minute(), t.Hour())\n\t\t},\n\t}, nil\n}", "func defaultHandler(w http.ResponseWriter, r *http.Request) {\n\tnode := node.GetNodeName()\n\tw.Write([]byte(\"Hello bubble tea server !! Node name: \" + node))\n}", "func CreateDefaultExtNetwork(networkType string) error {\n\treturn fmt.Errorf(\"CreateDefaultExtNetwork shouldn't be called for linux platform\")\n}", "func (o *AddOrUpdateNodePoolConfigItemParams) WithDefaults() *AddOrUpdateNodePoolConfigItemParams {\n\to.SetDefaults()\n\treturn o\n}", "func (dsc *DataSourceCreate) defaults() {\n\tif _, ok := dsc.mutation.Address(); !ok {\n\t\tv := datasource.DefaultAddress\n\t\tdsc.mutation.SetAddress(v)\n\t}\n}", "func (f *FakeIPWrapper) AddDefaultRoute(gw net.IP, dev netlink.Link) error {\n\tif _, ok := f.data[dev.Attrs().HardwareAddr.String()]; !ok {\n\t\tf.data[dev.Attrs().HardwareAddr.String()] = gw\n\t}\n\treturn nil\n}", "func newnode(id byte, name string, value string) *xmlx.Node {\n\tnode := xmlx.NewNode(id)\n\tif name != \"\" {\n\t\tnode.Name = xml.Name{\n\t\t\tLocal: name,\n\t\t}\n\t}\n\tif value != \"\" {\n\t\tnode.Value = value\n\t}\n\treturn node\n}", "func (edgeFunctionsApi *EdgeFunctionsApiV1) SetDefaultHeaders(headers http.Header) {\n\tedgeFunctionsApi.Service.SetDefaultHeaders(headers)\n}", "func newDefaultContainerConfig() ContainerConfig {\n\treturn ContainerConfig{\n\t\tCPU: newMinMaxAllocation(),\n\t\tMemory: newMinMaxAllocation(),\n\t\tBlockRead: newMinMaxAllocation(),\n\t\tBlockWrite: newMinMaxAllocation(),\n\t\tNetworkRx: newMinMaxAllocation(),\n\t\tNetworkTx: newMinMaxAllocation(),\n\t}\n}", "func (in *ManagedCluster) Default() {\n}", "func addDefaultYamlFile(dYamlPath string, configs *[]*RawConfig) {\n\tenvs, targets, err := BuiltinDefault()\n\tdConfig := &RawConfig{\n\t\tFilepath: \"builtin:target/default.yaml\",\n\t\tEnvs: envs,\n\t\tTargets: targets,\n\t}\n\tif dYamlPath != \"\" {\n\t\tdConfig, err = LoadConfigFile(dYamlPath)\n\t\tif err != nil {\n\t\t\tfmt.Println(color.Red(err.Error()))\n\t\t\treturn\n\t\t}\n\t\tdConfig.Filepath = dYamlPath\n\t}\n\tdConfig.Envs = strings.TrimSpace(dConfig.Envs)\n\tdConfig.Remotes = strings.TrimSpace(dConfig.Remotes)\n\tdConfig.Targets = strings.TrimSpace(dConfig.Targets)\n\t*configs = append(*configs, dConfig)\n}", "func addDefaultValuesToViper(v *viper.Viper) {\n\tflagSet := &flag.FlagSet{}\n\tkafkaexporter.DefaultOptions().AddFlags(flagSet)\n\telasticsearchexporter.DefaultOptions().AddFlags(flagSet)\n\tcassandraexporter.DefaultOptions().AddFlags(flagSet)\n\tpflagSet := &pflag.FlagSet{}\n\tpflagSet.AddGoFlagSet(flagSet)\n\tv.BindPFlags(pflagSet)\n}", "func SetDefaultRegistry(uri string) {\n\tregistryURI = uri\n}", "func (bc *BlockCreate) defaults() {\n\tif _, ok := bc.mutation.CreateTime(); !ok {\n\t\tv := block.DefaultCreateTime()\n\t\tbc.mutation.SetCreateTime(v)\n\t}\n\tif _, ok := bc.mutation.UpdateTime(); !ok {\n\t\tv := block.DefaultUpdateTime()\n\t\tbc.mutation.SetUpdateTime(v)\n\t}\n}", "func DefaultMeta() *Meta {\n\treturn &Meta{\n\t\tMirror: \"http://mirrors.servercentral.com/voidlinux/current\",\n\t\tServices: []string{\"dhcpcd\", \"sshd\"},\n\t}\n}", "func NewCfnModuleDefaultVersion(scope constructs.Construct, id *string, props *CfnModuleDefaultVersionProps) CfnModuleDefaultVersion {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnModuleDefaultVersion{}\n\n\t_jsii_.Create(\n\t\t\"aws-cdk-lib.aws_cloudformation.CfnModuleDefaultVersion\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func Default() *Server {\n\tf := logrus.Fields{\n\t\tLogLatency: 0,\n\t\tLogServerHostname: \"\",\n\t\tLogRemoteAddr: \"\",\n\t\tLogRequestSize: 0,\n\t\tLogResponseSize: 0,\n\t}\n\tl := logrus.New()\n\tl.Formatter = &logrus.TextFormatter{DisableTimestamp: true}\n\th := New()\n\th.Use(Logger(l, f))\n\th.Use(Recovery())\n\treturn h\n}", "func Default() *Config {\n\treturn &Config{\n\t\tEnv: &Env{Region: region, Zone: zone, DeployEnv: deployEnv, Host: host, Weight: weight},\n\t\tDiscovery: &naming.Config{Region: region, Zone: zone, Env: deployEnv, Host: host},\n\t\tHTTPServer: &HTTPServer{\n\t\t\tNetwork: \"tcp\",\n\t\t\tAddr: \"3111\",\n\t\t\tReadTimeout: xtime.Duration(time.Second),\n\t\t\tWriteTimeout: xtime.Duration(time.Second),\n\t\t},\n\t\tRPCClient: &RPCClient{Dial: xtime.Duration(time.Second), Timeout: xtime.Duration(time.Second)},\n\t\tRPCServer: &RPCServer{\n\t\t\tNetwork: \"tcp\",\n\t\t\tAddr: \"3119\",\n\t\t\tTimeout: xtime.Duration(time.Second),\n\t\t\tIdleTimeout: xtime.Duration(time.Second * 60),\n\t\t\tMaxLifeTime: xtime.Duration(time.Hour * 2),\n\t\t\tForceCloseWait: xtime.Duration(time.Second * 20),\n\t\t\tKeepAliveInterval: xtime.Duration(time.Second * 60),\n\t\t\tKeepAliveTimeout: xtime.Duration(time.Second * 20),\n\t\t},\n\t\tBackoff: &Backoff{MaxDelay: 300, BaseDelay: 3, Factor: 1.8, Jitter: 1.3},\n\t}\n}", "func NewUpdateHostGroupsDefault(code int) *UpdateHostGroupsDefault {\n\treturn &UpdateHostGroupsDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (p *param) Default() []byte {\n\treturn []byte(`{\"descr\":\"Normal network L0 server\",\"prefix\":[\"tg001\"]}`)\n}", "func Defaults() Definition {\n\treturn Definition{\n\n\t\tHost: \"\",\n\n\t\tPort: \"9000\",\n\n\t\tEndpoint: \"/api\",\n\n\t\tUsername: \"\",\n\n\t\tPassword: \"\",\n\n\t\tScheme: \"http\",\n\n\t}\n}", "func (n *Node) New(name string, def_val interface{}) (*Node, error) {\n\tif !valid_name(name) {\n\t\treturn nil, errors.New(\"Invalid Name\")\n\t}\n\n\tn.mutex.Lock()\n\tdefer n.mutex.Unlock()\n\n\tif n.nodes[name] != nil {\n\t\treturn nil, errors.New(\"Already exists\")\n\t}\n\n\tnew_node := &Node{\n\t\tname: name,\n\t\tdelimiter: n.delimiter,\n\t\tparent: n,\n\t\tnodes: make(map[string]*Node),\n\t}\n\n\tif def_val != nil {\n\t\tnew_node.def_val = new(string)\n\n\t\tvar str_val string\n\t\tswitch t := def_val.(type) {\n\t\tcase string:\n\t\t\tif val, ok := def_val.(string); ok {\n\t\t\t\tstr_val = val\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"Unabled to assert type string on default value\")\n\t\t\t}\n\t\tcase []byte:\n\t\t\tif val, ok := def_val.([]byte); ok {\n\t\t\t\tstr_val = string(val)\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"Unabled to assert type []byte on default value\")\n\t\t\t}\n\t\tcase fmt.Stringer:\n\t\t\tif val, ok := def_val.(fmt.Stringer); ok {\n\t\t\t\tstr_val = val.String()\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"Unabled to assert type fmt.Stringer on default value\")\n\t\t\t}\n\t\tcase int:\n\t\t\tif val, ok := def_val.(int); ok {\n\t\t\t\tstr_val = strconv.Itoa(val)\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"Unabled to assert type int on default value\")\n\t\t\t}\n\t\tcase float64:\n\t\t\tif val, ok := def_val.(float64); ok {\n\t\t\t\tstr_val = strconv.FormatFloat(val, 'f', -1, 64)\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"Unabled to assert type float64 on default value\")\n\t\t\t}\n\t\tcase bool:\n\t\t\tif val, ok := def_val.(bool); ok {\n\t\t\t\tstr_val = strconv.FormatBool(val)\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"Unabled to assert type bool on default value\")\n\t\t\t}\n\t\tdefault:\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Unexpected type %T\", t))\n\t\t}\n\n\t\t*new_node.def_val = str_val\n\t}\n\n\tn.nodes[name] = new_node\n\treturn n.nodes[name], nil\n}", "func defaultHostConfigModifier(req ContainerRequest) func(hostConfig *container.HostConfig) {\n\treturn func(hostConfig *container.HostConfig) {\n\t\thostConfig.AutoRemove = req.AutoRemove\n\t\thostConfig.CapAdd = req.CapAdd\n\t\thostConfig.CapDrop = req.CapDrop\n\t\thostConfig.Binds = req.Binds\n\t\thostConfig.ExtraHosts = req.ExtraHosts\n\t\thostConfig.NetworkMode = req.NetworkMode\n\t\thostConfig.Resources = req.Resources\n\t}\n}", "func NewDescribeDefault(code int) *DescribeDefault {\n\tif code <= 0 {\n\t\tcode = 500\n\t}\n\n\treturn &DescribeDefault{\n\t\t_statusCode: code,\n\t}\n}", "func Default() *Config {\n\treturn &Config{\n\t\tEnv: &Env{Region: region, Zone: zone, DeployEnv: deployEnv, Host: host},\n\t\tDiscovery: &naming.Config{Region: region, Zone: zone, Env: deployEnv, Host: host},\n\t}\n}", "func NewCfnResourceDefaultVersion_Override(c CfnResourceDefaultVersion, scope constructs.Construct, id *string, props *CfnResourceDefaultVersionProps) {\n\t_init_.Initialize()\n\n\t_jsii_.Create(\n\t\t\"aws-cdk-lib.aws_cloudformation.CfnResourceDefaultVersion\",\n\t\t[]interface{}{scope, id, props},\n\t\tc,\n\t)\n}", "func Default() *Config {\n\treturn &Config{\n\t\tEnv: &Env{DeployEnv: deployEnv, Host: host, Weight: weight},\n\t\tTCPServer: &TCPServer{\n\t\t\tNetwork: \"tcp\",\n\t\t\tAddr: \"3119\",\n\t\t\tReadTimeout: xtime.Duration(time.Second),\n\t\t\tWriteTimeout: xtime.Duration(time.Second),\n\t\t},\n\t\tHTTPServer: &HTTPServer{\n\t\t\tNetwork: \"tcp\",\n\t\t\tAddr: \"3111\",\n\t\t\tReadTimeout: xtime.Duration(time.Second),\n\t\t\tWriteTimeout: xtime.Duration(time.Second),\n\t\t},\n\t\tBucket: &Bucket{\n\t\t\tSize: 32,\n\t\t\tChannel: 1024,\n\t\t\tRoom: 1024,\n\t\t\tRoutineAmount: 32,\n\t\t\tRoutineSize: 1024,\n\t\t},\n\t\tRPCClient: &RPCClient{Dial: xtime.Duration(time.Second), Timeout: xtime.Duration(time.Second), SrvAddr: \":3119\"},\n\t\tRPCServer: &RPCServer{\n\t\t\tNetwork: \"tcp\",\n\t\t\tAddr: \"3119\",\n\t\t\tTimeout: xtime.Duration(time.Second),\n\t\t\tIdleTimeout: xtime.Duration(time.Second * 60),\n\t\t\tMaxLifeTime: xtime.Duration(time.Hour * 2),\n\t\t\tForceCloseWait: xtime.Duration(time.Second * 20),\n\t\t\tKeepAliveInterval: xtime.Duration(time.Second * 60),\n\t\t\tKeepAliveTimeout: xtime.Duration(time.Second * 20),\n\t\t},\n\t}\n}", "func (nuo *NodeUpdateOne) defaults() {\n\tif _, ok := nuo.mutation.UpdatedAt(); !ok {\n\t\tv := node.UpdateDefaultUpdatedAt()\n\t\tnuo.mutation.SetUpdatedAt(v)\n\t}\n}", "func (o *ListMachineDeploymentNodesParams) SetDefaults() {\n\t// no default values defined for this parameter\n}", "func newDefaultEnvoyClusterConfig() *envoy_config_cluster_v3.Cluster {\n\treturn &envoy_config_cluster_v3.Cluster{\n\t\tConnectTimeout: defaultConnectionTimeout,\n\t\tRespectDnsTtl: true,\n\t\tDnsLookupFamily: envoy_config_cluster_v3.Cluster_AUTO,\n\t}\n}", "func createNewNodeNetworkObject(writer *bufio.Writer, sourceOsmNode *osm.Node) {\n\ttags := sourceOsmNode.TagMap()\n\n\t// Punktnetzwerk 'Fahrrad'\n\tnewOsmNode := *sourceOsmNode // copy content (don't modify origin/source node)\n\tnewOsmNode.ID = 0\n\tnewOsmNode.Tags = []osm.Tag{} // remove all source tags\n\trefValue, found := tags[\"icn_ref\"]\n\tif found {\n\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_bicycle\"}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\twriteNewNodeObject(writer, &newOsmNode)\n\t} else {\n\t\trefValue, found = tags[\"ncn_ref\"]\n\t\tif found {\n\t\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_bicycle\"}\n\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\twriteNewNodeObject(writer, &newOsmNode)\n\t\t} else {\n\t\t\trefValue, found = tags[\"rcn_ref\"]\n\t\t\tif found {\n\t\t\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_bicycle\"}\n\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\twriteNewNodeObject(writer, &newOsmNode)\n\t\t\t} else {\n\t\t\t\trefValue, found = tags[\"lcn_ref\"]\n\t\t\t\tif found {\n\t\t\t\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_bicycle\"}\n\t\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\t\twriteNewNodeObject(writer, &newOsmNode)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Punktnetzwerk 'Wandern'\n\tnewOsmNode = *sourceOsmNode // copy content (don't modify origin/source node)\n\tnewOsmNode.ID = 0\n\tnewOsmNode.Tags = []osm.Tag{} // remove all source tags\n\trefValue, found = tags[\"iwn_ref\"]\n\tif found {\n\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_hiking\"}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\twriteNewNodeObject(writer, &newOsmNode)\n\t} else {\n\t\trefValue, found = tags[\"nwn_ref\"]\n\t\tif found {\n\t\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_hiking\"}\n\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\twriteNewNodeObject(writer, &newOsmNode)\n\t\t} else {\n\t\t\trefValue, found = tags[\"rwn_ref\"]\n\t\t\tif found {\n\t\t\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_hiking\"}\n\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\twriteNewNodeObject(writer, &newOsmNode)\n\t\t\t} else {\n\t\t\t\trefValue, found = tags[\"lwn_ref\"]\n\t\t\t\tif found {\n\t\t\t\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_hiking\"}\n\t\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\t\t\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\t\t\t\twriteNewNodeObject(writer, &newOsmNode)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Punktnetzwerk 'Inline-Skaten'\n\tnewOsmNode = *sourceOsmNode // copy content (don't modify origin/source node)\n\tnewOsmNode.ID = 0\n\tnewOsmNode.Tags = []osm.Tag{} // remove all source tags\n\trefValue, found = tags[\"rin_ref\"]\n\tif found {\n\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_inline_skates\"}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\twriteNewNodeObject(writer, &newOsmNode)\n\t}\n\n\t// Punktnetzwerk 'Reiten'\n\tnewOsmNode = *sourceOsmNode // copy content (don't modify origin/source node)\n\tnewOsmNode.ID = 0\n\tnewOsmNode.Tags = []osm.Tag{} // remove all source tags\n\trefValue, found = tags[\"rhn_ref\"]\n\tif found {\n\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_horse\"}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\twriteNewNodeObject(writer, &newOsmNode)\n\t}\n\n\t// Punktnetzwerk 'Kanu'\n\tnewOsmNode = *sourceOsmNode // copy content (don't modify origin/source node)\n\tnewOsmNode.ID = 0\n\tnewOsmNode.Tags = []osm.Tag{} // remove all source tags\n\trefValue, found = tags[\"rpn_ref\"]\n\tif found {\n\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_canoe\"}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\twriteNewNodeObject(writer, &newOsmNode)\n\t}\n\n\t// Punktnetzwerk 'Motorboot'\n\tnewOsmNode = *sourceOsmNode // copy content (don't modify origin/source node)\n\tnewOsmNode.ID = 0\n\tnewOsmNode.Tags = []osm.Tag{} // remove all source tags\n\trefValue, found = tags[\"rmn_ref\"]\n\tif found {\n\t\ttag := osm.Tag{Key: \"node_network\", Value: \"node_motorboat\"}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\ttag = osm.Tag{Key: \"name\", Value: refValue}\n\t\tnewOsmNode.Tags = append(newOsmNode.Tags, tag)\n\t\twriteNewNodeObject(writer, &newOsmNode)\n\t}\n}", "func SetDefaults_NodeConfiguration(obj *NodeConfiguration) {\n\tif len(obj.ContainerRuntimeConfiguration.Version) == 0 {\n\t\tobj.ContainerRuntimeConfiguration.Version = DefaultContainerRuntimeVersion\n\t}\n\tif len(obj.ContainerRuntimeConfiguration.Endpoint) == 0 {\n\t\tobj.ContainerRuntimeConfiguration.Endpoint = DefaultContainerRuntimeEndpoint\n\t}\n}", "func (r *Storage) Default() {\n\tstoragelog.Info(\"default\", \"name\", r.Name)\n\tif r.Spec.ConnectType == \"internal\" {\n\t\tif r.Spec.Image == \"\" {\n\t\t\tr.Spec.Image = \"docker.elastic.co/elasticsearch/elasticsearch:7.5.1\"\n\t\t}\n\t\tif r.Spec.Instances == 0 {\n\t\t\tr.Spec.Instances = 3\n\t\t}\n\t}\n}", "func AddDefaultData(td *templates.TemplateData) *templates.TemplateData {\n\ttd.ClientVersion = fmt.Sprintf(`<strong><a href=\"https://github.com/tsawler/courses/\" target=\"_blank\">Courses</a></strong> %s`, version)\n\treturn td\n}", "func RegisterDefaults() {\n\tviper.SetDefault(\"crypto.cost\", 10)\n\n\tviper.SetDefault(\"env\", \"development\")\n\n\t// database defaults\n\tviper.SetDefault(\"database.development.host\", \"localhost\")\n\tviper.SetDefault(\"database.development.username\", \"neo4j\")\n\tviper.SetDefault(\"database.development.port\", 7687)\n}", "func (rc *ResourceCreate) defaults() {\n\tif _, ok := rc.mutation.UpdatedAt(); !ok {\n\t\tv := resource.DefaultUpdatedAt()\n\t\trc.mutation.SetUpdatedAt(v)\n\t}\n}", "func NewPostGatewayConnectNetaddressDefault(code int) *PostGatewayConnectNetaddressDefault {\n\treturn &PostGatewayConnectNetaddressDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (globalLoadBalancerMonitor *GlobalLoadBalancerMonitorV1) SetDefaultHeaders(headers http.Header) {\n\tglobalLoadBalancerMonitor.Service.SetDefaultHeaders(headers)\n}", "func (c *Configuration) AddDefaultHeader(key string, value string) {\n\tc.DefaultHeader[key] = value\n}", "func NewDefaultRegistryConfig(protocol string) *RegistryConfig {\n\tswitch protocol {\n\tcase \"zookeeper\":\n\t\treturn &RegistryConfig{\n\t\t\tProtocol: protocol,\n\t\t\tAddress: defaultZKAddr,\n\t\t\tTimeoutStr: defaultRegistryTimeout,\n\t\t}\n\tcase \"consul\":\n\t\treturn &RegistryConfig{\n\t\t\tProtocol: protocol,\n\t\t\tAddress: defaultConsulAddr,\n\t\t\tTimeoutStr: defaultRegistryTimeout,\n\t\t}\n\tcase \"nacos\":\n\t\treturn &RegistryConfig{\n\t\t\tProtocol: protocol,\n\t\t\tAddress: defaultNacosAddr,\n\t\t\tTimeoutStr: defaultRegistryTimeout,\n\t\t}\n\tdefault:\n\t\treturn &RegistryConfig{\n\t\t\tProtocol: protocol,\n\t\t}\n\t}\n}", "func (c *ConfigPolicyNode) AddDefaults(m map[string]ctypes.ConfigValue) (*map[string]ctypes.ConfigValue, *ProcessingErrors) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tpErrors := NewProcessingErrors()\n\t// Loop through each rule and process\n\tfor key, rule := range c.rules {\n\t\t// items exists for rule\n\t\tif _, ok := m[key]; ok {\n\t\t\tpErrors.AddError(fmt.Errorf(\"The key \\\"%v\\\" already has a default policy for this plugin\", key))\n\t\t} else {\n\t\t\t// If it was required add error\n\t\t\tif !rule.Required() {\n\t\t\t\t// If default returns we should add it\n\t\t\t\tcv := rule.Default()\n\t\t\t\tif cv != nil {\n\t\t\t\t\tm[key] = cv\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif pErrors.HasErrors() {\n\t\treturn nil, pErrors\n\t}\n\treturn &m, pErrors\n}", "func CreateOrUpdate(ctx context.Context, client client.Interface, node *libapi.Node) (*libapi.Node, error) {\n\tif node.ResourceVersion != \"\" {\n\t\treturn client.Nodes().Update(ctx, node, options.SetOptions{})\n\t}\n\n\treturn client.Nodes().Create(ctx, node, options.SetOptions{})\n}", "func setDefault(c *Config) {\n\tc.Token = \"\"\n\tc.GuildID = \"\"\n}", "func (req *Request) DefaultHeaders(mKey string) (err error) {\n\treq.Header.Add(HeaderXDate, time.Now().UTC().Format(\"Mon, 02 Jan 2006 15:04:05 GMT\"))\n\treq.Header.Add(HeaderVersion, SupportedAPIVersion)\n\treq.Header.Add(HeaderUserAgent, UserAgent)\n\n\t// Auth\n\tparts := req.Method + \"\\n\" +\n\t\treq.rType + \"\\n\" +\n\t\treq.rLink + \"\\n\" +\n\t\treq.Header.Get(HeaderXDate) + \"\\n\" +\n\t\treq.Header.Get(\"Date\") + \"\\n\"\n\n\tpartsLower := strings.ToLower(parts)\n\n\tsign, err := authorize(partsLower, mKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmasterToken := \"master\"\n\ttokenVersion := \"1.0\"\n\treq.Header.Add(HeaderAuth, url.QueryEscape(\"type=\"+masterToken+\"&ver=\"+tokenVersion+\"&sig=\"+sign))\n\treturn\n}", "func CreateDefaultUser(username, password string) (err error) {\n\n err = checkInit()\n if err != nil {\n return\n }\n\n var users = data[\"users\"].(map[string]interface{})\n // Check if the default user exists\n if len(users) > 0 {\n err = createError(001)\n return\n }\n\n var defaults = defaultsForNewUser(username, password)\n users[defaults[\"_id\"].(string)] = defaults\n saveDatabase(data)\n\n return\n}", "func (i *InstanceServiceHandler) DefaultReverseIPv4(ctx context.Context, instanceID, ip string) error {\n\turi := fmt.Sprintf(\"%s/%s/ipv4/reverse/default\", instancePath, instanceID)\n\treqBody := RequestBody{\"ip\": ip}\n\n\treq, err := i.client.NewRequest(ctx, http.MethodPost, uri, reqBody)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.client.DoWithContext(ctx, req, nil)\n}", "func DefaultEnvConfig() (*Config, error) {\n\tif !env.OnGCE() {\n\t\treturn nil, nil\n\t}\n\tauth := \"none\"\n\tuser, _ := metadata.InstanceAttributeValue(\"camlistore-username\")\n\tpass, _ := metadata.InstanceAttributeValue(\"camlistore-password\")\n\tconfBucket, err := metadata.InstanceAttributeValue(\"camlistore-config-dir\")\n\tif confBucket == \"\" || err != nil {\n\t\treturn nil, fmt.Errorf(\"VM instance metadata key 'camlistore-config-dir' not set: %v\", err)\n\t}\n\tblobBucket, err := metadata.InstanceAttributeValue(\"camlistore-blob-dir\")\n\tif blobBucket == \"\" || err != nil {\n\t\treturn nil, fmt.Errorf(\"VM instance metadata key 'camlistore-blob-dir' not set: %v\", err)\n\t}\n\tif user != \"\" && pass != \"\" {\n\t\tauth = \"userpass:\" + user + \":\" + pass\n\t}\n\n\tif v := osutil.SecretRingFile(); !strings.HasPrefix(v, \"/gcs/\") {\n\t\treturn nil, fmt.Errorf(\"Internal error: secret ring path on GCE should be at /gcs/, not %q\", v)\n\t}\n\tkeyID, secRing, err := getOrMakeKeyring()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thighConf := &serverconfig.Config{\n\t\tAuth: auth,\n\t\tHTTPS: true,\n\t\tIdentity: keyID,\n\t\tIdentitySecretRing: secRing,\n\t\tGoogleCloudStorage: \":\" + strings.TrimPrefix(blobBucket, \"gs://\"),\n\t\tPackRelated: true,\n\t\tShareHandler: true,\n\t}\n\n\texternalIP, _ := metadata.ExternalIP()\n\thostName, _ := metadata.InstanceAttributeValue(\"camlistore-hostname\")\n\t// If they specified a hostname (probably with pk-deploy), then:\n\t// if it looks like an FQDN, perkeepd is going to rely on Let's\n\t// Encrypt, else perkeepd is going to generate some self-signed for that\n\t// hostname.\n\t// Also, if the hostname is in camlistore.net, we want Perkeep to initialize\n\t// exactly as if the instance had no hostname, so that it registers its hostname/IP\n\t// with the camlistore.net DNS server (possibly needlessly, if the instance IP has\n\t// not changed) again.\n\tif hostName != \"\" && !strings.HasSuffix(hostName, CamliNetDomain) {\n\t\thighConf.BaseURL = fmt.Sprintf(\"https://%s\", hostName)\n\t\thighConf.Listen = \"0.0.0.0:443\"\n\t} else {\n\t\thighConf.CamliNetIP = externalIP\n\t}\n\n\t// Detect a linked Docker MySQL container. It must have alias \"mysqldb\".\n\tmysqlPort := os.Getenv(\"MYSQLDB_PORT\")\n\tif !strings.HasPrefix(mysqlPort, \"tcp://\") {\n\t\t// No MySQL\n\t\t// TODO: also detect Cloud SQL.\n\t\thighConf.KVFile = \"/index.kv\"\n\t\treturn genLowLevelConfig(highConf)\n\t}\n\thostPort := strings.TrimPrefix(mysqlPort, \"tcp://\")\n\thighConf.MySQL = \"root@\" + hostPort + \":\" // no password\n\tconfigVersion, err := metadata.InstanceAttributeValue(\"perkeep-config-version\")\n\tif configVersion == \"\" || err != nil {\n\t\t// the launcher is deploying a pre-\"perkeep-config-version\" Perkeep, which means\n\t\t// we want the old configuration, with DBNames\n\t\thighConf.DBUnique = useDBNamesConfig\n\t} else if configVersion != \"1\" {\n\t\treturn nil, fmt.Errorf(\"unexpected value for VM instance metadata key 'perkeep-config-version': %q\", configVersion)\n\t}\n\n\tconf, err := genLowLevelConfig(highConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := conf.readFields(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn conf, nil\n}", "func NewDefaultConfig(host string) Config {\n\treturn Config{GraylogPort: 12201, MaxChunkSize: 8154, GraylogHostname: host}\n}", "func CreateDefaultTree() *binaryTree {\n\tfour := node{4, nil, nil}\n\tfive := node{5, nil, nil}\n\tsix := node{6, nil, nil}\n\tseven := node{7, nil, nil}\n\n\ttwo := node{2, &four, &five}\n\tthree := node{3, &six, &seven}\n\n\tone := node{1, &two, &three}\n\treturn &binaryTree{root: &one}\n}", "func (upvc *UnsavedPostVideoCreate) defaults() {\n\tif _, ok := upvc.mutation.Validity(); !ok {\n\t\tv := unsavedpostvideo.DefaultValidity\n\t\tupvc.mutation.SetValidity(v)\n\t}\n\tif _, ok := upvc.mutation.CreatedAt(); !ok {\n\t\tv := unsavedpostvideo.DefaultCreatedAt()\n\t\tupvc.mutation.SetCreatedAt(v)\n\t}\n}", "func createNewNode(ctx context.Context, nodeName string, virtual bool, clientset kubernetes.Interface) (*corev1.Node, error) {\n\tresources := corev1.ResourceList{}\n\tresources[corev1.ResourceCPU] = *resource.NewScaledQuantity(5000, resource.Milli)\n\tresources[corev1.ResourceMemory] = *resource.NewScaledQuantity(5, resource.Mega)\n\tnode := &corev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: nodeName,\n\t\t},\n\t}\n\tif virtual {\n\t\tnode.Labels = map[string]string{\n\t\t\tconsts.TypeLabel: consts.TypeNode,\n\t\t}\n\t}\n\tnode.Status = corev1.NodeStatus{\n\t\tCapacity: resources,\n\t\tAllocatable: resources,\n\t\tConditions: []corev1.NodeCondition{\n\t\t\t0: {\n\t\t\t\tType: corev1.NodeReady,\n\t\t\t\tStatus: corev1.ConditionTrue,\n\t\t\t},\n\t\t},\n\t}\n\tnode, err := clientset.CoreV1().Nodes().Create(ctx, node, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn node, nil\n}", "func testNewConfigWithDefaults(in *Config) *Config {\n\tcfg := NewConfig()\n\tcfg.Name = in.Name\n\tcfg.ClusterName = in.ClusterName\n\tcfg.InitialCluster = in.InitialCluster\n\tcfg.InitialClusterToken = in.InitialClusterToken\n\tcfg.Dir = in.Dir\n\tcfg.PeerAutoTLS = in.PeerAutoTLS\n\tcfg.PeerTLSInfo = in.PeerTLSInfo\n\tcfg.LPUrls = in.LPUrls\n\tcfg.APUrls = in.APUrls\n\tcfg.ClientAutoTLS = in.ClientAutoTLS\n\tcfg.ClientTLSInfo = in.ClientTLSInfo\n\tcfg.LCUrls = in.LCUrls\n\tcfg.ACUrls = in.ACUrls\n\tcfg.Metrics = in.Metrics\n\tcfg.ListenMetricsUrls = in.ListenMetricsUrls\n\tcfg.ClusterState = in.ClusterState\n\treturn cfg\n}", "func NewMultipleNodeWithDefaults() *MultipleNode {\n\tthis := MultipleNode{}\n\treturn &this\n}", "func (directLinkProvider *DirectLinkProviderV2) SetDefaultHeaders(headers http.Header) {\n\tdirectLinkProvider.Service.SetDefaultHeaders(headers)\n}", "func NewAddRemoteRDSNodeOK() *AddRemoteRDSNodeOK {\n\treturn &AddRemoteRDSNodeOK{}\n}", "func NewReplaceServerDefault(code int) *ReplaceServerDefault {\n\treturn &ReplaceServerDefault{\n\t\t_statusCode: code,\n\t\tConfigurationVersion: 0,\n\t}\n}", "func NewDefault() *Config {\n\tvv := defaultConfig\n\treturn &vv\n}", "func NewDefault() *Config {\n\tvv := defaultConfig\n\treturn &vv\n}", "func (epc *EntryPointCreate) defaults() {\n\tif _, ok := epc.mutation.CreateTime(); !ok {\n\t\tv := entrypoint.DefaultCreateTime()\n\t\tepc.mutation.SetCreateTime(v)\n\t}\n\tif _, ok := epc.mutation.UpdateTime(); !ok {\n\t\tv := entrypoint.DefaultUpdateTime()\n\t\tepc.mutation.SetUpdateTime(v)\n\t}\n}", "func IowrDefault() IowrStruct {\n\treturn IowrStruct{\n\n\t\t// default to os.Stdout\n\t\tTrace: os.Stdout,\n\t\tDebug: os.Stdout,\n\t\tInfo: os.Stdout,\n\t\tNotice: os.Stdout,\n\t\tWarning: os.Stdout,\n\t\tAlert: os.Stdout,\n\n\t\t// default to os.Stderr\n\t\tError: os.Stderr,\n\t\tCritical: os.Stderr,\n\t\tEmergency: os.Stderr,\n\t}\n}", "func AddDefaultData(td *models.TemplateData, r *http.Request) *models.TemplateData {\n\ttd.Flash = app.Session.PopString(r.Context(), \"flash\")\n\ttd.Error = app.Session.PopString(r.Context(), \"error\")\n\ttd.Warning = app.Session.PopString(r.Context(), \"warning\")\n\ttd.CSRFToken = nosurf.Token(r)\n\tif app.Session.Exists(r.Context(), \"user_id\") {\n\t\ttd.IsAuthenticated = 1\n\t}\n\treturn td\n}", "func newDefaultHTTPClient() (cev2.Client, error) {\n\tp, err := cev2.NewHTTP()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cev2.NewClientObserved(p,\n\t\tcev2.WithUUIDs(),\n\t\tcev2.WithTimeNow(),\n\t\tcev2.WithTracePropagation,\n\t)\n}" ]
[ "0.5712152", "0.5362989", "0.5276561", "0.5187505", "0.5171736", "0.50459373", "0.49836302", "0.4941398", "0.4921797", "0.49036473", "0.48980224", "0.48975933", "0.48868924", "0.48832646", "0.48829064", "0.4865941", "0.4848242", "0.4837145", "0.48303595", "0.48179057", "0.48087785", "0.48048887", "0.4766716", "0.4765584", "0.47522396", "0.47488528", "0.47408733", "0.47249132", "0.47070026", "0.47027206", "0.47002977", "0.46976128", "0.46908396", "0.46906242", "0.46875277", "0.46820593", "0.46762827", "0.4671231", "0.4671007", "0.4669632", "0.46650025", "0.46367604", "0.4633063", "0.46267912", "0.46239394", "0.4619414", "0.46167624", "0.46057656", "0.46035358", "0.46031862", "0.46006218", "0.45933536", "0.4587161", "0.45746982", "0.45706865", "0.4564933", "0.4559052", "0.45577615", "0.45568696", "0.4551898", "0.45509204", "0.45481846", "0.4547927", "0.45381296", "0.45362914", "0.45355445", "0.4534381", "0.45327765", "0.45309877", "0.45299998", "0.45292133", "0.45277938", "0.45276752", "0.45215413", "0.45175177", "0.45134202", "0.45118234", "0.45010626", "0.44995633", "0.44917217", "0.4490179", "0.4486709", "0.44846693", "0.44797018", "0.44767892", "0.44744003", "0.44724628", "0.44647816", "0.44600844", "0.44591868", "0.4457127", "0.44560057", "0.4450538", "0.44495597", "0.44486862", "0.44486862", "0.4446487", "0.4445621", "0.44435883", "0.44425017" ]
0.7135118
0
Code gets the status code for the add remote RDS node default response
func (o *AddRemoteRDSNodeDefault) Code() int { return o._statusCode }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *AddClusterV5Default) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateAntivirusServerDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateServerSwitchingRuleDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *ReplaceServerDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PortsetCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *AddExternalDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *AddAPIDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *RegisterBareMetalHostDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateNdmpUserDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetNodesDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostDomainServiceNameGlueRecordHostUpdateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostClustersMulticlusterConfigDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *SecurityKeyManagerKeyServersCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateAddonV2Default) Code() int {\n\treturn o._statusCode\n}", "func (o *GetHostdbActiveDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostGatewayConnectNetaddressDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetNodeUpgradesDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *UpdateAntivirusServerDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *AddQANPostgreSQLPgStatementsAgentDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostHyperflexHxdpVersionsMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostNodesIdentifierObmIdentifyDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *AddServerGroupNotFound) Code() int {\n\treturn 404\n}", "func (o *PutExtensionsUUIDDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *ClusterProxyDeregisterV1Default) Code() int {\n\treturn o._statusCode\n}", "func (o *DescribeServerOK) Code() int {\n\treturn 200\n}", "func (o *DescribeDNSServerOK) Code() int {\n\treturn 200\n}", "func (o *AddPMMAgentDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *ReinstallMachineDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *NvmeSubsystemMapCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostHostsListDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *NodesGetDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *AddTokenToServiceAccountDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *SvmPeerModifyDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateTagDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetEtherPhysicalPortsDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *LdapSchemaCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateSettingsReportingEulaItemDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *SecurityLogForwardingCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PutNetworksNetworkIDNameDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostNodesIdentifierWorkflowsDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *UpdateHostGroupsDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *UpdateAgentDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *WebModifyDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateClusterFirmwareUpgradeItemDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostHostAnnounceDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostApplianceUpgradesMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *SMSInboundAutomationPostDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *EmsConfigModifyDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetModelRegistryDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateSecurityListDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostThermalSimulationDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *DescribeServerNotFound) Code() int {\n\treturn 404\n}", "func (o *PostClustersUUIDCertificatesPemkeyDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *SnapmirrorRelationshipModifyDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *ModifyClusterAppConfigV5Default) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateAccountDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *ReplaceTCPResponseRuleDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetAvailabilityZonesUUIDDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PutLTENetworkIDGatewaysGatewayIDMagmadDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostHclCompatibilityStatusesDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *EmsDestinationModifyDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *V2CreatePoolTemplateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostRestapiV10NumberPoolReserveDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostInventoryGenericInventoryHoldersMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostHyperflexClusterProfilesMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetLTENetworkIDGatewaysGatewayIDCellularEpcDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *UsersPostDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostWalletSiafundsDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetAvailableExtensionsUUIDDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *UnixUserSettingsModifyDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetDatasourceByIDDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *RechargeCreditCardPutDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *UpdateDeviceTagsDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *DeleteCrossConnectDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostPciLinksMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetHyperflexServerFirmwareVersionsDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateLocationDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetSSHPortalConnectionsIDDefault) Code() int {\n\treturn o._statusCode\n}", "func (abcr AppendBlobsCreateResponse) StatusCode() int {\n\treturn abcr.rawResponse.StatusCode\n}", "func (o *GetNetworksNetworkIDFeaturesDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *DescribeDNSServerNotFound) Code() int {\n\treturn 404\n}", "func (o *GetNetworksNetworkIDDescriptionDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *UpdateEnvVarDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *SMSInboundReadPutDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *NumbersBuyByDedicatedNumberPostDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetClusterByIDDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PatchMachineConfigurationDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *NodesGetRelationsDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostGatewayDisconnectNetaddressDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PutLTENetworkIDGatewaysGatewayIDCellularPoolingDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PutLTENetworkIDGatewaysGatewayIDCellularRanDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostSimulationActivityDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *ExtrasImageAttachmentsCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PostEquipmentIoExpandersMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *CreateFnDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *AddServerGroupNoContent) Code() int {\n\treturn 204\n}", "func (o *SnapshotCreateDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *IngestFromURIDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *PatchRoleDefault) Code() int {\n\treturn o._statusCode\n}", "func (o *GetServerConfigImportsMoidDefault) Code() int {\n\treturn o._statusCode\n}" ]
[ "0.692362", "0.6842809", "0.6776764", "0.6746196", "0.67214376", "0.6714648", "0.67118406", "0.6705345", "0.6704429", "0.6689789", "0.66794825", "0.6672727", "0.663601", "0.66230243", "0.6620177", "0.6610653", "0.6598204", "0.65737337", "0.6566433", "0.65617335", "0.65522105", "0.65337133", "0.6533502", "0.6526411", "0.65110385", "0.6485838", "0.64788795", "0.6476248", "0.6474675", "0.6466354", "0.6460993", "0.64582676", "0.64526063", "0.6449143", "0.64365065", "0.64068794", "0.64057624", "0.64040947", "0.64039236", "0.639291", "0.63675606", "0.6360546", "0.6357318", "0.6352176", "0.6338281", "0.63323116", "0.6321739", "0.6318422", "0.63174504", "0.6313728", "0.63044673", "0.62906414", "0.6287964", "0.6281444", "0.62715584", "0.6266002", "0.6265597", "0.62648666", "0.6261415", "0.6260031", "0.62586904", "0.6255622", "0.62555224", "0.6255279", "0.6254191", "0.62511796", "0.62511617", "0.6245975", "0.62399673", "0.62348616", "0.6233878", "0.62301767", "0.62278634", "0.6214011", "0.6205099", "0.6204631", "0.62024784", "0.6197", "0.61941373", "0.61923885", "0.61904794", "0.6187698", "0.61846817", "0.6182017", "0.61775905", "0.61741835", "0.6168687", "0.61680293", "0.6163619", "0.616171", "0.61585563", "0.6157054", "0.61528766", "0.6152535", "0.615251", "0.61502194", "0.6149784", "0.61486655", "0.6147146", "0.6139123" ]
0.80228853
0
Validate validates this add remote RDS node body
func (o *AddRemoteRDSNodeBody) Validate(formats strfmt.Registry) error { return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *AddRemoteRDSNodeOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateRemoteRDS(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *AddRemoteRDSNodeOKBodyRemoteRDS) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *AddRemoteRDSNodeDefaultBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateDetails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *AddQANPostgreSQLPgStatementsAgentBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *AddExternalBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *AddPMMAgentBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (body *AddRequestBody) Validate() (err error) {\n\tif body.Token == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"token\", \"body\"))\n\t}\n\treturn\n}", "func (g *GuidePost) validateNodeConfig(q *msg.Request) (bool, error) {\n\tif q.Node.Config == nil {\n\t\treturn false, fmt.Errorf(\"NodeConfig subobject missing\")\n\t}\n\treturn g.validateBucketInRepository(\n\t\tq.Node.Config.RepositoryID,\n\t\tq.Node.Config.BucketID,\n\t)\n}", "func (m *Node) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif !_Node_Host_Pattern.MatchString(m.GetHost()) {\n\t\treturn NodeValidationError{\n\t\t\tfield: \"Host\",\n\t\t\treason: \"value does not match regex pattern \\\"^\\\\\\\\*?[0-9a-zA-Z-._]+$\\\"\",\n\t\t}\n\t}\n\n\tif val := m.GetPort(); val < 1 || val > 65535 {\n\t\treturn NodeValidationError{\n\t\t\tfield: \"Port\",\n\t\t\treason: \"value must be inside range [1, 65535]\",\n\t\t}\n\t}\n\n\tif m.GetWeight() < 0 {\n\t\treturn NodeValidationError{\n\t\t\tfield: \"Weight\",\n\t\t\treason: \"value must be greater than or equal to 0\",\n\t\t}\n\t}\n\n\tfor key, val := range m.GetMetadata() {\n\t\t_ = val\n\n\t\t// no validation rules for Metadata[key]\n\n\t\tif v, ok := interface{}(val).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn NodeValidationError{\n\t\t\t\t\tfield: fmt.Sprintf(\"Metadata[%v]\", key),\n\t\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\t\tcause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func ValidateNewPostRequestBody(body *NewPostRequestBody) (err error) {\n\tif body.Body == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"body\", \"body\"))\n\t}\n\treturn\n}", "func ValidateAddRequestBody(body *AddRequestBody) (err error) {\n\tif body.Step != nil {\n\t\tif err2 := ValidateStepRequestBody(body.Step); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func ValidateAddRequestBody(body *AddRequestBody) (err error) {\n\tif body.Resource == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"resource\", \"body\"))\n\t}\n\tif body.Action == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"action\", \"body\"))\n\t}\n\treturn\n}", "func (nS *PostMessageBody) Validate() error {\n\treturn validator.New().Struct(nS)\n}", "func (o *VolumeCreateBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateNode(member serf.Member) (ok bool, role, dc string) {\n\tif _, ok = member.Tags[\"id\"]; !ok {\n\t\treturn false, \"\", \"\"\n\t}\n\n\t// Get role name\n\tif role, ok = member.Tags[\"role\"]; !ok {\n\t\treturn false, \"\", \"\"\n\t} else if role != CerebrumRole {\n\t\treturn false, \"\", \"\"\n\t}\n\n\t// Get datacenter name\n\tif dc, ok = member.Tags[\"dc\"]; ok {\n\t\treturn true, role, dc\n\t}\n\treturn false, \"\", \"\"\n}", "func (r *NodeDeployment) ValidateCreate() error {\n\tnodedeploymentlog.Info(\"validate create\", \"name\", r.Name)\n\n\t// TODO(user): fill in your validation logic upon object creation.\n\treturn nil\n}", "func (o *Virtualserver) validate(dbRecord *common.DbRecord) (ok bool, err error) {\n\t////////////////////////////////////////////////////////////////////////////\n\t// Marshal data interface.\n\t////////////////////////////////////////////////////////////////////////////\n\tvar data virtualserver.Data\n\terr = shared.MarshalInterface(dbRecord.Data, &data)\n\tif err != nil {\n\t\treturn\n\t}\n\t////////////////////////////////////////////////////////////////////////////\n\t// Test required fields.\n\t////////////////////////////////////////////////////////////////////////////\n\tok = true\n\trequired := make(map[string]bool)\n\trequired[\"ProductCode\"] = false\n\trequired[\"IP\"] = false\n\trequired[\"Port\"] = false\n\trequired[\"LoadBalancerIP\"] = false\n\trequired[\"Name\"] = false\n\t////////////////////////////////////////////////////////////////////////////\n\tif data.ProductCode != 0 {\n\t\trequired[\"ProductCode\"] = true\n\t}\n\tif len(dbRecord.LoadBalancerIP) > 0 {\n\t\trequired[\"LoadBalancerIP\"] = true\n\t}\n\tif len(data.Ports) != 0 {\n\t\trequired[\"Port\"] = true\n\t}\n\tif data.IP != \"\" {\n\t\trequired[\"IP\"] = true\n\t}\n\tif data.Name != \"\" {\n\t\trequired[\"Name\"] = true\n\t}\n\tfor _, val := range required {\n\t\tif val == false {\n\t\t\tok = false\n\t\t}\n\t}\n\tif !ok {\n\t\terr = fmt.Errorf(\"missing required fields - %+v\", required)\n\t}\n\treturn\n}", "func (payload *addListenPayload) Validate() (err error) {\n\tif payload.Etype == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\tif payload.Hookurl != nil {\n\t\tif ok := goa.ValidatePattern(`^https?://((\\w)+.?)+/(\\w+)$`, *payload.Hookurl); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`raw.hookurl`, *payload.Hookurl, `^https?://((\\w)+.?)+/(\\w+)$`))\n\t\t}\n\t}\n\treturn\n}", "func AddServer(data map[string]string)(err error) {\n uuid := data[\"uuid\"]\n err = ndb.GetTokenByUuid(uuid); if err!=nil{logs.Error(\"Error loading node token: %s\",err); return err}\n ipuuid,portuuid,err := ndb.ObtainPortIp(uuid)\n if err != nil {\n logs.Error(\"AddServer ERROR Obtaining Port and IP for Add a new server into STAP: \"+err.Error())\n return err\n }\n err = nodeclient.AddServer(ipuuid,portuuid, data)\n if err != nil {\n logs.Error(\"node/AddServer ERROR http data request: \"+err.Error())\n return err\n }\n return nil\n}", "func (o *PostSiteCreatedBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (c *Client) Add(ctx context.Context, node NodeInfo) error {\n\trequest := protocol.Message{}\n\tresponse := protocol.Message{}\n\n\trequest.Init(4096)\n\tresponse.Init(4096)\n\n\tprotocol.EncodeAdd(&request, node.ID, node.Address)\n\n\tif err := c.protocol.Call(ctx, &request, &response); err != nil {\n\t\treturn err\n\t}\n\n\tif err := protocol.DecodeEmpty(&response); err != nil {\n\t\treturn err\n\t}\n\n\t// If the desired role is spare, there's nothing to do, since all newly\n\t// added nodes have the spare role.\n\tif node.Role == Spare {\n\t\treturn nil\n\t}\n\n\treturn c.Assign(ctx, node.ID, node.Role)\n}", "func (o *PostLeasesIDAuthCreatedBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (payload *AddListenPayload) Validate() (err error) {\n\tif payload.Etype == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\tif ok := goa.ValidatePattern(`^https?://((\\w)+.?)+/(\\w+)$`, payload.Hookurl); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`raw.hookurl`, payload.Hookurl, `^https?://((\\w)+.?)+/(\\w+)$`))\n\t}\n\treturn\n}", "func (o *PostSiteCreatedBodyData) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateRoutes(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *PostIPAMIpsOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (body *CreateResponseBody) Validate() (err error) {\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Color == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"color\", \"body\"))\n\t}\n\tif body.Cron == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"cron\", \"body\"))\n\t}\n\tif body.Name != nil {\n\t\tif utf8.RuneCountInString(*body.Name) > 100 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(\"body.name\", *body.Name, utf8.RuneCountInString(*body.Name), 100, false))\n\t\t}\n\t}\n\tif body.Color != nil {\n\t\tif !(*body.Color == \"red\" || *body.Color == \"yellow\" || *body.Color == \"green\" || *body.Color == \"off\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"body.color\", *body.Color, []interface{}{\"red\", \"yellow\", \"green\", \"off\"}))\n\t\t}\n\t}\n\treturn\n}", "func (s SubnetArgs) validate() error {\n\tif s.isEmpty() {\n\t\treturn nil\n\t}\n\treturn s.FromTags.validate()\n}", "func (o *SyncCopyBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func validatePOSTRequest(body []byte, schema *gojsonschema.Schema) (err error) {\n\tdocLoader := gojsonschema.NewStringLoader(string(body))\n\tif result, err := schema.Validate(docLoader); err != nil && !result.Valid() {\n\t\treturn errors.New(\"Couldn't validate json\")\n\t}\n\treturn nil\n}", "func addNode(address, username, password, name, bundle string, approve bool) (string, error) {\n\tvar ret string\n\n\t// Build the request body.\n\tenrolBody := types.NodeEnrollmentBody{\n\t\tAddress: address,\n\t\tName: name,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tAutoApprove: !approve, // user specifies if they dont want it\n\t\tCallHome: false,\n\t}\n\tif bundle != \"\" {\n\t\tenrolBody.Bundle = bundle\n\t\tenrolBody.Hostname = name\n\t\tenrolBody.CallHome = true\n\t}\n\trequest := types.EnrollmentRequest{\n\t\tEnrollment: enrolBody,\n\t}\n\treqJSON, err := json.Marshal(&request)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\turl, err := client.GetURL(nodeURI)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\treq, err := client.BuildReq(&reqJSON, url, http.MethodPost, true)\n\trawResp, err := client.HTTPClient().Do(req)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\t_, err = client.ParseReq(rawResp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\treturn \"Node added successfully\\n\", nil\n}", "func (payload *CreateMessagePayload) Validate() (err error) {\n\n\tif payload.Text == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"text\"))\n\t}\n\treturn\n}", "func (o *RepoMigrateCreatedBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateCloneURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateDefaultBranch(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateDescription(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateEmpty(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateFork(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateForks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateFullName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateHTMLURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateMirror(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateOpenIssues(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePrivate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSSHURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSize(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateStars(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateUpdated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateWatchers(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateWebsite(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateOwner(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateParent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePermissions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func validateRpc(node *Node, reqId []byte) error {\n\tif !bytes.Equal(node.Id, reqId) {\n\t\terrStr := fmt.Sprintf(\"Node ids do not match %v, %v\", node.Id, reqId)\n\t\treturn errors.New(errStr)\n\t}\n\treturn nil\n}", "func (o *PostIPAMIpnatOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *PostSiteBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (payload *CreateItemPayload) Validate() (err error) {\n\tif payload.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"name\"))\n\t}\n\tif payload.Description == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"description\"))\n\t}\n\n\tif payload.Image1 == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"image1\"))\n\t}\n\treturn\n}", "func ValidateStoredStepRequestBody(body *StoredStepRequestBody) (err error) {\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Title == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"title\", \"body\"))\n\t}\n\tif body.Target == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"target\", \"body\"))\n\t}\n\tif body.StepNumber == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"stepNumber\", \"body\"))\n\t}\n\tif body.Content == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"content\", \"body\"))\n\t}\n\tif body.Placement == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"placement\", \"body\"))\n\t}\n\tif body.Action == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"action\", \"body\"))\n\t}\n\tif body.Placement != nil {\n\t\tif !(*body.Placement == \"left\" || *body.Placement == \"right\" || *body.Placement == \"top\" || *body.Placement == \"buttom\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"body.placement\", *body.Placement, []interface{}{\"left\", \"right\", \"top\", \"buttom\"}))\n\t\t}\n\t}\n\tif body.Action != nil {\n\t\tif !(*body.Action == \"click\" || *body.Action == \"next\" || *body.Action == \"end\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"body.action\", *body.Action, []interface{}{\"click\", \"next\", \"end\"}))\n\t\t}\n\t}\n\treturn\n}", "func (o *CreateShortLinkBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (p Peer) Validate() error {\n\treturn validation.ValidateStruct(\n\t\t&p,\n\t\tvalidation.Field(&p.NodeID, validation.Required),\n\t\tvalidation.Field(&p.Address, validation.Required, is.Host),\n\t)\n}", "func validateNodeStageVolumeRequest(req *csi.NodeStageVolumeRequest) error {\n\tif req.GetVolumeCapability() == nil {\n\t\treturn errors.New(\"volume capability missing in request\")\n\t}\n\n\tif req.GetVolumeId() == \"\" {\n\t\treturn errors.New(\"volume ID missing in request\")\n\t}\n\n\tif req.GetVolumeContext() == nil || len(req.GetVolumeContext()) == 0 {\n\t\treturn errors.New(\"volume context cannot be nil or empty\")\n\t}\n\n\tif req.GetSecrets() == nil || len(req.GetSecrets()) == 0 {\n\t\treturn errors.New(\"stage secrets cannot be nil or empty\")\n\t}\n\n\treturn nil\n}", "func (n *Node) validateComplete() error {\n\tif n.Incomplete() {\n\t\treturn errors.New(\"incomplete node\")\n\t}\n\tif n.UDP == 0 {\n\t\treturn errors.New(\"missing UDP port\")\n\t}\n\tif n.TCP == 0 {\n\t\treturn errors.New(\"missing TCP port\")\n\t}\n\tif n.IP.IsMulticast() || n.IP.IsUnspecified() {\n\t\treturn errors.New(\"invalid IP (multicast/unspecified)\")\n\t}\n\t_, err := n.ID.Pubkey() // validate the key (on curve, etc.)\n\treturn err\n}", "func (payload *createItemPayload) Validate() (err error) {\n\tif payload.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"name\"))\n\t}\n\tif payload.Description == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"description\"))\n\t}\n\tif payload.Price == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"price\"))\n\t}\n\tif payload.Compensation == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"compensation\"))\n\t}\n\tif payload.CategoryID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"category_id\"))\n\t}\n\tif payload.PlaceID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"place_id\"))\n\t}\n\tif payload.Image1 == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"image1\"))\n\t}\n\treturn\n}", "func ValidateAdminCreateNewUserRequestBody(body *AdminCreateNewUserRequestBody) (err error) {\n\tif body.UserName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"user_name\", \"body\"))\n\t}\n\tif body.EmailAddress == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"email_address\", \"body\"))\n\t}\n\tif body.PhoneNumber == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"phone_number\", \"body\"))\n\t}\n\tif body.PhotoURL == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"photo_url\", \"body\"))\n\t}\n\tif body.UserName != nil {\n\t\tif utf8.RuneCountInString(*body.UserName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(\"body.user_name\", *body.UserName, utf8.RuneCountInString(*body.UserName), 1, true))\n\t\t}\n\t}\n\tif body.UserName != nil {\n\t\tif utf8.RuneCountInString(*body.UserName) > 20 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(\"body.user_name\", *body.UserName, utf8.RuneCountInString(*body.UserName), 20, false))\n\t\t}\n\t}\n\tif body.EmailAddress != nil {\n\t\terr = goa.MergeErrors(err, goa.ValidateFormat(\"body.email_address\", *body.EmailAddress, goa.FormatEmail))\n\t}\n\tif body.PhoneNumber != nil {\n\t\terr = goa.MergeErrors(err, goa.ValidatePattern(\"body.phone_number\", *body.PhoneNumber, \"^\\\\+?[\\\\d]{10,}$\"))\n\t}\n\treturn\n}", "func validateNodeStageVolumeRequest(req *csi.NodeStageVolumeRequest) error {\n\tif req.GetVolumeCapability() == nil {\n\t\treturn fmt.Errorf(\"volume capability missing in request\")\n\t}\n\n\tif req.GetVolumeId() == \"\" {\n\t\treturn fmt.Errorf(\"volume ID missing in request\")\n\t}\n\n\tif req.GetStagingTargetPath() == \"\" {\n\t\treturn fmt.Errorf(\"staging target path missing in request\")\n\t}\n\n\tif req.GetNodeStageSecrets() == nil || len(req.GetNodeStageSecrets()) == 0 {\n\t\treturn fmt.Errorf(\"stage secrets cannot be nil or empty\")\n\t}\n\n\treturn nil\n}", "func (n *Nodes) validateComplete() error {\n\tif n.Incomplete() {\n\t\treturn errors.New(\"incomplete Nodes\")\n\t}\n\tif n.UDP == 0 {\n\t\treturn errors.New(\"missing UDP port\")\n\t}\n\tif n.TCP == 0 {\n\t\treturn errors.New(\"missing TCP port\")\n\t}\n\tif n.IP.IsMulticast() || n.IP.IsUnspecified() {\n\t\treturn errors.New(\"invalid IP (multicast/unspecified)\")\n\t}\n\t_, err := n.ID.Pubkey() // validate the key (on curve, etcPtr.)\n\treturn err\n}", "func (ut *addUserPayload) Validate() (err error) {\n\tif ut.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"name\"))\n\t}\n\tif ut.Email == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"email\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`request.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif ok := goa.ValidatePattern(`\\S`, *ut.Name); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`request.name`, *ut.Name, `\\S`))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 256 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 256, false))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 10 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 10, true))\n\t\t}\n\t}\n\treturn\n}", "func (p PingreqPacket) Validate() error { return nil }", "func (th *treeHead) validate(mac hash.Hash) error {\n\ttag, err := th.expectedTag(mac)\n\tif err != nil {\n\t\treturn err\n\t} else if !hmac.Equal(tag, th.Tag) {\n\t\treturn fmt.Errorf(\"integrity: failed to validate tree head\")\n\t}\n\treturn nil\n}", "func (payload *createMessagePayload) Validate() (err error) {\n\tif payload.OfferID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"offer_id\"))\n\t}\n\tif payload.Text == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"text\"))\n\t}\n\treturn\n}", "func (o *ServiceCreateCreatedBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *StoragepoolNodepool) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *PostSiteGatewayTimeoutBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *CreateWidgetBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateWidgetTemplateUUID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *DeleteDatasetCreatedBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (ctx Context) AddNode(count int, hardwareprofile, softwareprofile string) (AddNodeResult, error) {\n\tvar result AddNodeResult\n\n\t// we trust the signature\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\taddInput := AddNodeInput{inner{count, hardwareprofile, softwareprofile}}\n\tinput, errMarshal := json.Marshal(addInput)\n\tif errMarshal != nil {\n\t\treturn result, errMarshal\n\t}\n\turl := fmt.Sprintf(\"https://%s:8443/v1/nodes\", ctx.Address)\n\treq, errRequest := http.NewRequest(\"POST\", url, bytes.NewBuffer(input))\n\tif errRequest != nil {\n\t\treturn result, errRequest\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.SetBasicAuth(ctx.User, ctx.Password)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer resp.Body.Close()\n\n\tdecoder := json.NewDecoder(resp.Body)\n\tif err := decoder.Decode(&result); err != nil {\n\t\treturn result, err\n\t}\n\treturn result, nil\n}", "func (o *PostDeviceURLOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *CiNode) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAvailable(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLastLeaseTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVpnIP(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (ut *CreateLinkPayload) Validate() (err error) {\n\tif ut.Path == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"path\"))\n\t}\n\tif ut.URL == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"url\"))\n\t}\n\tif utf8.RuneCountInString(ut.Path) < 6 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.path`, ut.Path, utf8.RuneCountInString(ut.Path), 6, true))\n\t}\n\tif utf8.RuneCountInString(ut.Path) > 100 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.path`, ut.Path, utf8.RuneCountInString(ut.Path), 100, false))\n\t}\n\tif utf8.RuneCountInString(ut.URL) < 8 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.url`, ut.URL, utf8.RuneCountInString(ut.URL), 8, true))\n\t}\n\tif utf8.RuneCountInString(ut.URL) > 2000 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.url`, ut.URL, utf8.RuneCountInString(ut.URL), 2000, false))\n\t}\n\treturn\n}", "func (o *NewThreadBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateBaseReq(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *PostTemplateTemplateIDCopyBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateRemoveRequestBody(body *RemoveRequestBody) (err error) {\n\tif body.WtID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"wtId\", \"body\"))\n\t}\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\treturn\n}", "func (m *NodePoolUpdate) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateInstanceTypes(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (r *Node) validate() field.ErrorList {\n\tvar nodeErrors field.ErrorList\n\n\tif r.Spec.Validator {\n\t\t// validate rpc must be disabled if node is validator\n\t\tif r.Spec.RPC {\n\t\t\terr := field.Invalid(field.NewPath(\"spec\").Child(\"rpc\"), r.Spec.RPC, \"must be false if node is validator\")\n\t\t\tnodeErrors = append(nodeErrors, err)\n\t\t}\n\t\t// validate ws must be disabled if node is validator\n\t\tif r.Spec.WS {\n\t\t\terr := field.Invalid(field.NewPath(\"spec\").Child(\"ws\"), r.Spec.WS, \"must be false if node is validator\")\n\t\t\tnodeErrors = append(nodeErrors, err)\n\t\t}\n\t\t// validate pruning must be disabled if node is validator\n\t\tif pruning := r.Spec.Pruning; pruning != nil && *pruning {\n\t\t\terr := field.Invalid(field.NewPath(\"spec\").Child(\"pruning\"), r.Spec.Pruning, \"must be false if node is validator\")\n\t\t\tnodeErrors = append(nodeErrors, err)\n\t\t}\n\n\t}\n\n\treturn nodeErrors\n}", "func (payload *CreateOutputPayload) Validate() (err error) {\n\tif payload.Alias == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"alias\"))\n\t}\n\tif payload.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"name\"))\n\t}\n\treturn\n}", "func (ut *addFirmwarePayload) Validate() (err error) {\n\tif ut.Etag == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"etag\"))\n\t}\n\tif ut.Module == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"module\"))\n\t}\n\tif ut.Profile == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"profile\"))\n\t}\n\tif ut.URL == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"url\"))\n\t}\n\tif ut.Meta == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"meta\"))\n\t}\n\treturn\n}", "func (o *CreateChannelCreatedBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (ut *AddUserPayload) Validate() (err error) {\n\tif ut.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"name\"))\n\t}\n\tif ut.Email == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"email\"))\n\t}\n\tif ut.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"password\"))\n\t}\n\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\n\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\n\t}\n\tif ok := goa.ValidatePattern(`\\S`, ut.Name); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`type.name`, ut.Name, `\\S`))\n\t}\n\tif utf8.RuneCountInString(ut.Name) > 256 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.name`, ut.Name, utf8.RuneCountInString(ut.Name), 256, false))\n\t}\n\tif utf8.RuneCountInString(ut.Password) < 10 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 10, true))\n\t}\n\treturn\n}", "func (payload *postEventPayload) Validate() (err error) {\n\tif payload.Etype == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Action == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"action\"))\n\t}\n\tif payload.From == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (o *SecurityKeyManagerMigrateBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateLinks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *CreateChannelBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateConfigMeta(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePlatform(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *MerchantCreateBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFeatures(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGatewayID(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (c *CAPI) AddNode(req *btcjson.AddNodeCmd, resp None) (e error) {\n\tnrh := RPCHandlers\n\tres := nrh[\"addnode\"].Result()\n\tres.Params = req\n\tnrh[\"addnode\"].Call <- res\n\tselect {\n\tcase resp = <-res.Ch.(chan None):\n\tcase <-time.After(c.Timeout):\n\tcase <-c.quit.Wait():\n\t} \n\treturn \n}", "func validateNodeServerCSR(agent *aiv1beta1.Agent, node *corev1.Node, csr *certificatesv1.CertificateSigningRequest, x509CSR *x509.CertificateRequest) (bool, error) {\n\n\t// Username must consist from \"\"system:node:\" and the node name\n\tnodeAsking := strings.TrimPrefix(csr.Spec.Username, nodeUserPrefix)\n\tif len(nodeAsking) == 0 {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: CSR does not appear to be a node serving CSR. Empty node name after %s prefix\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tnodeUserPrefix)\n\t}\n\n\t// Check groups, we need at least:\n\t// - system:authenticated\n\tif len(csr.Spec.Groups) < 2 || !funk.ContainsString(csr.Spec.Groups, \"system:authenticated\") {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: %v is too small or not contains %q\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tcsr.Spec.Groups, \"system:authenticated\")\n\t}\n\n\tserverUsagesLegacy := []certificatesv1.KeyUsage{\n\t\tcertificatesv1.UsageDigitalSignature,\n\t\tcertificatesv1.UsageKeyEncipherment,\n\t\tcertificatesv1.UsageServerAuth,\n\t}\n\tserverUsages := []certificatesv1.KeyUsage{\n\t\tcertificatesv1.UsageDigitalSignature,\n\t\tcertificatesv1.UsageServerAuth,\n\t}\n\n\tif !hasExactUsages(csr, serverUsages) && !hasExactUsages(csr, serverUsagesLegacy) {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: No exact match between CSR %v and required usages\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tcsr.Spec.Usages)\n\t}\n\n\t// \"system:nodes\" must be one of the elements of Organization\n\tif !funk.ContainsString(x509CSR.Subject.Organization, nodeGroup) {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: Organization %v doesn't include %s\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tx509CSR.Subject.Organization, nodeGroup)\n\t}\n\n\t// CN and Username must be equal\n\tif x509CSR.Subject.CommonName != csr.Spec.Username {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: Mismatched CommonName %s != %s for CSR %s\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tx509CSR.Subject.CommonName, csr.Spec.Username, csr.Name)\n\t}\n\tnodeDNSNames := append(getNodeDNSNames(node), node.Name)\n\n\t// Any DNS name in CSR must exist in the nodeDNSNames\n\t// TODO: May need to modify for IPv6 only node\n\tfor _, dnsName := range x509CSR.DNSNames {\n\t\tif !funk.ContainsString(nodeDNSNames, dnsName) {\n\t\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: DNS name %s missing from available DNS names %v\", csr.Name, agent.Namespace, agent.Name,\n\t\t\t\tdnsName, nodeDNSNames)\n\t\t}\n\t}\n\tnodeIPs := getNodeIPs(node)\n\t// Any IP address in CSR must exist in nodeIPs\n\tfor _, ip := range x509CSR.IPAddresses {\n\t\tif !funk.ContainsString(nodeIPs, ip.String()) {\n\t\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: IP address %s missing from available node IPs %v\", csr.Name, agent.Namespace, agent.Name,\n\t\t\t\tip.String(), nodeIPs)\n\t\t}\n\t}\n\treturn true, nil\n}", "func (o *SaveBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateHash(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateKeyPair(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (payload *putEventPayload) Validate() (err error) {\n\tif payload.Etype == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Action == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"action\"))\n\t}\n\tif payload.From == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (payload *UpdateListenPayload) Validate() (err error) {\n\tif payload.Etype == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func RegisterNode(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Register Node called\")\n\tdecoder := json.NewDecoder(r.Body)\n\tvar signedNode models.SignedPeer\n\terr := decoder.Decode(&signedNode)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to decode request to register node. Incorrect format\")\n\t}\n\tvar nodeListJSON string\n\tpeerNode, ok := nodeList[signedNode.PeerNode.PeerId]\n\tif !ok {\n\t\tif(signedNode.PeerNode.VerifyPeerSignature(signedNode.SignedPeerNode)){\n\t\t\tfmt.Println(\"Signature Verified for new user. Register Successful\")\n\t\t\tnodeList[signedNode.PeerNode.PeerId] = signedNode.PeerNode\n\t\t\tnodeListJSON = nodeList.GetNodeListJSON()\n\t\t}else{\n\t\t\tnodeListJSON = \"{}\"\n\t\t}\n\t}else{\n\t\tfmt.Println(\"Peer Id already registered with this uuid.\")\n\t\tif(peerNode.VerifyPeerSignature(signedNode.SignedPeerNode)){\n\t\t\tfmt.Println(\"Verified with old public key. Updating key pair\")\n\t\t\tnodeList[signedNode.PeerNode.PeerId] = signedNode.PeerNode\n\t\t\tnodeListJSON = nodeList.GetNodeListJSON()\n\t\t}else{\n\t\t\tnodeListJSON = \"{}\"\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(nodeListJSON))\n}", "func (m *NdmpNode) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateLinks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNdmpNodeInlineAuthenticationTypes(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNode(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (payload *CreateVerificationPayload) Validate() (err error) {\n\n\treturn\n}", "func (cc *ContrailCommand) CreateNode(host vcenter.ESXIHost) error {\n\tlog.Debug(\"Create Node:\", cc.AuthToken)\n\tnodeResource := contrailCommandNodeSync{\n\t\tResources: []*nodeResources{\n\t\t\t{\n\t\t\t\tKind: \"node\",\n\t\t\t\tData: &nodeData{\n\t\t\t\t\tNodeType: \"esxi\",\n\t\t\t\t\tUUID: host.UUID,\n\t\t\t\t\tHostname: host.Hostname,\n\t\t\t\t\tFqName: []string{\"default-global-system-config\", host.Hostname},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tjsonData, err := json.Marshal(nodeResource)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Sending Request\")\n\tresp, _, err := cc.sendRequest(\"/sync\", string(jsonData), \"POST\") //nolint: bodyclose\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Got status : \", resp.StatusCode)\n\tswitch resp.StatusCode {\n\tdefault:\n\t\treturn fmt.Errorf(\"resource creation failed, %d\", resp.StatusCode)\n\tcase 200, 201:\n\t}\n\treturn nil\n}", "func (m *CatalogueNode) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNodes(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTags(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (r *CAPIClient) AddNode(cmd ...*btcjson.AddNodeCmd) (res None, e error) {\n\tvar c *btcjson.AddNodeCmd\n\tif len(cmd) > 0 {\n\t\tc = cmd[0]\n\t}\n\tif e = r.Call(\"CAPI.AddNode\", c, &res); E.Chk(e) {\n\t}\n\treturn\n}", "func (o *CreateDatasetBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateAccess(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateComp(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCompressMethod(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateEnc(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateMetadata(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateProject(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePushMethod(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func isValidLocationConstraint(reqBody io.Reader) (err error) {\n\tvar region = helper.CONFIG.Region\n\tvar locationConstraint CreateBucketLocationConfiguration\n\te := xmlDecoder(reqBody, &locationConstraint)\n\tif e != nil {\n\t\tif e == io.EOF {\n\t\t\t// Failed due to empty request body. The location will be set to\n\t\t\t// default value from the serverConfig\n\t\t\terr = nil\n\t\t} else {\n\t\t\t// Failed due to malformed configuration.\n\t\t\terr = ErrMalformedXML\n\t\t}\n\t} else {\n\t\t// Region obtained from the body.\n\t\t// It should be equal to Region in serverConfig.\n\t\t// Else ErrInvalidRegion returned.\n\t\t// For empty value location will be to set to default value from the serverConfig.\n\t\tif locationConstraint.Location != \"\" && region != locationConstraint.Location {\n\t\t\terr = ErrInvalidRegion\n\t\t}\n\t}\n\treturn err\n}", "func (payload *updateListenPayload) Validate() (err error) {\n\tif payload.Etype == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (m *Body16) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateContent(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEuid(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSourceID(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSourceType(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (payload *PutEventPayload) Validate() (err error) {\n\tif payload.Etype == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Action == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"action\"))\n\t}\n\tif payload.From == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (payload *createOutputPayload) Validate() (err error) {\n\tif payload.Alias == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"alias\"))\n\t}\n\tif payload.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"name\"))\n\t}\n\treturn\n}", "func (ut *AddFirmwarePayload) Validate() (err error) {\n\tif ut.Etag == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"etag\"))\n\t}\n\tif ut.Module == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"module\"))\n\t}\n\tif ut.Profile == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"profile\"))\n\t}\n\tif ut.URL == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"url\"))\n\t}\n\tif ut.Meta == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"meta\"))\n\t}\n\treturn\n}", "func (m *NodeHealthDetails) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateInstanceID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIssues(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *GaragesCreateBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCentreID(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLocations(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (payload *PostEventPayload) Validate() (err error) {\n\tif payload.Etype == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Action == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"action\"))\n\t}\n\tif payload.From == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (ut *createLinkPayload) Validate() (err error) {\n\tif ut.Path == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"path\"))\n\t}\n\tif ut.URL == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"url\"))\n\t}\n\tif ut.Path != nil {\n\t\tif utf8.RuneCountInString(*ut.Path) < 6 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.path`, *ut.Path, utf8.RuneCountInString(*ut.Path), 6, true))\n\t\t}\n\t}\n\tif ut.Path != nil {\n\t\tif utf8.RuneCountInString(*ut.Path) > 100 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.path`, *ut.Path, utf8.RuneCountInString(*ut.Path), 100, false))\n\t\t}\n\t}\n\tif ut.URL != nil {\n\t\tif utf8.RuneCountInString(*ut.URL) < 8 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.url`, *ut.URL, utf8.RuneCountInString(*ut.URL), 8, true))\n\t\t}\n\t}\n\tif ut.URL != nil {\n\t\tif utf8.RuneCountInString(*ut.URL) > 2000 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.url`, *ut.URL, utf8.RuneCountInString(*ut.URL), 2000, false))\n\t\t}\n\t}\n\treturn\n}", "func (ut *addFieldNotePayload) Validate() (err error) {\n\tif ut.Created == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"created\"))\n\t}\n\treturn\n}", "func (o *PostProfileBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (config *AppConfig) CreateNode(newNode NodeAttributes) (node Node, err error) {\n\tendpoint := fmt.Sprintf(\"nodes/\")\n\n\tnewNodeBytes, err := json.Marshal(newNode)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// get json bytes from the panel.\n\tnodeBytes, err := config.queryApplicationAPI(endpoint, \"post\", newNodeBytes)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Get server info from the panel\n\t// Unmarshal the bytes to a usable struct.\n\terr = json.Unmarshal(nodeBytes, &node)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (o *PostSiteNotFoundBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (r *Node) ValidateUpdate(old runtime.Object) error {\n\tvar allErrors field.ErrorList\n\toldNode := old.(*Node)\n\n\tnodelog.Info(\"validate update\", \"name\", r.Name)\n\n\tallErrors = append(allErrors, r.validate()...)\n\n\tif r.Spec.Network != oldNode.Spec.Network {\n\t\terr := field.Invalid(field.NewPath(\"spec\").Child(\"network\"), r.Spec.Network, \"field is immutable\")\n\t\tallErrors = append(allErrors, err)\n\t}\n\n\tif len(allErrors) == 0 {\n\t\treturn nil\n\t}\n\n\treturn apierrors.NewInvalid(schema.GroupKind{}, r.Name, allErrors)\n}", "func (n *NetworkBuilder) AddNode(nodeID string, subnet string, port uint, forceHidden bool) (*NetworkBuilder, error) {\n\tn.NodeID = nodeID\n\n\tif subnet == \"\" {\n\t\treturn n, fmt.Errorf(\"subnet cannot be empty\")\n\t}\n\tipnet, err := types.ParseIPNet(subnet)\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"invalid subnet\")\n\t}\n\n\tif port == 0 {\n\t\tport, err = n.pickPort()\n\t\tif err != nil {\n\t\t\treturn n, errors.Wrap(err, \"failed to pick wireguard port\")\n\t\t}\n\t}\n\n\tprivateKey, err := wgtypes.GeneratePrivateKey()\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"error during wireguard key generation\")\n\t}\n\tsk := privateKey.String()\n\n\tpk, err := crypto.KeyFromID(pkg.StrIdentifier(nodeID))\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"failed to parse nodeID\")\n\t}\n\n\tencrypted, err := crypto.Encrypt([]byte(sk), pk)\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"failed to encrypt private key\")\n\t}\n\n\tpubSubnets, err := n.getEndPointAddrs(pkg.StrIdentifier(nodeID))\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"failed to get node public endpoints\")\n\t}\n\tvar endpoints []net.IP\n\tif !forceHidden {\n\t\tfor _, sn := range pubSubnets {\n\t\t\tendpoints = append(endpoints, sn.IP)\n\t\t}\n\t}\n\n\tnr := NetResource{\n\t\tNetworkNetResource: workloads.NetworkNetResource{\n\t\t\tNodeId: nodeID,\n\t\t\tIprange: schema.IPRange{ipnet.IPNet},\n\t\t\tWireguardListenPort: int64(port),\n\t\t\tWireguardPublicKey: privateKey.PublicKey().String(),\n\t\t\tWireguardPrivateKeyEncrypted: hex.EncodeToString(encrypted),\n\t\t},\n\t\tPubEndpoints: endpoints,\n\t}\n\n\tn.NetResources = append(n.NetResources, nr)\n\n\tif err = n.generatePeers(); err != nil {\n\t\treturn n, errors.Wrap(err, \"failed to generate peers\")\n\t}\n\n\treturn n, nil\n}", "func (o *TunnelServerOptions) validate() error {\n\tif len(o.bindAddr) == 0 {\n\t\treturn fmt.Errorf(\"%s's bind address can't be empty\",\n\t\t\tversion.GetServerName())\n\t}\n\treturn nil\n}" ]
[ "0.68498296", "0.67687345", "0.61033916", "0.51745284", "0.5173281", "0.5138812", "0.5095825", "0.50670433", "0.50491786", "0.50297546", "0.5026576", "0.50178283", "0.49751574", "0.496253", "0.49549386", "0.49383596", "0.49335337", "0.49203494", "0.48882163", "0.48774028", "0.48645517", "0.48555884", "0.48278004", "0.48073152", "0.48066664", "0.4799555", "0.47877645", "0.47720551", "0.47710717", "0.47669187", "0.47630838", "0.47583243", "0.47574404", "0.4754686", "0.47498092", "0.47464308", "0.4746048", "0.47452086", "0.47365808", "0.47316957", "0.4725635", "0.47197974", "0.47166333", "0.47145176", "0.47144762", "0.47072217", "0.47028244", "0.4693505", "0.46923658", "0.46852237", "0.46747434", "0.46639428", "0.4651021", "0.46439528", "0.46410257", "0.46410087", "0.46338472", "0.46233463", "0.46208966", "0.4601861", "0.46006036", "0.4598775", "0.45978317", "0.45965463", "0.4593905", "0.45788273", "0.4569181", "0.45444688", "0.45363262", "0.4535364", "0.45349628", "0.4533254", "0.45288646", "0.45259547", "0.4525708", "0.45253688", "0.45159122", "0.4512505", "0.4511842", "0.45112926", "0.45096916", "0.4509034", "0.45079476", "0.44980827", "0.44941723", "0.44858298", "0.44846395", "0.44829872", "0.44756514", "0.447184", "0.44698355", "0.4467916", "0.44643724", "0.4447843", "0.4439788", "0.44382706", "0.44372147", "0.4436467", "0.4435757", "0.443102" ]
0.7425289
0
Validate validates this add remote RDS node default body
func (o *AddRemoteRDSNodeDefaultBody) Validate(formats strfmt.Registry) error { var res []error if err := o.validateDetails(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *AddRemoteRDSNodeBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *AddRemoteRDSNodeOKBodyRemoteRDS) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *AddRemoteRDSNodeOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateRemoteRDS(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *AddPMMAgentDefaultBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateDetails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *AddExternalDefaultBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateDetails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ValidateNewPostRequestBody(body *NewPostRequestBody) (err error) {\n\tif body.Body == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"body\", \"body\"))\n\t}\n\treturn\n}", "func (o *AddExternalBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *AddPMMAgentBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *AddQANPostgreSQLPgStatementsAgentDefaultBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateDetails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *AddQANPostgreSQLPgStatementsAgentBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (body *AddRequestBody) Validate() (err error) {\n\tif body.Token == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"token\", \"body\"))\n\t}\n\treturn\n}", "func (o *PostSiteCreatedBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *PostSiteBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *VolumeCreateBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (body *CreateResponseBody) Validate() (err error) {\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Color == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"color\", \"body\"))\n\t}\n\tif body.Cron == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"cron\", \"body\"))\n\t}\n\tif body.Name != nil {\n\t\tif utf8.RuneCountInString(*body.Name) > 100 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(\"body.name\", *body.Name, utf8.RuneCountInString(*body.Name), 100, false))\n\t\t}\n\t}\n\tif body.Color != nil {\n\t\tif !(*body.Color == \"red\" || *body.Color == \"yellow\" || *body.Color == \"green\" || *body.Color == \"off\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"body.color\", *body.Color, []interface{}{\"red\", \"yellow\", \"green\", \"off\"}))\n\t\t}\n\t}\n\treturn\n}", "func (o *PostIPAMIpsOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (payload *CreateMessagePayload) Validate() (err error) {\n\n\tif payload.Text == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"text\"))\n\t}\n\treturn\n}", "func (o *RepoMigrateCreatedBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateCloneURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateDefaultBranch(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateDescription(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateEmpty(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateFork(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateForks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateFullName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateHTMLURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateMirror(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateOpenIssues(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePrivate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSSHURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSize(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateStars(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateUpdated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateWatchers(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateWebsite(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateOwner(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateParent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePermissions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *ServiceCreateCreatedBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (payload *CreateItemPayload) Validate() (err error) {\n\tif payload.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"name\"))\n\t}\n\tif payload.Description == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"description\"))\n\t}\n\n\tif payload.Image1 == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"image1\"))\n\t}\n\treturn\n}", "func (o *PostIPAMIpnatOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateAddRequestBody(body *AddRequestBody) (err error) {\n\tif body.Resource == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"resource\", \"body\"))\n\t}\n\tif body.Action == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"action\", \"body\"))\n\t}\n\treturn\n}", "func (g *GuidePost) validateNodeConfig(q *msg.Request) (bool, error) {\n\tif q.Node.Config == nil {\n\t\treturn false, fmt.Errorf(\"NodeConfig subobject missing\")\n\t}\n\treturn g.validateBucketInRepository(\n\t\tq.Node.Config.RepositoryID,\n\t\tq.Node.Config.BucketID,\n\t)\n}", "func (nS *PostMessageBody) Validate() error {\n\treturn validator.New().Struct(nS)\n}", "func (o *PostSiteCreatedBodyData) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateRoutes(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func ValidateAdminCreateNewUserRequestBody(body *AdminCreateNewUserRequestBody) (err error) {\n\tif body.UserName == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"user_name\", \"body\"))\n\t}\n\tif body.EmailAddress == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"email_address\", \"body\"))\n\t}\n\tif body.PhoneNumber == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"phone_number\", \"body\"))\n\t}\n\tif body.PhotoURL == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"photo_url\", \"body\"))\n\t}\n\tif body.UserName != nil {\n\t\tif utf8.RuneCountInString(*body.UserName) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(\"body.user_name\", *body.UserName, utf8.RuneCountInString(*body.UserName), 1, true))\n\t\t}\n\t}\n\tif body.UserName != nil {\n\t\tif utf8.RuneCountInString(*body.UserName) > 20 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(\"body.user_name\", *body.UserName, utf8.RuneCountInString(*body.UserName), 20, false))\n\t\t}\n\t}\n\tif body.EmailAddress != nil {\n\t\terr = goa.MergeErrors(err, goa.ValidateFormat(\"body.email_address\", *body.EmailAddress, goa.FormatEmail))\n\t}\n\tif body.PhoneNumber != nil {\n\t\terr = goa.MergeErrors(err, goa.ValidatePattern(\"body.phone_number\", *body.PhoneNumber, \"^\\\\+?[\\\\d]{10,}$\"))\n\t}\n\treturn\n}", "func (o *PostSiteNotFoundBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *PostLeasesIDAuthCreatedBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateAddRequestBody(body *AddRequestBody) (err error) {\n\tif body.Step != nil {\n\t\tif err2 := ValidateStepRequestBody(body.Step); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func (o *Virtualserver) validate(dbRecord *common.DbRecord) (ok bool, err error) {\n\t////////////////////////////////////////////////////////////////////////////\n\t// Marshal data interface.\n\t////////////////////////////////////////////////////////////////////////////\n\tvar data virtualserver.Data\n\terr = shared.MarshalInterface(dbRecord.Data, &data)\n\tif err != nil {\n\t\treturn\n\t}\n\t////////////////////////////////////////////////////////////////////////////\n\t// Test required fields.\n\t////////////////////////////////////////////////////////////////////////////\n\tok = true\n\trequired := make(map[string]bool)\n\trequired[\"ProductCode\"] = false\n\trequired[\"IP\"] = false\n\trequired[\"Port\"] = false\n\trequired[\"LoadBalancerIP\"] = false\n\trequired[\"Name\"] = false\n\t////////////////////////////////////////////////////////////////////////////\n\tif data.ProductCode != 0 {\n\t\trequired[\"ProductCode\"] = true\n\t}\n\tif len(dbRecord.LoadBalancerIP) > 0 {\n\t\trequired[\"LoadBalancerIP\"] = true\n\t}\n\tif len(data.Ports) != 0 {\n\t\trequired[\"Port\"] = true\n\t}\n\tif data.IP != \"\" {\n\t\trequired[\"IP\"] = true\n\t}\n\tif data.Name != \"\" {\n\t\trequired[\"Name\"] = true\n\t}\n\tfor _, val := range required {\n\t\tif val == false {\n\t\t\tok = false\n\t\t}\n\t}\n\tif !ok {\n\t\terr = fmt.Errorf(\"missing required fields - %+v\", required)\n\t}\n\treturn\n}", "func (o *SyncCopyBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (payload *addListenPayload) Validate() (err error) {\n\tif payload.Etype == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\tif payload.Hookurl != nil {\n\t\tif ok := goa.ValidatePattern(`^https?://((\\w)+.?)+/(\\w+)$`, *payload.Hookurl); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`raw.hookurl`, *payload.Hookurl, `^https?://((\\w)+.?)+/(\\w+)$`))\n\t\t}\n\t}\n\treturn\n}", "func (o *PostTemplateTemplateIDCopyBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func NewAddRemoteRDSNodeDefault(code int) *AddRemoteRDSNodeDefault {\n\treturn &AddRemoteRDSNodeDefault{\n\t\t_statusCode: code,\n\t}\n}", "func addNode(address, username, password, name, bundle string, approve bool) (string, error) {\n\tvar ret string\n\n\t// Build the request body.\n\tenrolBody := types.NodeEnrollmentBody{\n\t\tAddress: address,\n\t\tName: name,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tAutoApprove: !approve, // user specifies if they dont want it\n\t\tCallHome: false,\n\t}\n\tif bundle != \"\" {\n\t\tenrolBody.Bundle = bundle\n\t\tenrolBody.Hostname = name\n\t\tenrolBody.CallHome = true\n\t}\n\trequest := types.EnrollmentRequest{\n\t\tEnrollment: enrolBody,\n\t}\n\treqJSON, err := json.Marshal(&request)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\turl, err := client.GetURL(nodeURI)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\treq, err := client.BuildReq(&reqJSON, url, http.MethodPost, true)\n\trawResp, err := client.HTTPClient().Do(req)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\t_, err = client.ParseReq(rawResp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\treturn \"Node added successfully\\n\", nil\n}", "func ValidateStoredStepRequestBody(body *StoredStepRequestBody) (err error) {\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Title == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"title\", \"body\"))\n\t}\n\tif body.Target == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"target\", \"body\"))\n\t}\n\tif body.StepNumber == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"stepNumber\", \"body\"))\n\t}\n\tif body.Content == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"content\", \"body\"))\n\t}\n\tif body.Placement == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"placement\", \"body\"))\n\t}\n\tif body.Action == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"action\", \"body\"))\n\t}\n\tif body.Placement != nil {\n\t\tif !(*body.Placement == \"left\" || *body.Placement == \"right\" || *body.Placement == \"top\" || *body.Placement == \"buttom\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"body.placement\", *body.Placement, []interface{}{\"left\", \"right\", \"top\", \"buttom\"}))\n\t\t}\n\t}\n\tif body.Action != nil {\n\t\tif !(*body.Action == \"click\" || *body.Action == \"next\" || *body.Action == \"end\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"body.action\", *body.Action, []interface{}{\"click\", \"next\", \"end\"}))\n\t\t}\n\t}\n\treturn\n}", "func (o *PostSiteGatewayTimeoutBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *PostRestapiV10NumberPoolReserveDefaultBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateRecords(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *NewThreadBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateBaseReq(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func AddServer(data map[string]string)(err error) {\n uuid := data[\"uuid\"]\n err = ndb.GetTokenByUuid(uuid); if err!=nil{logs.Error(\"Error loading node token: %s\",err); return err}\n ipuuid,portuuid,err := ndb.ObtainPortIp(uuid)\n if err != nil {\n logs.Error(\"AddServer ERROR Obtaining Port and IP for Add a new server into STAP: \"+err.Error())\n return err\n }\n err = nodeclient.AddServer(ipuuid,portuuid, data)\n if err != nil {\n logs.Error(\"node/AddServer ERROR http data request: \"+err.Error())\n return err\n }\n return nil\n}", "func (payload *AddListenPayload) Validate() (err error) {\n\tif payload.Etype == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\tif ok := goa.ValidatePattern(`^https?://((\\w)+.?)+/(\\w+)$`, payload.Hookurl); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`raw.hookurl`, payload.Hookurl, `^https?://((\\w)+.?)+/(\\w+)$`))\n\t}\n\treturn\n}", "func (payload *CreateOutputPayload) Validate() (err error) {\n\tif payload.Alias == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"alias\"))\n\t}\n\tif payload.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"name\"))\n\t}\n\treturn\n}", "func validatePOSTRequest(body []byte, schema *gojsonschema.Schema) (err error) {\n\tdocLoader := gojsonschema.NewStringLoader(string(body))\n\tif result, err := schema.Validate(docLoader); err != nil && !result.Valid() {\n\t\treturn errors.New(\"Couldn't validate json\")\n\t}\n\treturn nil\n}", "func (o *PostSiteBadRequestBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (payload *createMessagePayload) Validate() (err error) {\n\tif payload.OfferID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"offer_id\"))\n\t}\n\tif payload.Text == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"text\"))\n\t}\n\treturn\n}", "func (cc *ContrailCommand) CreateNode(host vcenter.ESXIHost) error {\n\tlog.Debug(\"Create Node:\", cc.AuthToken)\n\tnodeResource := contrailCommandNodeSync{\n\t\tResources: []*nodeResources{\n\t\t\t{\n\t\t\t\tKind: \"node\",\n\t\t\t\tData: &nodeData{\n\t\t\t\t\tNodeType: \"esxi\",\n\t\t\t\t\tUUID: host.UUID,\n\t\t\t\t\tHostname: host.Hostname,\n\t\t\t\t\tFqName: []string{\"default-global-system-config\", host.Hostname},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tjsonData, err := json.Marshal(nodeResource)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Sending Request\")\n\tresp, _, err := cc.sendRequest(\"/sync\", string(jsonData), \"POST\") //nolint: bodyclose\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Got status : \", resp.StatusCode)\n\tswitch resp.StatusCode {\n\tdefault:\n\t\treturn fmt.Errorf(\"resource creation failed, %d\", resp.StatusCode)\n\tcase 200, 201:\n\t}\n\treturn nil\n}", "func (payload *createItemPayload) Validate() (err error) {\n\tif payload.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"name\"))\n\t}\n\tif payload.Description == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"description\"))\n\t}\n\tif payload.Price == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"price\"))\n\t}\n\tif payload.Compensation == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"compensation\"))\n\t}\n\tif payload.CategoryID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"category_id\"))\n\t}\n\tif payload.PlaceID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"place_id\"))\n\t}\n\tif payload.Image1 == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"image1\"))\n\t}\n\treturn\n}", "func (s SubnetArgs) validate() error {\n\tif s.isEmpty() {\n\t\treturn nil\n\t}\n\treturn s.FromTags.validate()\n}", "func (m *Node) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif !_Node_Host_Pattern.MatchString(m.GetHost()) {\n\t\treturn NodeValidationError{\n\t\t\tfield: \"Host\",\n\t\t\treason: \"value does not match regex pattern \\\"^\\\\\\\\*?[0-9a-zA-Z-._]+$\\\"\",\n\t\t}\n\t}\n\n\tif val := m.GetPort(); val < 1 || val > 65535 {\n\t\treturn NodeValidationError{\n\t\t\tfield: \"Port\",\n\t\t\treason: \"value must be inside range [1, 65535]\",\n\t\t}\n\t}\n\n\tif m.GetWeight() < 0 {\n\t\treturn NodeValidationError{\n\t\t\tfield: \"Weight\",\n\t\t\treason: \"value must be greater than or equal to 0\",\n\t\t}\n\t}\n\n\tfor key, val := range m.GetMetadata() {\n\t\t_ = val\n\n\t\t// no validation rules for Metadata[key]\n\n\t\tif v, ok := interface{}(val).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn NodeValidationError{\n\t\t\t\t\tfield: fmt.Sprintf(\"Metadata[%v]\", key),\n\t\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\t\tcause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func validateNodeStageVolumeRequest(req *csi.NodeStageVolumeRequest) error {\n\tif req.GetVolumeCapability() == nil {\n\t\treturn fmt.Errorf(\"volume capability missing in request\")\n\t}\n\n\tif req.GetVolumeId() == \"\" {\n\t\treturn fmt.Errorf(\"volume ID missing in request\")\n\t}\n\n\tif req.GetStagingTargetPath() == \"\" {\n\t\treturn fmt.Errorf(\"staging target path missing in request\")\n\t}\n\n\tif req.GetNodeStageSecrets() == nil || len(req.GetNodeStageSecrets()) == 0 {\n\t\treturn fmt.Errorf(\"stage secrets cannot be nil or empty\")\n\t}\n\n\treturn nil\n}", "func (ut *addUserPayload) Validate() (err error) {\n\tif ut.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"name\"))\n\t}\n\tif ut.Email == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"email\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`request.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif ok := goa.ValidatePattern(`\\S`, *ut.Name); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`request.name`, *ut.Name, `\\S`))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 256 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 256, false))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 10 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 10, true))\n\t\t}\n\t}\n\treturn\n}", "func validateNodeStageVolumeRequest(req *csi.NodeStageVolumeRequest) error {\n\tif req.GetVolumeCapability() == nil {\n\t\treturn errors.New(\"volume capability missing in request\")\n\t}\n\n\tif req.GetVolumeId() == \"\" {\n\t\treturn errors.New(\"volume ID missing in request\")\n\t}\n\n\tif req.GetVolumeContext() == nil || len(req.GetVolumeContext()) == 0 {\n\t\treturn errors.New(\"volume context cannot be nil or empty\")\n\t}\n\n\tif req.GetSecrets() == nil || len(req.GetSecrets()) == 0 {\n\t\treturn errors.New(\"stage secrets cannot be nil or empty\")\n\t}\n\n\treturn nil\n}", "func (r *NodeDeployment) ValidateCreate() error {\n\tnodedeploymentlog.Info(\"validate create\", \"name\", r.Name)\n\n\t// TODO(user): fill in your validation logic upon object creation.\n\treturn nil\n}", "func (r *MachinePoolsAddServerRequest) Body() *MachinePool {\n\tif r == nil {\n\t\treturn nil\n\t}\n\treturn r.body\n}", "func (o *DeleteDatasetCreatedBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *CreateWidgetBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateWidgetTemplateUUID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m *MerchantCreateBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCode(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateFeatures(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateGatewayID(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *PostDeviceURLOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (c *Client) Add(ctx context.Context, node NodeInfo) error {\n\trequest := protocol.Message{}\n\tresponse := protocol.Message{}\n\n\trequest.Init(4096)\n\tresponse.Init(4096)\n\n\tprotocol.EncodeAdd(&request, node.ID, node.Address)\n\n\tif err := c.protocol.Call(ctx, &request, &response); err != nil {\n\t\treturn err\n\t}\n\n\tif err := protocol.DecodeEmpty(&response); err != nil {\n\t\treturn err\n\t}\n\n\t// If the desired role is spare, there's nothing to do, since all newly\n\t// added nodes have the spare role.\n\tif node.Role == Spare {\n\t\treturn nil\n\t}\n\n\treturn c.Assign(ctx, node.ID, node.Role)\n}", "func AddReplicationTarget(nbmaster string, httpClient *http.Client, jwt string, stsName string, candId string)(int) {\n fmt.Printf(\"\\nSending a POST request to create with defaults...\\n\")\n\n\t//reader := bufio.NewReader(os.Stdin)\n\tIdSlice := strings.Split(candId, \":\")\n\n username := apiUtil.TakeInput(\"Enter target storage server username:\")\n\tpassword := apiUtil.TakeInput(\"Enter target storage server password:\")\n\n replicationtarget := map[string]interface{}{\n \"data\": map[string]interface{}{\n \"type\": \"replicationTargetRequest\",\n \"attributes\": map[string]interface{}{\n\t\t\t\t\"targetStorageServerInfo\": map[string]interface{}{\n \"targetMasterServer\": IdSlice[3],\n\t\t\t\t\t\"targetStorageServer\": IdSlice[1],\n\t\t\t\t\t\"targetStorageServerType\": IdSlice[0],\n\t\t\t\t\t\"targetMediaServer\": IdSlice[2]},\n\t\t\t\t\"targetStorageServerCredentials\": map[string]interface{}{\n\t\t\t\t\t\"userName\": username,\n\t\t\t\t\t\"password\": password}}}}\n\t\t\t\t\n\n\n stsRequest, _ := json.Marshal(replicationtarget)\n\n uri := \"https://\" + nbmaster + \":\" + port + \"/netbackup/\" + storageUri + storageServerUri + \"PureDisk:\" + stsName + replicationTargetsUri\n\n request, _ := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(stsRequest))\n request.Header.Add(\"Content-Type\", contentType);\n request.Header.Add(\"Authorization\", jwt);\n\n fmt.Println (\"Firing request: POST: \" + uri)\n response, err := httpClient.Do(request)\n\n if err != nil {\n fmt.Printf(\"The HTTP request failed with error: %s\\n\", err)\n panic(\"Unable to add replication target.\\n\")\n } else {\n if response.StatusCode != 201 {\n responseBody, _ := ioutil.ReadAll(response.Body)\n fmt.Printf(\"%s\\n\", responseBody)\n panic(\"Unable to add replication target.\\n\")\n } else {\n fmt.Printf(\"%s created successfully.\\n\", \"\");\n //responseDetails, _ := httputil.DumpResponse(response, true);\n apiUtil.AskForResponseDisplay(response.Body)\n }\n }\n\t\n\treturn response.StatusCode;\n}", "func (m *StoragepoolNodepool) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func isValidLocationConstraint(reqBody io.Reader) (err error) {\n\tvar region = helper.CONFIG.Region\n\tvar locationConstraint CreateBucketLocationConfiguration\n\te := xmlDecoder(reqBody, &locationConstraint)\n\tif e != nil {\n\t\tif e == io.EOF {\n\t\t\t// Failed due to empty request body. The location will be set to\n\t\t\t// default value from the serverConfig\n\t\t\terr = nil\n\t\t} else {\n\t\t\t// Failed due to malformed configuration.\n\t\t\terr = ErrMalformedXML\n\t\t}\n\t} else {\n\t\t// Region obtained from the body.\n\t\t// It should be equal to Region in serverConfig.\n\t\t// Else ErrInvalidRegion returned.\n\t\t// For empty value location will be to set to default value from the serverConfig.\n\t\tif locationConstraint.Location != \"\" && region != locationConstraint.Location {\n\t\t\terr = ErrInvalidRegion\n\t\t}\n\t}\n\treturn err\n}", "func (o *PostTemplateTemplateIDCopyOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *PostSiteForbiddenBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func NodeUpdate(w http.ResponseWriter, r *http.Request) {\n\tvar n swl.Node\n\tvar nameChanged bool\n\tvar ipChanged bool\n\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err := r.Body.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif !swl.ValidateAndUnmarshalJSON(body, &n, w) {\n\t\treturn\n\t}\n\n\tif n.Name != nil {\n\t\tnameChanged = true\n\t}\n\n\tif n.IP != nil {\n\t\tif !swl.ValidateParamRegex(\"ip\", node.IP,\n\t\t\t\"\\\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\\\.|$)){4}\\\\b\", w) {\n\t\t\treturn\n\t\t}\n\t\tipChanged = true\n\t}\n\n\tif nameChanged {\n\t\tnode.Name = n.Name\n\t}\n\tif ipChanged {\n\t\tnode.IP = n.IP\n\t}\n\tw.Header().Set(\"Content-Type\", \"appliation/json; charset=UTF-8\")\n\tw.WriteHeader(200)\n\tif err := json.NewEncoder(w).Encode(node); err != nil {\n\t\tpanic(err)\n\t}\n}", "func resourceNodeV1Create(d *schema.ResourceData, meta interface{}) error {\n\tclient, err := meta.(*Clients).GetIronicClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create the node object in Ironic\n\tcreateOpts := schemaToCreateOpts(d)\n\tresult, err := nodes.Create(client, createOpts).Extract()\n\tif err != nil {\n\t\td.SetId(\"\")\n\t\treturn err\n\t}\n\n\t// Setting the ID is what tells terraform we were successful in creating the node\n\tlog.Printf(\"[DEBUG] Node created with ID %s\\n\", d.Id())\n\td.SetId(result.UUID)\n\n\t// Create ports as part of the node object - you may also use the native port resource\n\tportSet := d.Get(\"ports\").(*schema.Set)\n\tif portSet != nil {\n\t\tportList := portSet.List()\n\t\tfor _, portInterface := range portList {\n\t\t\tport := portInterface.(map[string]interface{})\n\n\t\t\t// Terraform map can't handle bool... seriously.\n\t\t\tvar pxeEnabled bool\n\t\t\tif port[\"pxe_enabled\"] != nil {\n\t\t\t\tif port[\"pxe_enabled\"] == \"true\" {\n\t\t\t\t\tpxeEnabled = true\n\t\t\t\t} else {\n\t\t\t\t\tpxeEnabled = false\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t// FIXME: All values other than address and pxe\n\t\t\tportCreateOpts := ports.CreateOpts{\n\t\t\t\tNodeUUID: d.Id(),\n\t\t\t\tAddress: port[\"address\"].(string),\n\t\t\t\tPXEEnabled: &pxeEnabled,\n\t\t\t}\n\t\t\t_, err := ports.Create(client, portCreateOpts).Extract()\n\t\t\tif err != nil {\n\t\t\t\t_ = resourcePortV1Read(d, meta)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Make node manageable\n\tif d.Get(\"manage\").(bool) || d.Get(\"clean\").(bool) || d.Get(\"inspect\").(bool) {\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"manage\", nil, nil, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"could not manage: %s\", err)\n\t\t}\n\t}\n\n\t// Clean node\n\tif d.Get(\"clean\").(bool) {\n\t\tif err := setRAIDConfig(client, d); err != nil {\n\t\t\treturn fmt.Errorf(\"fail to set raid config: %s\", err)\n\t\t}\n\n\t\tvar cleanSteps []nodes.CleanStep\n\t\tif cleanSteps, err = buildManualCleaningSteps(d.Get(\"raid_interface\").(string), d.Get(\"raid_config\").(string), d.Get(\"bios_settings\").(string)); err != nil {\n\t\t\treturn fmt.Errorf(\"fail to build raid clean steps: %s\", err)\n\t\t}\n\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"clean\", nil, nil, cleanSteps); err != nil {\n\t\t\treturn fmt.Errorf(\"could not clean: %s\", err)\n\t\t}\n\t}\n\n\t// Inspect node\n\tif d.Get(\"inspect\").(bool) {\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"inspect\", nil, nil, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"could not inspect: %s\", err)\n\t\t}\n\t}\n\n\t// Make node available\n\tif d.Get(\"available\").(bool) {\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"provide\", nil, nil, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"could not make node available: %s\", err)\n\t\t}\n\t}\n\n\t// Change power state, if required\n\tif targetPowerState := d.Get(\"target_power_state\").(string); targetPowerState != \"\" {\n\t\terr := changePowerState(client, d, nodes.TargetPowerState(targetPowerState))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not change power state: %s\", err)\n\t\t}\n\t}\n\n\treturn resourceNodeV1Read(d, meta)\n}", "func (o *CreateChannelBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateConfigMeta(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePlatform(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *CreateWidgetUnprocessableEntityBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (payload *UpdateListenPayload) Validate() (err error) {\n\tif payload.Etype == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (o *CreateChannelCreatedBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (v rdwsVpcConfig) validate() error {\n\tif v.isEmpty() {\n\t\treturn nil\n\t}\n\tif err := v.Placement.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"placement\": %w`, err)\n\t}\n\treturn nil\n}", "func (payload *createOutputPayload) Validate() (err error) {\n\tif payload.Alias == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"alias\"))\n\t}\n\tif payload.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"name\"))\n\t}\n\treturn\n}", "func (client *Client) AddShardingNodeWithOptions(request *AddShardingNodeRequest, runtime *util.RuntimeOptions) (_result *AddShardingNodeResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AutoPay)) {\n\t\tquery[\"AutoPay\"] = request.AutoPay\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.BusinessInfo)) {\n\t\tquery[\"BusinessInfo\"] = request.BusinessInfo\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.CouponNo)) {\n\t\tquery[\"CouponNo\"] = request.CouponNo\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ForceTrans)) {\n\t\tquery[\"ForceTrans\"] = request.ForceTrans\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.InstanceId)) {\n\t\tquery[\"InstanceId\"] = request.InstanceId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerAccount)) {\n\t\tquery[\"OwnerAccount\"] = request.OwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerId)) {\n\t\tquery[\"OwnerId\"] = request.OwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerAccount)) {\n\t\tquery[\"ResourceOwnerAccount\"] = request.ResourceOwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerId)) {\n\t\tquery[\"ResourceOwnerId\"] = request.ResourceOwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SecurityToken)) {\n\t\tquery[\"SecurityToken\"] = request.SecurityToken\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ShardCount)) {\n\t\tquery[\"ShardCount\"] = request.ShardCount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SourceBiz)) {\n\t\tquery[\"SourceBiz\"] = request.SourceBiz\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.VSwitchId)) {\n\t\tquery[\"VSwitchId\"] = request.VSwitchId\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"AddShardingNode\"),\n\t\tVersion: tea.String(\"2015-01-01\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &AddShardingNodeResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (c *CAPI) AddNode(req *btcjson.AddNodeCmd, resp None) (e error) {\n\tnrh := RPCHandlers\n\tres := nrh[\"addnode\"].Result()\n\tres.Params = req\n\tnrh[\"addnode\"].Call <- res\n\tselect {\n\tcase resp = <-res.Ch.(chan None):\n\tcase <-time.After(c.Timeout):\n\tcase <-c.quit.Wait():\n\t} \n\treturn \n}", "func (o *CreateShortLinkBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (payload *CreateVerificationPayload) Validate() (err error) {\n\n\treturn\n}", "func (o *PostProfileBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (payload *postEventPayload) Validate() (err error) {\n\tif payload.Etype == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Action == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"action\"))\n\t}\n\tif payload.From == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (o *SaveBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateHash(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateKeyPair(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (payload *PostEventPayload) Validate() (err error) {\n\tif payload.Etype == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Action == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"action\"))\n\t}\n\tif payload.From == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func (payload *updateListenPayload) Validate() (err error) {\n\tif payload.Etype == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\treturn\n}", "func createNode(w http.ResponseWriter, r *http.Request) {\n\tvar newNode* Nodo\n\t//leemos el body de la petición\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Datos Inválidos\")\n\t}\n\t//tomamos los valores del body y los colocamos en una variable de struct de Nodo\n\tjson.Unmarshal(reqBody, &newNode)\n\t//fmt.Printf(\"%d\",newNode.Carnet)\n\t//insertamos la raiz\n\traiz=crearNodo(raiz,newNode)\n\tescribir,err2:=json.Marshal(raiz)\n\tif err2 != nil {\n log.Fatal(err2)\n }\n\tdata := []byte(escribir)\n err = ioutil.WriteFile(\"persiste.json\", data, 0644)\n if err != nil {\n log.Fatal(err)\n }\n\tfmt.Println(\"----------------\")\n\t//preorden(raiz)\n\t//createDot(raiz)\n\t//Si todo ha salido bien, devolvemos un status code 201 y el arbol\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\trespuesta:= &Respuesta{Message:\"Alumno creado exitosamente\"}\n\tw.WriteHeader(http.StatusCreated)\n\tjson.NewEncoder(w).Encode(respuesta)\n\n}", "func (m *GaragesCreateBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCentreID(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLocations(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *TunnelServerOptions) validate() error {\n\tif len(o.bindAddr) == 0 {\n\t\treturn fmt.Errorf(\"%s's bind address can't be empty\",\n\t\t\tversion.GetServerName())\n\t}\n\treturn nil\n}", "func (ut *userCreatePayload) Validate() (err error) {\n\tif ut.Email == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"email\"))\n\t}\n\tif ut.Nickname == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"nickname\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`request.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Nickname != nil {\n\t\tif utf8.RuneCountInString(*ut.Nickname) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.nickname`, *ut.Nickname, utf8.RuneCountInString(*ut.Nickname), 1, true))\n\t\t}\n\t}\n\tif ut.Nickname != nil {\n\t\tif utf8.RuneCountInString(*ut.Nickname) > 32 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.nickname`, *ut.Nickname, utf8.RuneCountInString(*ut.Nickname), 32, false))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 1 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 1, true))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) > 32 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 32, false))\n\t\t}\n\t}\n\treturn\n}", "func AddNode(c *cli.Context) error {\n\n\t/*\n\t * (0) Check flags\n\t */\n\n\tclusterName := c.String(\"name\")\n\tnodeCount := c.Int(\"count\")\n\n\tclusterSpec := &ClusterSpec{\n\t\tAgentArgs: nil,\n\t\tAPIPort: apiPort{},\n\t\tAutoRestart: false,\n\t\tClusterName: clusterName,\n\t\tEnv: nil,\n\t\tNodeToLabelSpecMap: nil,\n\t\tImage: \"\",\n\t\tNodeToPortSpecMap: nil,\n\t\tPortAutoOffset: 0,\n\t\tServerArgs: nil,\n\t\tVolumes: &Volumes{},\n\t}\n\n\t/* (0.1)\n\t * --role\n\t * Role of the node that has to be created.\n\t * One of (server|master), (agent|worker)\n\t */\n\tnodeRole := c.String(\"role\")\n\tif nodeRole == \"worker\" {\n\t\tnodeRole = \"agent\"\n\t}\n\tif nodeRole == \"master\" {\n\t\tnodeRole = \"server\"\n\t}\n\n\t// TODO: support adding server nodes\n\tif nodeRole != \"worker\" && nodeRole != \"agent\" {\n\t\treturn fmt.Errorf(\"Adding nodes of type '%s' is not supported\", nodeRole)\n\t}\n\n\t/* (0.2)\n\t * --image, -i\n\t * The k3s image used for the k3d node containers\n\t */\n\t// TODO: use the currently running image by default\n\timage := c.String(\"image\")\n\t// if no registry was provided, use the default docker.io\n\tif len(strings.Split(image, \"/\")) <= 2 {\n\t\timage = fmt.Sprintf(\"%s/%s\", DefaultRegistry, image)\n\t}\n\tclusterSpec.Image = image\n\n\t/* (0.3)\n\t * --env, -e <key1=val1>[,<keyX=valX]\n\t * Environment variables that will be passed to the node containers\n\t */\n\tclusterSpec.Env = []string{}\n\tclusterSpec.Env = append(clusterSpec.Env, c.StringSlice(\"env\")...)\n\n\t/* (0.4)\n\t * --arg, -x <argument>\n\t * Argument passed in to the k3s server/agent command\n\t */\n\tclusterSpec.ServerArgs = append(clusterSpec.ServerArgs, c.StringSlice(\"arg\")...)\n\tclusterSpec.AgentArgs = append(clusterSpec.AgentArgs, c.StringSlice(\"arg\")...)\n\n\t/* (0.5)\n\t * --volume, -v\n\t * Add volume mounts\n\t */\n\tvolumeSpec, err := NewVolumes(c.StringSlice(\"volume\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\t// TODO: volumeSpec.DefaultVolumes = append(volumeSpec.DefaultVolumes, \"%s:/images\", imageVolume.Name)\n\tclusterSpec.Volumes = volumeSpec\n\n\t/* (0.5) BREAKOUT\n\t * --k3s <url>\n\t * Connect to a non-dockerized k3s server\n\t */\n\n\tif c.IsSet(\"k3s\") {\n\t\tlog.Infof(\"Adding %d %s-nodes to k3s cluster %s...\\n\", nodeCount, nodeRole, c.String(\"k3s\"))\n\t\tif _, err := createClusterNetwork(clusterName); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := addNodeToK3s(c, clusterSpec, nodeRole); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t/*\n\t * (1) Check cluster\n\t */\n\n\tctx := context.Background()\n\tdocker, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())\n\tif err != nil {\n\t\tlog.Errorln(\"Failed to create docker client\")\n\t\treturn err\n\t}\n\n\tfilters := filters.NewArgs()\n\tfilters.Add(\"label\", fmt.Sprintf(\"cluster=%s\", clusterName))\n\tfilters.Add(\"label\", \"app=k3d\")\n\n\t/*\n\t * (1.1) Verify, that the cluster (i.e. the server) that we want to connect to, is running\n\t */\n\tfilters.Add(\"label\", \"component=server\")\n\n\tserverList, err := docker.ContainerList(ctx, types.ContainerListOptions{\n\t\tFilters: filters,\n\t})\n\tif err != nil || len(serverList) == 0 {\n\t\tlog.Errorf(\"Failed to get server container for cluster '%s'\", clusterName)\n\t\treturn err\n\t}\n\n\t/*\n\t * (1.2) Extract cluster information from server container\n\t */\n\tserverContainer, err := docker.ContainerInspect(ctx, serverList[0].ID)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to inspect server container '%s' to get cluster secret\", serverList[0].ID)\n\t\treturn err\n\t}\n\n\t/*\n\t * (1.2.1) Extract cluster secret from server container's labels\n\t */\n\tclusterSecretEnvVar := \"\"\n\tfor _, envVar := range serverContainer.Config.Env {\n\t\tif envVarSplit := strings.SplitN(envVar, \"=\", 2); envVarSplit[0] == \"K3S_CLUSTER_SECRET\" {\n\t\t\tclusterSecretEnvVar = envVar\n\t\t}\n\t}\n\tif clusterSecretEnvVar == \"\" {\n\t\treturn fmt.Errorf(\"Failed to get cluster secret from server container\")\n\t}\n\n\tclusterSpec.Env = append(clusterSpec.Env, clusterSecretEnvVar)\n\n\t/*\n\t * (1.2.2) Extract API server Port from server container's cmd\n\t */\n\tserverListenPort := \"\"\n\tfor cmdIndex, cmdPart := range serverContainer.Config.Cmd {\n\t\tif cmdPart == \"--https-listen-port\" {\n\t\t\tserverListenPort = serverContainer.Config.Cmd[cmdIndex+1]\n\t\t}\n\t}\n\tif serverListenPort == \"\" {\n\t\treturn fmt.Errorf(\"Failed to get https-listen-port from server container\")\n\t}\n\n\tserverURLEnvVar := fmt.Sprintf(\"K3S_URL=https://%s:%s\", strings.TrimLeft(serverContainer.Name, \"/\"), serverListenPort)\n\tclusterSpec.Env = append(clusterSpec.Env, serverURLEnvVar)\n\n\t/*\n\t * (1.3) Get the docker network of the cluster that we want to connect to\n\t */\n\tfilters.Del(\"label\", \"component=server\")\n\n\tnetworkList, err := docker.NetworkList(ctx, types.NetworkListOptions{\n\t\tFilters: filters,\n\t})\n\tif err != nil || len(networkList) == 0 {\n\t\tlog.Errorf(\"Failed to find network for cluster '%s'\", clusterName)\n\t\treturn err\n\t}\n\n\t/*\n\t * (2) Now identify any existing worker nodes IF we're adding a new one\n\t */\n\thighestExistingWorkerSuffix := 0 // needs to be outside conditional because of bad branching\n\n\tif nodeRole == \"agent\" {\n\t\tfilters.Add(\"label\", \"component=worker\")\n\n\t\tworkerList, err := docker.ContainerList(ctx, types.ContainerListOptions{\n\t\t\tFilters: filters,\n\t\t\tAll: true,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Errorln(\"Failed to list worker node containers\")\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, worker := range workerList {\n\t\t\tsplit := strings.Split(worker.Names[0], \"-\")\n\t\t\tcurrSuffix, err := strconv.Atoi(split[len(split)-1])\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(\"Failed to get highest worker suffix\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif currSuffix > highestExistingWorkerSuffix {\n\t\t\t\thighestExistingWorkerSuffix = currSuffix\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * (3) Create the nodes with configuration that automatically joins them to the cluster\n\t */\n\n\tlog.Infof(\"Adding %d %s-nodes to k3d cluster %s...\\n\", nodeCount, nodeRole, clusterName)\n\n\tif err := createNodes(clusterSpec, nodeRole, highestExistingWorkerSuffix+1, nodeCount); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *AddPMMAgentOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validatePMMAgent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (i ImageWithOptionalPort) validate() error {\n\tif err := i.Image.validate(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (payload *CreateUserPayload) Validate() (err error) {\n\tif payload.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"name\"))\n\t}\n\treturn\n}", "func (payload *createUserPayload) Validate() (err error) {\n\tif payload.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"name\"))\n\t}\n\treturn\n}", "func ValidateNode(member serf.Member) (ok bool, role, dc string) {\n\tif _, ok = member.Tags[\"id\"]; !ok {\n\t\treturn false, \"\", \"\"\n\t}\n\n\t// Get role name\n\tif role, ok = member.Tags[\"role\"]; !ok {\n\t\treturn false, \"\", \"\"\n\t} else if role != CerebrumRole {\n\t\treturn false, \"\", \"\"\n\t}\n\n\t// Get datacenter name\n\tif dc, ok = member.Tags[\"dc\"]; ok {\n\t\treturn true, role, dc\n\t}\n\treturn false, \"\", \"\"\n}", "func (r *RequestBody) AddDefaults() {\n\tif r.DomainScope == \"\" {\n\t\tr.DomainScope = \"annotated\"\n\t}\n\tif len(r.Background) > 0 && r.DomainScope != \"custom\" {\n\t\tr.DomainScope = \"custom\"\n\t}\n\n\tif r.Organism == \"\" {\n\t\tr.Organism = \"hsapiens\"\n\t}\n\n\tif r.SignificanceThresholdMethod == \"\" {\n\t\tr.SignificanceThresholdMethod = \"gSCS\"\n\t}\n\n\tif r.UserThreshold == 0 {\n\t\tr.UserThreshold = 0.01\n\t}\n}", "func (o *AddPMMAgentOKBodyPMMAgent) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func createServer(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar newServer server\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t fmt.Println(err)\n\t\tfmt.Fprintf(w, \"Kindly enter data with the server's address, MSA and MTA network addresses only in order to create new server\")\n\t w.WriteHeader(http.StatusInternalServerError)\n\t return\n\t}\n\tnewServer.ID = strconv.Itoa(len(servers)+1)\n\n\tjson.Unmarshal(reqBody, &newServer)\n\tservers = append(servers, newServer)\n\tw.WriteHeader(http.StatusCreated)\n\n\tjson.NewEncoder(w).Encode(newServer)\n}", "func ValidatePostBadReqResponseBody(body *PostBadReqResponseBody) (err error) {\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Message == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"message\", \"body\"))\n\t}\n\tif body.Temporary == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"temporary\", \"body\"))\n\t}\n\tif body.Timeout == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"timeout\", \"body\"))\n\t}\n\tif body.Fault == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"fault\", \"body\"))\n\t}\n\treturn\n}", "func ValidatePostBadReqResponseBody(body *PostBadReqResponseBody) (err error) {\n\tif body.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"name\", \"body\"))\n\t}\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Message == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"message\", \"body\"))\n\t}\n\tif body.Temporary == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"temporary\", \"body\"))\n\t}\n\tif body.Timeout == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"timeout\", \"body\"))\n\t}\n\tif body.Fault == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"fault\", \"body\"))\n\t}\n\treturn\n}", "func (ut *addFirmwarePayload) Validate() (err error) {\n\tif ut.Etag == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"etag\"))\n\t}\n\tif ut.Module == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"module\"))\n\t}\n\tif ut.Profile == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"profile\"))\n\t}\n\tif ut.URL == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"url\"))\n\t}\n\tif ut.Meta == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"meta\"))\n\t}\n\treturn\n}", "func (o *CreateChannelUnprocessableEntityBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (ut *AddUserPayload) Validate() (err error) {\n\tif ut.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"name\"))\n\t}\n\tif ut.Email == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"email\"))\n\t}\n\tif ut.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"password\"))\n\t}\n\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\n\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\n\t}\n\tif ok := goa.ValidatePattern(`\\S`, ut.Name); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`type.name`, ut.Name, `\\S`))\n\t}\n\tif utf8.RuneCountInString(ut.Name) > 256 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.name`, ut.Name, utf8.RuneCountInString(ut.Name), 256, false))\n\t}\n\tif utf8.RuneCountInString(ut.Password) < 10 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 10, true))\n\t}\n\treturn\n}", "func (o *CreateProductUnprocessableEntityBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}" ]
[ "0.6955345", "0.64617455", "0.6260935", "0.5257282", "0.51660234", "0.5053359", "0.50475365", "0.5042062", "0.49865404", "0.4915012", "0.48963714", "0.4886728", "0.488275", "0.48794582", "0.48703107", "0.4830896", "0.48222688", "0.47989315", "0.479046", "0.47726774", "0.47579357", "0.47455654", "0.47431767", "0.4736205", "0.4734083", "0.47339672", "0.4728034", "0.47205704", "0.47018853", "0.46996644", "0.46991912", "0.4694576", "0.46939775", "0.46891594", "0.46752694", "0.4674374", "0.4666772", "0.465931", "0.46572834", "0.46451607", "0.46179253", "0.46153787", "0.4615345", "0.46153042", "0.4611603", "0.46096522", "0.4598046", "0.45708048", "0.4547839", "0.4543017", "0.4538024", "0.45361936", "0.4526325", "0.45221066", "0.45173746", "0.45101163", "0.45067966", "0.4504816", "0.4501656", "0.44990957", "0.44949368", "0.44881782", "0.44831425", "0.44718665", "0.44693896", "0.44633234", "0.44631165", "0.4461974", "0.44589156", "0.44564235", "0.4455044", "0.44430348", "0.44339642", "0.44264", "0.44224554", "0.44102776", "0.44087347", "0.44019717", "0.4401148", "0.43940732", "0.43927976", "0.43912005", "0.438099", "0.4380047", "0.4378856", "0.43760318", "0.43636543", "0.43633437", "0.43546858", "0.435462", "0.43533212", "0.43480447", "0.43434778", "0.43329662", "0.43291068", "0.43291068", "0.43268925", "0.4322326", "0.43181464", "0.43180004" ]
0.68783987
1
Validate validates this add remote RDS node OK body
func (o *AddRemoteRDSNodeOKBody) Validate(formats strfmt.Registry) error { var res []error if err := o.validateRemoteRDS(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *AddRemoteRDSNodeBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *AddRemoteRDSNodeOKBodyRemoteRDS) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *AddRemoteRDSNodeDefaultBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateDetails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func AddServer(data map[string]string)(err error) {\n uuid := data[\"uuid\"]\n err = ndb.GetTokenByUuid(uuid); if err!=nil{logs.Error(\"Error loading node token: %s\",err); return err}\n ipuuid,portuuid,err := ndb.ObtainPortIp(uuid)\n if err != nil {\n logs.Error(\"AddServer ERROR Obtaining Port and IP for Add a new server into STAP: \"+err.Error())\n return err\n }\n err = nodeclient.AddServer(ipuuid,portuuid, data)\n if err != nil {\n logs.Error(\"node/AddServer ERROR http data request: \"+err.Error())\n return err\n }\n return nil\n}", "func (c *Client) Add(ctx context.Context, node NodeInfo) error {\n\trequest := protocol.Message{}\n\tresponse := protocol.Message{}\n\n\trequest.Init(4096)\n\tresponse.Init(4096)\n\n\tprotocol.EncodeAdd(&request, node.ID, node.Address)\n\n\tif err := c.protocol.Call(ctx, &request, &response); err != nil {\n\t\treturn err\n\t}\n\n\tif err := protocol.DecodeEmpty(&response); err != nil {\n\t\treturn err\n\t}\n\n\t// If the desired role is spare, there's nothing to do, since all newly\n\t// added nodes have the spare role.\n\tif node.Role == Spare {\n\t\treturn nil\n\t}\n\n\treturn c.Assign(ctx, node.ID, node.Role)\n}", "func (c *CAPI) AddNode(req *btcjson.AddNodeCmd, resp None) (e error) {\n\tnrh := RPCHandlers\n\tres := nrh[\"addnode\"].Result()\n\tres.Params = req\n\tnrh[\"addnode\"].Call <- res\n\tselect {\n\tcase resp = <-res.Ch.(chan None):\n\tcase <-time.After(c.Timeout):\n\tcase <-c.quit.Wait():\n\t} \n\treturn \n}", "func addNode(address, username, password, name, bundle string, approve bool) (string, error) {\n\tvar ret string\n\n\t// Build the request body.\n\tenrolBody := types.NodeEnrollmentBody{\n\t\tAddress: address,\n\t\tName: name,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tAutoApprove: !approve, // user specifies if they dont want it\n\t\tCallHome: false,\n\t}\n\tif bundle != \"\" {\n\t\tenrolBody.Bundle = bundle\n\t\tenrolBody.Hostname = name\n\t\tenrolBody.CallHome = true\n\t}\n\trequest := types.EnrollmentRequest{\n\t\tEnrollment: enrolBody,\n\t}\n\treqJSON, err := json.Marshal(&request)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\turl, err := client.GetURL(nodeURI)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\treq, err := client.BuildReq(&reqJSON, url, http.MethodPost, true)\n\trawResp, err := client.HTTPClient().Do(req)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\t_, err = client.ParseReq(rawResp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\treturn \"Node added successfully\\n\", nil\n}", "func (ctx Context) AddNode(count int, hardwareprofile, softwareprofile string) (AddNodeResult, error) {\n\tvar result AddNodeResult\n\n\t// we trust the signature\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\taddInput := AddNodeInput{inner{count, hardwareprofile, softwareprofile}}\n\tinput, errMarshal := json.Marshal(addInput)\n\tif errMarshal != nil {\n\t\treturn result, errMarshal\n\t}\n\turl := fmt.Sprintf(\"https://%s:8443/v1/nodes\", ctx.Address)\n\treq, errRequest := http.NewRequest(\"POST\", url, bytes.NewBuffer(input))\n\tif errRequest != nil {\n\t\treturn result, errRequest\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.SetBasicAuth(ctx.User, ctx.Password)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer resp.Body.Close()\n\n\tdecoder := json.NewDecoder(resp.Body)\n\tif err := decoder.Decode(&result); err != nil {\n\t\treturn result, err\n\t}\n\treturn result, nil\n}", "func (r *CAPIClient) AddNode(cmd ...*btcjson.AddNodeCmd) (res None, e error) {\n\tvar c *btcjson.AddNodeCmd\n\tif len(cmd) > 0 {\n\t\tc = cmd[0]\n\t}\n\tif e = r.Call(\"CAPI.AddNode\", c, &res); E.Chk(e) {\n\t}\n\treturn\n}", "func (cc *ContrailCommand) CreateNode(host vcenter.ESXIHost) error {\n\tlog.Debug(\"Create Node:\", cc.AuthToken)\n\tnodeResource := contrailCommandNodeSync{\n\t\tResources: []*nodeResources{\n\t\t\t{\n\t\t\t\tKind: \"node\",\n\t\t\t\tData: &nodeData{\n\t\t\t\t\tNodeType: \"esxi\",\n\t\t\t\t\tUUID: host.UUID,\n\t\t\t\t\tHostname: host.Hostname,\n\t\t\t\t\tFqName: []string{\"default-global-system-config\", host.Hostname},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tjsonData, err := json.Marshal(nodeResource)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Sending Request\")\n\tresp, _, err := cc.sendRequest(\"/sync\", string(jsonData), \"POST\") //nolint: bodyclose\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Got status : \", resp.StatusCode)\n\tswitch resp.StatusCode {\n\tdefault:\n\t\treturn fmt.Errorf(\"resource creation failed, %d\", resp.StatusCode)\n\tcase 200, 201:\n\t}\n\treturn nil\n}", "func RegisterNode(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Register Node called\")\n\tdecoder := json.NewDecoder(r.Body)\n\tvar signedNode models.SignedPeer\n\terr := decoder.Decode(&signedNode)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to decode request to register node. Incorrect format\")\n\t}\n\tvar nodeListJSON string\n\tpeerNode, ok := nodeList[signedNode.PeerNode.PeerId]\n\tif !ok {\n\t\tif(signedNode.PeerNode.VerifyPeerSignature(signedNode.SignedPeerNode)){\n\t\t\tfmt.Println(\"Signature Verified for new user. Register Successful\")\n\t\t\tnodeList[signedNode.PeerNode.PeerId] = signedNode.PeerNode\n\t\t\tnodeListJSON = nodeList.GetNodeListJSON()\n\t\t}else{\n\t\t\tnodeListJSON = \"{}\"\n\t\t}\n\t}else{\n\t\tfmt.Println(\"Peer Id already registered with this uuid.\")\n\t\tif(peerNode.VerifyPeerSignature(signedNode.SignedPeerNode)){\n\t\t\tfmt.Println(\"Verified with old public key. Updating key pair\")\n\t\t\tnodeList[signedNode.PeerNode.PeerId] = signedNode.PeerNode\n\t\t\tnodeListJSON = nodeList.GetNodeListJSON()\n\t\t}else{\n\t\t\tnodeListJSON = \"{}\"\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(nodeListJSON))\n}", "func (r *NodeDeployment) ValidateCreate() error {\n\tnodedeploymentlog.Info(\"validate create\", \"name\", r.Name)\n\n\t// TODO(user): fill in your validation logic upon object creation.\n\treturn nil\n}", "func (o *Virtualserver) validate(dbRecord *common.DbRecord) (ok bool, err error) {\n\t////////////////////////////////////////////////////////////////////////////\n\t// Marshal data interface.\n\t////////////////////////////////////////////////////////////////////////////\n\tvar data virtualserver.Data\n\terr = shared.MarshalInterface(dbRecord.Data, &data)\n\tif err != nil {\n\t\treturn\n\t}\n\t////////////////////////////////////////////////////////////////////////////\n\t// Test required fields.\n\t////////////////////////////////////////////////////////////////////////////\n\tok = true\n\trequired := make(map[string]bool)\n\trequired[\"ProductCode\"] = false\n\trequired[\"IP\"] = false\n\trequired[\"Port\"] = false\n\trequired[\"LoadBalancerIP\"] = false\n\trequired[\"Name\"] = false\n\t////////////////////////////////////////////////////////////////////////////\n\tif data.ProductCode != 0 {\n\t\trequired[\"ProductCode\"] = true\n\t}\n\tif len(dbRecord.LoadBalancerIP) > 0 {\n\t\trequired[\"LoadBalancerIP\"] = true\n\t}\n\tif len(data.Ports) != 0 {\n\t\trequired[\"Port\"] = true\n\t}\n\tif data.IP != \"\" {\n\t\trequired[\"IP\"] = true\n\t}\n\tif data.Name != \"\" {\n\t\trequired[\"Name\"] = true\n\t}\n\tfor _, val := range required {\n\t\tif val == false {\n\t\t\tok = false\n\t\t}\n\t}\n\tif !ok {\n\t\terr = fmt.Errorf(\"missing required fields - %+v\", required)\n\t}\n\treturn\n}", "func (n *Nodes) validateComplete() error {\n\tif n.Incomplete() {\n\t\treturn errors.New(\"incomplete Nodes\")\n\t}\n\tif n.UDP == 0 {\n\t\treturn errors.New(\"missing UDP port\")\n\t}\n\tif n.TCP == 0 {\n\t\treturn errors.New(\"missing TCP port\")\n\t}\n\tif n.IP.IsMulticast() || n.IP.IsUnspecified() {\n\t\treturn errors.New(\"invalid IP (multicast/unspecified)\")\n\t}\n\t_, err := n.ID.Pubkey() // validate the key (on curve, etcPtr.)\n\treturn err\n}", "func (o *AddQANPostgreSQLPgStatementsAgentBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (n *Node) validateComplete() error {\n\tif n.Incomplete() {\n\t\treturn errors.New(\"incomplete node\")\n\t}\n\tif n.UDP == 0 {\n\t\treturn errors.New(\"missing UDP port\")\n\t}\n\tif n.TCP == 0 {\n\t\treturn errors.New(\"missing TCP port\")\n\t}\n\tif n.IP.IsMulticast() || n.IP.IsUnspecified() {\n\t\treturn errors.New(\"invalid IP (multicast/unspecified)\")\n\t}\n\t_, err := n.ID.Pubkey() // validate the key (on curve, etc.)\n\treturn err\n}", "func (a API) AddNode(cmd *btcjson.AddNodeCmd) (e error) {\n\tRPCHandlers[\"addnode\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func AddNode(address string) string {\n\turl := buildUrl(ADD_NODE)\n\tresp, e := Client.Get(url + \"?node=\" + address)\n\tif e != nil {\n\t\tfmt.Println(e)\n\t\treturn \"ERROR\"\n\t}\n\n\t//var data []byte\n\t//num, _ := resp.Body.Read(data)\n\tdefer resp.Body.Close()\n\n\tgetResp := new(GetResp)\n\n\tjson.NewDecoder(resp.Body).Decode(getResp)\n\t//json.Unmarshal(data, getResp)\n\tif getResp.Code == 200 {\n\t\treturn getResp.Data\n\t}\n\treturn getResp.Msg\n}", "func validateRpc(node *Node, reqId []byte) error {\n\tif !bytes.Equal(node.Id, reqId) {\n\t\terrStr := fmt.Sprintf(\"Node ids do not match %v, %v\", node.Id, reqId)\n\t\treturn errors.New(errStr)\n\t}\n\treturn nil\n}", "func (o *AddPMMAgentBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func ValidateNode(member serf.Member) (ok bool, role, dc string) {\n\tif _, ok = member.Tags[\"id\"]; !ok {\n\t\treturn false, \"\", \"\"\n\t}\n\n\t// Get role name\n\tif role, ok = member.Tags[\"role\"]; !ok {\n\t\treturn false, \"\", \"\"\n\t} else if role != CerebrumRole {\n\t\treturn false, \"\", \"\"\n\t}\n\n\t// Get datacenter name\n\tif dc, ok = member.Tags[\"dc\"]; ok {\n\t\treturn true, role, dc\n\t}\n\treturn false, \"\", \"\"\n}", "func (tapestry *Tapestry) addNode(remote Node, newnode Node) (neighbours []Node, err error) {\n\terr = makeRemoteNodeCall(remote, \"AddNode\", NodeRequest{remote, newnode}, &neighbours)\n\treturn\n}", "func (o *PostIPAMIpsOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (g *GuidePost) validateNodeConfig(q *msg.Request) (bool, error) {\n\tif q.Node.Config == nil {\n\t\treturn false, fmt.Errorf(\"NodeConfig subobject missing\")\n\t}\n\treturn g.validateBucketInRepository(\n\t\tq.Node.Config.RepositoryID,\n\t\tq.Node.Config.BucketID,\n\t)\n}", "func (client *Client) AddShardingNodeWithOptions(request *AddShardingNodeRequest, runtime *util.RuntimeOptions) (_result *AddShardingNodeResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AutoPay)) {\n\t\tquery[\"AutoPay\"] = request.AutoPay\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.BusinessInfo)) {\n\t\tquery[\"BusinessInfo\"] = request.BusinessInfo\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.CouponNo)) {\n\t\tquery[\"CouponNo\"] = request.CouponNo\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ForceTrans)) {\n\t\tquery[\"ForceTrans\"] = request.ForceTrans\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.InstanceId)) {\n\t\tquery[\"InstanceId\"] = request.InstanceId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerAccount)) {\n\t\tquery[\"OwnerAccount\"] = request.OwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerId)) {\n\t\tquery[\"OwnerId\"] = request.OwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerAccount)) {\n\t\tquery[\"ResourceOwnerAccount\"] = request.ResourceOwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerId)) {\n\t\tquery[\"ResourceOwnerId\"] = request.ResourceOwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SecurityToken)) {\n\t\tquery[\"SecurityToken\"] = request.SecurityToken\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ShardCount)) {\n\t\tquery[\"ShardCount\"] = request.ShardCount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SourceBiz)) {\n\t\tquery[\"SourceBiz\"] = request.SourceBiz\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.VSwitchId)) {\n\t\tquery[\"VSwitchId\"] = request.VSwitchId\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"AddShardingNode\"),\n\t\tVersion: tea.String(\"2015-01-01\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &AddShardingNodeResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func AddNode(c *cli.Context) error {\n\n\t/*\n\t * (0) Check flags\n\t */\n\n\tclusterName := c.String(\"name\")\n\tnodeCount := c.Int(\"count\")\n\n\tclusterSpec := &ClusterSpec{\n\t\tAgentArgs: nil,\n\t\tAPIPort: apiPort{},\n\t\tAutoRestart: false,\n\t\tClusterName: clusterName,\n\t\tEnv: nil,\n\t\tNodeToLabelSpecMap: nil,\n\t\tImage: \"\",\n\t\tNodeToPortSpecMap: nil,\n\t\tPortAutoOffset: 0,\n\t\tServerArgs: nil,\n\t\tVolumes: &Volumes{},\n\t}\n\n\t/* (0.1)\n\t * --role\n\t * Role of the node that has to be created.\n\t * One of (server|master), (agent|worker)\n\t */\n\tnodeRole := c.String(\"role\")\n\tif nodeRole == \"worker\" {\n\t\tnodeRole = \"agent\"\n\t}\n\tif nodeRole == \"master\" {\n\t\tnodeRole = \"server\"\n\t}\n\n\t// TODO: support adding server nodes\n\tif nodeRole != \"worker\" && nodeRole != \"agent\" {\n\t\treturn fmt.Errorf(\"Adding nodes of type '%s' is not supported\", nodeRole)\n\t}\n\n\t/* (0.2)\n\t * --image, -i\n\t * The k3s image used for the k3d node containers\n\t */\n\t// TODO: use the currently running image by default\n\timage := c.String(\"image\")\n\t// if no registry was provided, use the default docker.io\n\tif len(strings.Split(image, \"/\")) <= 2 {\n\t\timage = fmt.Sprintf(\"%s/%s\", DefaultRegistry, image)\n\t}\n\tclusterSpec.Image = image\n\n\t/* (0.3)\n\t * --env, -e <key1=val1>[,<keyX=valX]\n\t * Environment variables that will be passed to the node containers\n\t */\n\tclusterSpec.Env = []string{}\n\tclusterSpec.Env = append(clusterSpec.Env, c.StringSlice(\"env\")...)\n\n\t/* (0.4)\n\t * --arg, -x <argument>\n\t * Argument passed in to the k3s server/agent command\n\t */\n\tclusterSpec.ServerArgs = append(clusterSpec.ServerArgs, c.StringSlice(\"arg\")...)\n\tclusterSpec.AgentArgs = append(clusterSpec.AgentArgs, c.StringSlice(\"arg\")...)\n\n\t/* (0.5)\n\t * --volume, -v\n\t * Add volume mounts\n\t */\n\tvolumeSpec, err := NewVolumes(c.StringSlice(\"volume\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\t// TODO: volumeSpec.DefaultVolumes = append(volumeSpec.DefaultVolumes, \"%s:/images\", imageVolume.Name)\n\tclusterSpec.Volumes = volumeSpec\n\n\t/* (0.5) BREAKOUT\n\t * --k3s <url>\n\t * Connect to a non-dockerized k3s server\n\t */\n\n\tif c.IsSet(\"k3s\") {\n\t\tlog.Infof(\"Adding %d %s-nodes to k3s cluster %s...\\n\", nodeCount, nodeRole, c.String(\"k3s\"))\n\t\tif _, err := createClusterNetwork(clusterName); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := addNodeToK3s(c, clusterSpec, nodeRole); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\n\t/*\n\t * (1) Check cluster\n\t */\n\n\tctx := context.Background()\n\tdocker, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())\n\tif err != nil {\n\t\tlog.Errorln(\"Failed to create docker client\")\n\t\treturn err\n\t}\n\n\tfilters := filters.NewArgs()\n\tfilters.Add(\"label\", fmt.Sprintf(\"cluster=%s\", clusterName))\n\tfilters.Add(\"label\", \"app=k3d\")\n\n\t/*\n\t * (1.1) Verify, that the cluster (i.e. the server) that we want to connect to, is running\n\t */\n\tfilters.Add(\"label\", \"component=server\")\n\n\tserverList, err := docker.ContainerList(ctx, types.ContainerListOptions{\n\t\tFilters: filters,\n\t})\n\tif err != nil || len(serverList) == 0 {\n\t\tlog.Errorf(\"Failed to get server container for cluster '%s'\", clusterName)\n\t\treturn err\n\t}\n\n\t/*\n\t * (1.2) Extract cluster information from server container\n\t */\n\tserverContainer, err := docker.ContainerInspect(ctx, serverList[0].ID)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to inspect server container '%s' to get cluster secret\", serverList[0].ID)\n\t\treturn err\n\t}\n\n\t/*\n\t * (1.2.1) Extract cluster secret from server container's labels\n\t */\n\tclusterSecretEnvVar := \"\"\n\tfor _, envVar := range serverContainer.Config.Env {\n\t\tif envVarSplit := strings.SplitN(envVar, \"=\", 2); envVarSplit[0] == \"K3S_CLUSTER_SECRET\" {\n\t\t\tclusterSecretEnvVar = envVar\n\t\t}\n\t}\n\tif clusterSecretEnvVar == \"\" {\n\t\treturn fmt.Errorf(\"Failed to get cluster secret from server container\")\n\t}\n\n\tclusterSpec.Env = append(clusterSpec.Env, clusterSecretEnvVar)\n\n\t/*\n\t * (1.2.2) Extract API server Port from server container's cmd\n\t */\n\tserverListenPort := \"\"\n\tfor cmdIndex, cmdPart := range serverContainer.Config.Cmd {\n\t\tif cmdPart == \"--https-listen-port\" {\n\t\t\tserverListenPort = serverContainer.Config.Cmd[cmdIndex+1]\n\t\t}\n\t}\n\tif serverListenPort == \"\" {\n\t\treturn fmt.Errorf(\"Failed to get https-listen-port from server container\")\n\t}\n\n\tserverURLEnvVar := fmt.Sprintf(\"K3S_URL=https://%s:%s\", strings.TrimLeft(serverContainer.Name, \"/\"), serverListenPort)\n\tclusterSpec.Env = append(clusterSpec.Env, serverURLEnvVar)\n\n\t/*\n\t * (1.3) Get the docker network of the cluster that we want to connect to\n\t */\n\tfilters.Del(\"label\", \"component=server\")\n\n\tnetworkList, err := docker.NetworkList(ctx, types.NetworkListOptions{\n\t\tFilters: filters,\n\t})\n\tif err != nil || len(networkList) == 0 {\n\t\tlog.Errorf(\"Failed to find network for cluster '%s'\", clusterName)\n\t\treturn err\n\t}\n\n\t/*\n\t * (2) Now identify any existing worker nodes IF we're adding a new one\n\t */\n\thighestExistingWorkerSuffix := 0 // needs to be outside conditional because of bad branching\n\n\tif nodeRole == \"agent\" {\n\t\tfilters.Add(\"label\", \"component=worker\")\n\n\t\tworkerList, err := docker.ContainerList(ctx, types.ContainerListOptions{\n\t\t\tFilters: filters,\n\t\t\tAll: true,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Errorln(\"Failed to list worker node containers\")\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, worker := range workerList {\n\t\t\tsplit := strings.Split(worker.Names[0], \"-\")\n\t\t\tcurrSuffix, err := strconv.Atoi(split[len(split)-1])\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorln(\"Failed to get highest worker suffix\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif currSuffix > highestExistingWorkerSuffix {\n\t\t\t\thighestExistingWorkerSuffix = currSuffix\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * (3) Create the nodes with configuration that automatically joins them to the cluster\n\t */\n\n\tlog.Infof(\"Adding %d %s-nodes to k3d cluster %s...\\n\", nodeCount, nodeRole, clusterName)\n\n\tif err := createNodes(clusterSpec, nodeRole, highestExistingWorkerSuffix+1, nodeCount); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *Node) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif !_Node_Host_Pattern.MatchString(m.GetHost()) {\n\t\treturn NodeValidationError{\n\t\t\tfield: \"Host\",\n\t\t\treason: \"value does not match regex pattern \\\"^\\\\\\\\*?[0-9a-zA-Z-._]+$\\\"\",\n\t\t}\n\t}\n\n\tif val := m.GetPort(); val < 1 || val > 65535 {\n\t\treturn NodeValidationError{\n\t\t\tfield: \"Port\",\n\t\t\treason: \"value must be inside range [1, 65535]\",\n\t\t}\n\t}\n\n\tif m.GetWeight() < 0 {\n\t\treturn NodeValidationError{\n\t\t\tfield: \"Weight\",\n\t\t\treason: \"value must be greater than or equal to 0\",\n\t\t}\n\t}\n\n\tfor key, val := range m.GetMetadata() {\n\t\t_ = val\n\n\t\t// no validation rules for Metadata[key]\n\n\t\tif v, ok := interface{}(val).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn NodeValidationError{\n\t\t\t\t\tfield: fmt.Sprintf(\"Metadata[%v]\", key),\n\t\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\t\tcause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func validateNodeStageVolumeRequest(req *csi.NodeStageVolumeRequest) error {\n\tif req.GetVolumeCapability() == nil {\n\t\treturn errors.New(\"volume capability missing in request\")\n\t}\n\n\tif req.GetVolumeId() == \"\" {\n\t\treturn errors.New(\"volume ID missing in request\")\n\t}\n\n\tif req.GetVolumeContext() == nil || len(req.GetVolumeContext()) == 0 {\n\t\treturn errors.New(\"volume context cannot be nil or empty\")\n\t}\n\n\tif req.GetSecrets() == nil || len(req.GetSecrets()) == 0 {\n\t\treturn errors.New(\"stage secrets cannot be nil or empty\")\n\t}\n\n\treturn nil\n}", "func (o *PostIPAMIpnatOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (eb *ElectrumBackend) addNode(addr, port string, network Network) error {\n\tident := electrum.NodeIdent(addr, port)\n\n\teb.nodeMu.RLock()\n\t_, existsGood := eb.nodes[ident]\n\t_, existsBad := eb.blacklistedNodes[ident]\n\teb.nodeMu.RUnlock()\n\tif existsGood {\n\t\treturn fmt.Errorf(\"already connected to %s\", addr)\n\t}\n\tif existsBad {\n\t\t// TODO: if we can't connect to a node over TCP, we should try the TLS port?\n\t\treturn fmt.Errorf(\"%s is known to be unreachable\", addr)\n\t}\n\n\tlog.Printf(\"connecting to %s\", addr)\n\tnode, err := electrum.NewNode(addr, port, network)\n\tif err != nil {\n\t\teb.nodeMu.Lock()\n\t\teb.blacklistedNodes[ident] = struct{}{}\n\t\teb.nodeMu.Unlock()\n\t\treturn err\n\t}\n\n\t// Get the server's features\n\tfeature, err := node.ServerFeatures()\n\tif err != nil {\n\t\teb.nodeMu.Lock()\n\t\teb.blacklistedNodes[ident] = struct{}{}\n\t\teb.nodeMu.Unlock()\n\t\treturn err\n\t}\n\t// Check genesis block\n\tif feature.Genesis != GenesisBlock(network) {\n\t\teb.nodeMu.Lock()\n\t\teb.blacklistedNodes[ident] = struct{}{}\n\t\teb.nodeMu.Unlock()\n\t\treturn ErrIncorrectGenesisBlock\n\t}\n\t// TODO: check pruning. Currently, servers currently don't prune, so it's fine to skip for now.\n\n\t// Check version\n\terr = checkVersion(feature.Protocol)\n\tif err != nil {\n\t\teb.nodeMu.Lock()\n\t\teb.blacklistedNodes[ident] = struct{}{}\n\t\teb.nodeMu.Unlock()\n\t\treturn err\n\t}\n\n\t// Negotiate version\n\terr = node.ServerVersion(\"1.2\")\n\tif err != nil {\n\t\teb.nodeMu.Lock()\n\t\teb.blacklistedNodes[ident] = struct{}{}\n\t\teb.nodeMu.Unlock()\n\t\treturn ErrFailedNegotiateVersion\n\t}\n\n\t// TODO: ask the server for info on the block height we care about. If the server doesn't have\n\t// that block, we'll automatically disconnect.\n\n\teb.nodeMu.Lock()\n\teb.nodes[ident] = node\n\teb.nodeMu.Unlock()\n\n\t// We can process requests\n\tgo eb.processRequests(node)\n\n\treturn nil\n}", "func (p PingreqPacket) Validate() error { return nil }", "func createServer(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar newServer server\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t fmt.Println(err)\n\t\tfmt.Fprintf(w, \"Kindly enter data with the server's address, MSA and MTA network addresses only in order to create new server\")\n\t w.WriteHeader(http.StatusInternalServerError)\n\t return\n\t}\n\tnewServer.ID = strconv.Itoa(len(servers)+1)\n\n\tjson.Unmarshal(reqBody, &newServer)\n\tservers = append(servers, newServer)\n\tw.WriteHeader(http.StatusCreated)\n\n\tjson.NewEncoder(w).Encode(newServer)\n}", "func (o *AddExternalBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (th *treeHead) validate(mac hash.Hash) error {\n\ttag, err := th.expectedTag(mac)\n\tif err != nil {\n\t\treturn err\n\t} else if !hmac.Equal(tag, th.Tag) {\n\t\treturn fmt.Errorf(\"integrity: failed to validate tree head\")\n\t}\n\treturn nil\n}", "func (a API) AddNodeChk() (isNew bool) {\n\tselect {\n\tcase o := <-a.Ch.(chan AddNodeRes):\n\t\tif o.Err != nil {\n\t\t\ta.Result = o.Err\n\t\t} else {\n\t\t\ta.Result = o.Res\n\t\t}\n\t\tisNew = true\n\tdefault:\n\t}\n\treturn\n}", "func validateNodeStageVolumeRequest(req *csi.NodeStageVolumeRequest) error {\n\tif req.GetVolumeCapability() == nil {\n\t\treturn fmt.Errorf(\"volume capability missing in request\")\n\t}\n\n\tif req.GetVolumeId() == \"\" {\n\t\treturn fmt.Errorf(\"volume ID missing in request\")\n\t}\n\n\tif req.GetStagingTargetPath() == \"\" {\n\t\treturn fmt.Errorf(\"staging target path missing in request\")\n\t}\n\n\tif req.GetNodeStageSecrets() == nil || len(req.GetNodeStageSecrets()) == 0 {\n\t\treturn fmt.Errorf(\"stage secrets cannot be nil or empty\")\n\t}\n\n\treturn nil\n}", "func (s *DNSSeeder) addNa(nNa *wire.NetAddress) bool {\n\n\tif len(s.nodes) > s.maxSize {\n\t\treturn false\n\t}\n\n\tif nNa.Port != s.Port {\n\t\treturn false\n\t}\n\n\t// generate the key and add to nodes\n\tk := net.JoinHostPort(nNa.IP.String(), strconv.Itoa(int(nNa.Port)))\n\n\tif _, dup := s.nodes[k]; dup == true {\n\t\treturn false\n\t}\n\n\t// if the reported timestamp suggests the netaddress has not been seen in the last 24 hours\n\t// then ignore this netaddress\n\tif (time.Now().Add(-(time.Hour * 24))).After(nNa.Timestamp) {\n\t\treturn false\n\t}\n\n\tnt := node{\n\t\tna: nNa,\n\t\tstatus: statusRG,\n\t\tdnsType: dns.TypeA,\n\t}\n\n\t// select the dns type based on the remote address type and port\n\tif x := nt.na.IP.To4(); x == nil {\n\t\tnt.dnsType = dns.TypeAAAA\n\t}\n\n\t// add the new node details to nodes\n\ts.nodes[k] = &nt\n\n\treturn true\n}", "func validateNodeServerCSR(agent *aiv1beta1.Agent, node *corev1.Node, csr *certificatesv1.CertificateSigningRequest, x509CSR *x509.CertificateRequest) (bool, error) {\n\n\t// Username must consist from \"\"system:node:\" and the node name\n\tnodeAsking := strings.TrimPrefix(csr.Spec.Username, nodeUserPrefix)\n\tif len(nodeAsking) == 0 {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: CSR does not appear to be a node serving CSR. Empty node name after %s prefix\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tnodeUserPrefix)\n\t}\n\n\t// Check groups, we need at least:\n\t// - system:authenticated\n\tif len(csr.Spec.Groups) < 2 || !funk.ContainsString(csr.Spec.Groups, \"system:authenticated\") {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: %v is too small or not contains %q\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tcsr.Spec.Groups, \"system:authenticated\")\n\t}\n\n\tserverUsagesLegacy := []certificatesv1.KeyUsage{\n\t\tcertificatesv1.UsageDigitalSignature,\n\t\tcertificatesv1.UsageKeyEncipherment,\n\t\tcertificatesv1.UsageServerAuth,\n\t}\n\tserverUsages := []certificatesv1.KeyUsage{\n\t\tcertificatesv1.UsageDigitalSignature,\n\t\tcertificatesv1.UsageServerAuth,\n\t}\n\n\tif !hasExactUsages(csr, serverUsages) && !hasExactUsages(csr, serverUsagesLegacy) {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: No exact match between CSR %v and required usages\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tcsr.Spec.Usages)\n\t}\n\n\t// \"system:nodes\" must be one of the elements of Organization\n\tif !funk.ContainsString(x509CSR.Subject.Organization, nodeGroup) {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: Organization %v doesn't include %s\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tx509CSR.Subject.Organization, nodeGroup)\n\t}\n\n\t// CN and Username must be equal\n\tif x509CSR.Subject.CommonName != csr.Spec.Username {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: Mismatched CommonName %s != %s for CSR %s\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tx509CSR.Subject.CommonName, csr.Spec.Username, csr.Name)\n\t}\n\tnodeDNSNames := append(getNodeDNSNames(node), node.Name)\n\n\t// Any DNS name in CSR must exist in the nodeDNSNames\n\t// TODO: May need to modify for IPv6 only node\n\tfor _, dnsName := range x509CSR.DNSNames {\n\t\tif !funk.ContainsString(nodeDNSNames, dnsName) {\n\t\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: DNS name %s missing from available DNS names %v\", csr.Name, agent.Namespace, agent.Name,\n\t\t\t\tdnsName, nodeDNSNames)\n\t\t}\n\t}\n\tnodeIPs := getNodeIPs(node)\n\t// Any IP address in CSR must exist in nodeIPs\n\tfor _, ip := range x509CSR.IPAddresses {\n\t\tif !funk.ContainsString(nodeIPs, ip.String()) {\n\t\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: IP address %s missing from available node IPs %v\", csr.Name, agent.Namespace, agent.Name,\n\t\t\t\tip.String(), nodeIPs)\n\t\t}\n\t}\n\treturn true, nil\n}", "func AddNode(namespace string, clusterName string, req *app.NodeReq) (*model.NodeList, error) {\n\n\t// validate namespace\n\tif err := verifyNamespace(namespace); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get a cluster-entity\n\tcluster := model.NewCluster(namespace, clusterName)\n\tif exists, err := cluster.Select(); err != nil {\n\t\treturn nil, err\n\t} else if exists == false {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Could not be found a cluster '%s'. (namespace=%s)\", clusterName, namespace))\n\t} else if cluster.Status.Phase != model.ClusterPhaseProvisioned {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Unable to add a node. status is '%s'.\", cluster.Status.Phase))\n\t}\n\n\t// get a MCIS\n\tmcis := tumblebug.NewMCIS(namespace, cluster.MCIS)\n\tif exists, err := mcis.GET(); err != nil {\n\t\treturn nil, err\n\t} else if !exists {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Can't be found a MCIS '%s'.\", cluster.MCIS))\n\t}\n\tlogger.Infof(\"[%s.%s] The inquiry has been completed..\", namespace, clusterName)\n\n\tmcisName := cluster.MCIS\n\n\tif cluster.ServiceType == app.ST_SINGLE {\n\t\tif len(mcis.VMs) > 0 {\n\t\t\tconnection := mcis.VMs[0].Config\n\t\t\tfor _, worker := range req.Worker {\n\t\t\t\tif worker.Connection != connection {\n\t\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"The new node must be the same connection config. (connection=%s)\", worker.Connection))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"There is no VMs. (cluster=%s)\", clusterName))\n\t\t}\n\t}\n\n\t// get a provisioner\n\tprovisioner := provision.NewProvisioner(cluster)\n\n\t/*\n\t\tif err := provisioner.BuildAllMachines(); err != nil {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to build provisioner's map: %v\", err))\n\t\t}\n\t*/\n\n\t// get join command\n\tworkerJoinCmd, err := provisioner.NewWorkerJoinCommand()\n\tif err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to get join-command (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Worker join-command inquiry has been completed. (command=%s)\", namespace, clusterName, workerJoinCmd)\n\n\tvar workerCSP app.CSP\n\n\t// create a MCIR & MCIS-vm\n\tidx := cluster.NextNodeIndex(app.WORKER)\n\tvar vmgroupid []string\n\tfor _, worker := range req.Worker {\n\t\tmcir := NewMCIR(namespace, app.WORKER, *worker)\n\t\treason, msg := mcir.CreateIfNotExist()\n\t\tif reason != \"\" {\n\t\t\treturn nil, errors.New(msg)\n\t\t} else {\n\t\t\tfor i := 0; i < mcir.vmCount; i++ {\n\t\t\t\tname := lang.GenerateNewNodeName(string(app.WORKER), idx)\n\t\t\t\tif i == 0 {\n\t\t\t\t\tworkerCSP = mcir.csp\n\t\t\t\t}\n\t\t\t\tvm := mcir.NewVM(namespace, name, mcisName, \"\", worker.RootDisk.Type, worker.RootDisk.Size)\n\t\t\t\tif err := vm.POST(); err != nil {\n\t\t\t\t\tcleanUpNodes(*provisioner)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tvmgroupid = append(vmgroupid, name)\n\t\t\t\tprovisioner.AppendWorkerNodeMachine(name+\"-1\", mcir.csp, mcir.region, mcir.zone, mcir.credential)\n\t\t\t\tidx = idx + 1\n\t\t\t}\n\t\t}\n\t}\n\t// Pull out the added VMlist\n\tif _, err := mcis.GET(); err != nil {\n\t\treturn nil, err\n\t}\n\tvms := []tumblebug.VM{}\n\tfor _, mcisvm := range mcis.VMs {\n\t\tfor _, grupid := range vmgroupid {\n\t\t\tif mcisvm.VmGroupId == grupid {\n\t\t\t\tmcisvm.Namespace = namespace\n\t\t\t\tmcisvm.McisName = mcisName\n\t\t\t\tvms = append(vms, mcisvm)\n\t\t\t}\n\t\t}\n\t}\n\tlogger.Infof(\"[%s.%s] MCIS(vm) creation has been completed. (len=%d)\", namespace, clusterName, len(vms))\n\n\t// save nodes metadata\n\tif nodes, err := provisioner.BindVM(vms); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tcluster.Nodes = append(cluster.Nodes, nodes...)\n\t\tif err := cluster.PutStore(); err != nil {\n\t\t\tcleanUpNodes(*provisioner)\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity. (cause='%v')\", err))\n\t\t}\n\t}\n\n\t// kubernetes provisioning : bootstrap\n\ttime.Sleep(2 * time.Second)\n\tif err := provisioner.Bootstrap(); err != nil {\n\t\tcleanUpNodes(*provisioner)\n\t\treturn nil, errors.New(fmt.Sprintf(\"Bootstrap failed. (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Bootstrap has been completed.\", namespace, clusterName)\n\n\t// kubernetes provisioning : worker node join\n\tfor _, machine := range provisioner.WorkerNodeMachines {\n\t\tif err := machine.JoinWorker(&workerJoinCmd); err != nil {\n\t\t\tcleanUpNodes(*provisioner)\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Fail to worker-node join. (node=%s)\", machine.Name))\n\t\t}\n\t}\n\tlogger.Infof(\"[%s.%s] Woker-nodes join has been completed.\", namespace, clusterName)\n\n\t/* FIXME: after joining, check the worker is ready */\n\n\t// assign node labels (topology.cloud-barista.github.io/csp , topology.kubernetes.io/region, topology.kubernetes.io/zone)\n\tif err = provisioner.AssignNodeLabelAnnotation(); err != nil {\n\t\tlogger.Warnf(\"[%s.%s] Failed to assign node labels (cause='%v')\", namespace, clusterName, err)\n\t} else {\n\t\tlogger.Infof(\"[%s.%s] Node label assignment has been completed.\", namespace, clusterName)\n\t}\n\n\t// kubernetes provisioning : add some actions for cloud-controller-manager\n\tif provisioner.Cluster.ServiceType == app.ST_SINGLE {\n\t\tif workerCSP == app.CSP_AWS {\n\t\t\t// check whether AWS IAM roles exists and are same\n\t\t\tvar bFail bool = false\n\t\t\tvar bEmptyOrDiff bool = false\n\t\t\tvar msgError string\n\t\t\tvar awsWorkerRole string\n\n\t\t\tawsWorkerRole = req.Worker[0].Role\n\t\t\tif awsWorkerRole == \"\" {\n\t\t\t\tbEmptyOrDiff = true\n\t\t\t}\n\n\t\t\tif bEmptyOrDiff == false {\n\t\t\t\tfor _, worker := range req.Worker {\n\t\t\t\t\tif awsWorkerRole != worker.Role {\n\t\t\t\t\t\tbEmptyOrDiff = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif bEmptyOrDiff == true {\n\t\t\t\tbFail = true\n\t\t\t\tmsgError = \"Role should be assigned\"\n\t\t\t} else {\n\t\t\t\tif err := awsPrepareCCM(req.Worker[0].Connection, clusterName, vms, provisioner, \"\", awsWorkerRole); err != nil {\n\t\t\t\t\tbFail = true\n\t\t\t\t\tmsgError = \"Failed to prepare cloud-controller-manager\"\n\t\t\t\t} else {\n\t\t\t\t\t// Success\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif bFail == true {\n\t\t\t\tcleanUpNodes(*provisioner)\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity: %v)\", msgError))\n\t\t\t} else {\n\t\t\t\t// Success\n\t\t\t\tlogger.Infof(\"[%s.%s] CCM ready has been completed.\", namespace, clusterName)\n\t\t\t}\n\t\t}\n\t}\n\n\t// save nodes metadata & update status\n\tfor _, node := range cluster.Nodes {\n\t\tnode.CreatedTime = lang.GetNowUTC()\n\t}\n\tif err := cluster.PutStore(); err != nil {\n\t\tcleanUpNodes(*provisioner)\n\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity. (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Nodes creation has been completed.\", namespace, clusterName)\n\n\tnodes := model.NewNodeList(namespace, clusterName)\n\tnodes.Items = cluster.Nodes\n\treturn nodes, nil\n}", "func (body *AddRequestBody) Validate() (err error) {\n\tif body.Token == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"token\", \"body\"))\n\t}\n\treturn\n}", "func resourceNodeV1Create(d *schema.ResourceData, meta interface{}) error {\n\tclient, err := meta.(*Clients).GetIronicClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create the node object in Ironic\n\tcreateOpts := schemaToCreateOpts(d)\n\tresult, err := nodes.Create(client, createOpts).Extract()\n\tif err != nil {\n\t\td.SetId(\"\")\n\t\treturn err\n\t}\n\n\t// Setting the ID is what tells terraform we were successful in creating the node\n\tlog.Printf(\"[DEBUG] Node created with ID %s\\n\", d.Id())\n\td.SetId(result.UUID)\n\n\t// Create ports as part of the node object - you may also use the native port resource\n\tportSet := d.Get(\"ports\").(*schema.Set)\n\tif portSet != nil {\n\t\tportList := portSet.List()\n\t\tfor _, portInterface := range portList {\n\t\t\tport := portInterface.(map[string]interface{})\n\n\t\t\t// Terraform map can't handle bool... seriously.\n\t\t\tvar pxeEnabled bool\n\t\t\tif port[\"pxe_enabled\"] != nil {\n\t\t\t\tif port[\"pxe_enabled\"] == \"true\" {\n\t\t\t\t\tpxeEnabled = true\n\t\t\t\t} else {\n\t\t\t\t\tpxeEnabled = false\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t// FIXME: All values other than address and pxe\n\t\t\tportCreateOpts := ports.CreateOpts{\n\t\t\t\tNodeUUID: d.Id(),\n\t\t\t\tAddress: port[\"address\"].(string),\n\t\t\t\tPXEEnabled: &pxeEnabled,\n\t\t\t}\n\t\t\t_, err := ports.Create(client, portCreateOpts).Extract()\n\t\t\tif err != nil {\n\t\t\t\t_ = resourcePortV1Read(d, meta)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Make node manageable\n\tif d.Get(\"manage\").(bool) || d.Get(\"clean\").(bool) || d.Get(\"inspect\").(bool) {\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"manage\", nil, nil, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"could not manage: %s\", err)\n\t\t}\n\t}\n\n\t// Clean node\n\tif d.Get(\"clean\").(bool) {\n\t\tif err := setRAIDConfig(client, d); err != nil {\n\t\t\treturn fmt.Errorf(\"fail to set raid config: %s\", err)\n\t\t}\n\n\t\tvar cleanSteps []nodes.CleanStep\n\t\tif cleanSteps, err = buildManualCleaningSteps(d.Get(\"raid_interface\").(string), d.Get(\"raid_config\").(string), d.Get(\"bios_settings\").(string)); err != nil {\n\t\t\treturn fmt.Errorf(\"fail to build raid clean steps: %s\", err)\n\t\t}\n\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"clean\", nil, nil, cleanSteps); err != nil {\n\t\t\treturn fmt.Errorf(\"could not clean: %s\", err)\n\t\t}\n\t}\n\n\t// Inspect node\n\tif d.Get(\"inspect\").(bool) {\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"inspect\", nil, nil, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"could not inspect: %s\", err)\n\t\t}\n\t}\n\n\t// Make node available\n\tif d.Get(\"available\").(bool) {\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"provide\", nil, nil, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"could not make node available: %s\", err)\n\t\t}\n\t}\n\n\t// Change power state, if required\n\tif targetPowerState := d.Get(\"target_power_state\").(string); targetPowerState != \"\" {\n\t\terr := changePowerState(client, d, nodes.TargetPowerState(targetPowerState))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not change power state: %s\", err)\n\t\t}\n\t}\n\n\treturn resourceNodeV1Read(d, meta)\n}", "func NewAddRemoteRDSNodeOK() *AddRemoteRDSNodeOK {\n\treturn &AddRemoteRDSNodeOK{}\n}", "func (nS *PostMessageBody) Validate() error {\n\treturn validator.New().Struct(nS)\n}", "func (o *VolumeCreateBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (r *Node) validate() field.ErrorList {\n\tvar nodeErrors field.ErrorList\n\n\tif r.Spec.Validator {\n\t\t// validate rpc must be disabled if node is validator\n\t\tif r.Spec.RPC {\n\t\t\terr := field.Invalid(field.NewPath(\"spec\").Child(\"rpc\"), r.Spec.RPC, \"must be false if node is validator\")\n\t\t\tnodeErrors = append(nodeErrors, err)\n\t\t}\n\t\t// validate ws must be disabled if node is validator\n\t\tif r.Spec.WS {\n\t\t\terr := field.Invalid(field.NewPath(\"spec\").Child(\"ws\"), r.Spec.WS, \"must be false if node is validator\")\n\t\t\tnodeErrors = append(nodeErrors, err)\n\t\t}\n\t\t// validate pruning must be disabled if node is validator\n\t\tif pruning := r.Spec.Pruning; pruning != nil && *pruning {\n\t\t\terr := field.Invalid(field.NewPath(\"spec\").Child(\"pruning\"), r.Spec.Pruning, \"must be false if node is validator\")\n\t\t\tnodeErrors = append(nodeErrors, err)\n\t\t}\n\n\t}\n\n\treturn nodeErrors\n}", "func (o *PostServiceListenerPortsOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *CiNode) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateAvailable(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLastLeaseTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateVpnIP(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *RepoMigrateCreatedBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateCloneURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateDefaultBranch(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateDescription(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateEmpty(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateFork(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateForks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateFullName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateHTMLURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateMirror(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateOpenIssues(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePrivate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSSHURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSize(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateStars(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateUpdated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateWatchers(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateWebsite(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateOwner(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateParent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePermissions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (config *AppConfig) CreateNode(newNode NodeAttributes) (node Node, err error) {\n\tendpoint := fmt.Sprintf(\"nodes/\")\n\n\tnewNodeBytes, err := json.Marshal(newNode)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// get json bytes from the panel.\n\tnodeBytes, err := config.queryApplicationAPI(endpoint, \"post\", newNodeBytes)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Get server info from the panel\n\t// Unmarshal the bytes to a usable struct.\n\terr = json.Unmarshal(nodeBytes, &node)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func newAddnode() *cobra.Command {\n\tvar cluster []string\n\tvar address string\n\t//var role string\n\tvar timeout time.Duration\n\n\troles := map[string]int{\n\t\tclient.Voter.String(): int(Voter),\n\t\tclient.Spare.String(): int(Spare),\n\t\tclient.StandBy.String(): int(Standby),\n\t}\n\tchoices := &FlagChoice{choices: mapKeys(roles), chosen: client.Voter.String()}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"add\",\n\t\tShort: \"Add a node to the cluster.\",\n\t\tArgs: cobra.MinimumNArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tid, err := strconv.ParseUint(args[0], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\t\t\trole, err := nodeRole(choices.chosen)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\t\t\tdefer cancel()\n\n\t\t\tclient, err := getLeader(ctx, &globalKeys, cluster)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\n\t\t\tif err := nodeAdd(ctx, client, id, role, address); err != nil {\n\t\t\t\tlog.Fatalln(\"error adding node:\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tflags.StringSliceVarP(&cluster, \"cluster\", \"c\", clusterList(), \"addresses of existing cluster nodes\")\n\tflags.StringVarP(&address, \"address\", \"a\", envy.StringDefault(\"DQLITED_ADDRESS\", \"127.0.0.1:9181\"), \"address of the node (default is 127.0.0.1:918<ID>)\")\n\tflags.VarP(choices, \"role\", \"r\", \"server role\")\n\tflags.DurationVarP(&timeout, \"timeout\", \"t\", time.Minute*5, \"time to wait for connection to complete\")\n\n\treturn cmd\n}", "func (d *portworx) ValidateNodeAfterPickingUpNodeID(delNode *api.StorageNode, newNode *api.StorageNode, storagelessNodes []*api.StorageNode) error {\n\t// If node is a storageless node below validation steps not needed\n\tif !d.validateNodeIDMigration(delNode, newNode, storagelessNodes) {\n\t\treturn fmt.Errorf(\"validation failed: NodeId: [%s] pick-up failed by new Node: [%s]\", delNode.Id, newNode.Hostname)\n\t}\n\n\tlog.Infof(\"Pools and Disks are matching after new node:[%s] picked the NodeId: [%s]\", newNode.Hostname, newNode.Id)\n\tlog.Infof(\"After recyling a node, Node [%s] is having following pools:\", newNode.Hostname)\n\tfor _, pool := range newNode.Pools {\n\t\tlog.Infof(\"Node [%s] is having pool id: [%s]\", newNode.Hostname, pool.Uuid)\n\t}\n\n\tlog.Infof(\"After recyling a node, Node [%s] is having disks: [%v]\", newNode.Hostname, newNode.Disks)\n\treturn nil\n}", "func (o *PostLeasesIDAuthCreatedBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (suite *TestAgentItSuite) TestAddNewAgent(c *C) {\n\tjsonBody := &struct {\n\t\tName string `json:\"name\"`\n\t\tHostname string `json:\"hostname\"`\n\t\tConnectionId string `json:\"connection_id\"`\n\t\tStatus bool `json:status`\n\t\tComment string `json:\"comment\"`\n\t\tIspId int `json:\"isp_id\"`\n\t\tProvinceId int `json:\"province_id\"`\n\t\tCityId int `json:\"city_id\"`\n\t\tNameTag string `json:\"name_tag\"`\n\t\tGroupTags []string `json:\"group_tags\"`\n\t} {\n\t\tName: \"new-agent-ccc\",\n\t\tHostname: \"new-host-cccc\",\n\t\tStatus: true,\n\t\tConnectionId: \"new-agent@blue.12.91.33\",\n\t\tComment: \"This is new agent by blue 12.91 ***\",\n\t\tIspId: 8,\n\t\tProvinceId: 9,\n\t\tCityId: 130,\n\t\tNameTag: \"rest-nt-1\",\n\t\tGroupTags: []string{ \"pp-rest-tag-1\", \"pp-rest-tag-2\" },\n\t}\n\n\ttestCases := []struct {\n\t\texpectedStatus int\n\t\texpectedErrorCode int\n\t} {\n\t\t{ http.StatusOK, -1 },\n\t\t{ http.StatusConflict, 1 },\n\t}\n\n\tfor _, testCase := range testCases {\n\t\tclient := sling.New().Post(httpClientConfig.String()).\n\t\t\tPath(\"/api/v1/nqm/agent\").\n\t\t\tBodyJSON(jsonBody)\n\n\t\tslintChecker := testingHttp.NewCheckSlint(c, client)\n\n\t\tjsonResp := slintChecker.GetJsonBody(testCase.expectedStatus)\n\n\t\tc.Logf(\"[Add Agent] JSON Result: %s\", json.MarshalPrettyJSON(jsonResp))\n\n\t\tswitch testCase.expectedStatus {\n\t\tcase http.StatusConflict:\n\t\t\tc.Assert(jsonResp.Get(\"error_code\").MustInt(), Equals, testCase.expectedErrorCode)\n\t\t}\n\n\t\tif testCase.expectedStatus != http.StatusOK {\n\t\t\tcontinue\n\t\t}\n\n\t\tc.Assert(jsonResp.Get(\"name\").MustString(), Equals, jsonBody.Name)\n\t\tc.Assert(jsonResp.Get(\"connection_id\").MustString(), Equals, jsonBody.ConnectionId)\n\t\tc.Assert(jsonResp.Get(\"ip_address\").MustString(), Equals, \"0.0.0.0\")\n\t\tc.Assert(jsonResp.Get(\"hostname\").MustString(), Equals, jsonBody.Hostname)\n\t\tc.Assert(jsonResp.Get(\"comment\").MustString(), Equals, jsonBody.Comment)\n\t\tc.Assert(jsonResp.Get(\"status\").MustBool(), Equals, jsonBody.Status)\n\t\tc.Assert(jsonResp.Get(\"isp\").Get(\"id\").MustInt(), Equals, jsonBody.IspId)\n\t\tc.Assert(jsonResp.Get(\"province\").Get(\"id\").MustInt(), Equals, jsonBody.ProvinceId)\n\t\tc.Assert(jsonResp.Get(\"city\").Get(\"id\").MustInt(), Equals, jsonBody.CityId)\n\t\tc.Assert(jsonResp.Get(\"name_tag\").Get(\"value\").MustString(), Equals, jsonBody.NameTag)\n\t\tc.Assert(jsonResp.Get(\"group_tags\").MustArray(), HasLen, len(jsonBody.GroupTags))\n\t}\n}", "func (m *StoragepoolNodepool) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (body *CreateResponseBody) Validate() (err error) {\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Color == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"color\", \"body\"))\n\t}\n\tif body.Cron == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"cron\", \"body\"))\n\t}\n\tif body.Name != nil {\n\t\tif utf8.RuneCountInString(*body.Name) > 100 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(\"body.name\", *body.Name, utf8.RuneCountInString(*body.Name), 100, false))\n\t\t}\n\t}\n\tif body.Color != nil {\n\t\tif !(*body.Color == \"red\" || *body.Color == \"yellow\" || *body.Color == \"green\" || *body.Color == \"off\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"body.color\", *body.Color, []interface{}{\"red\", \"yellow\", \"green\", \"off\"}))\n\t\t}\n\t}\n\treturn\n}", "func (n *NetworkBuilder) AddNode(nodeID string, subnet string, port uint, forceHidden bool) (*NetworkBuilder, error) {\n\tn.NodeID = nodeID\n\n\tif subnet == \"\" {\n\t\treturn n, fmt.Errorf(\"subnet cannot be empty\")\n\t}\n\tipnet, err := types.ParseIPNet(subnet)\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"invalid subnet\")\n\t}\n\n\tif port == 0 {\n\t\tport, err = n.pickPort()\n\t\tif err != nil {\n\t\t\treturn n, errors.Wrap(err, \"failed to pick wireguard port\")\n\t\t}\n\t}\n\n\tprivateKey, err := wgtypes.GeneratePrivateKey()\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"error during wireguard key generation\")\n\t}\n\tsk := privateKey.String()\n\n\tpk, err := crypto.KeyFromID(pkg.StrIdentifier(nodeID))\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"failed to parse nodeID\")\n\t}\n\n\tencrypted, err := crypto.Encrypt([]byte(sk), pk)\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"failed to encrypt private key\")\n\t}\n\n\tpubSubnets, err := n.getEndPointAddrs(pkg.StrIdentifier(nodeID))\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"failed to get node public endpoints\")\n\t}\n\tvar endpoints []net.IP\n\tif !forceHidden {\n\t\tfor _, sn := range pubSubnets {\n\t\t\tendpoints = append(endpoints, sn.IP)\n\t\t}\n\t}\n\n\tnr := NetResource{\n\t\tNetworkNetResource: workloads.NetworkNetResource{\n\t\t\tNodeId: nodeID,\n\t\t\tIprange: schema.IPRange{ipnet.IPNet},\n\t\t\tWireguardListenPort: int64(port),\n\t\t\tWireguardPublicKey: privateKey.PublicKey().String(),\n\t\t\tWireguardPrivateKeyEncrypted: hex.EncodeToString(encrypted),\n\t\t},\n\t\tPubEndpoints: endpoints,\n\t}\n\n\tn.NetResources = append(n.NetResources, nr)\n\n\tif err = n.generatePeers(); err != nil {\n\t\treturn n, errors.Wrap(err, \"failed to generate peers\")\n\t}\n\n\treturn n, nil\n}", "func (o *AddPMMAgentOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validatePMMAgent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (s *NodesInfoService) Validate() error {\n\treturn nil\n}", "func NodeUpdate(w http.ResponseWriter, r *http.Request) {\n\tvar n swl.Node\n\tvar nameChanged bool\n\tvar ipChanged bool\n\n\tbody, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err := r.Body.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif !swl.ValidateAndUnmarshalJSON(body, &n, w) {\n\t\treturn\n\t}\n\n\tif n.Name != nil {\n\t\tnameChanged = true\n\t}\n\n\tif n.IP != nil {\n\t\tif !swl.ValidateParamRegex(\"ip\", node.IP,\n\t\t\t\"\\\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\\\.|$)){4}\\\\b\", w) {\n\t\t\treturn\n\t\t}\n\t\tipChanged = true\n\t}\n\n\tif nameChanged {\n\t\tnode.Name = n.Name\n\t}\n\tif ipChanged {\n\t\tnode.IP = n.IP\n\t}\n\tw.Header().Set(\"Content-Type\", \"appliation/json; charset=UTF-8\")\n\tw.WriteHeader(200)\n\tif err := json.NewEncoder(w).Encode(node); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (m *NodeHealthDetails) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateInstanceID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateIssues(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateStatus(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *ServiceCreateCreatedBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (zic *ZoneInterconnectHandler) AddRemoteZoneNode(node *corev1.Node) error {\n\tklog.Infof(\"Creating interconnect resources for remote zone node %s for the network %s\", node.Name, zic.GetNetworkName())\n\n\tnodeID := util.GetNodeID(node)\n\tif nodeID == -1 {\n\t\t// Don't consider this node as cluster-manager has not allocated node id yet.\n\t\treturn fmt.Errorf(\"failed to get node id for node - %s\", node.Name)\n\t}\n\n\t// Get the chassis id.\n\tchassisId, err := util.ParseNodeChassisIDAnnotation(node)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse node chassis-id for node - %s, error: %w\", node.Name, err)\n\t}\n\n\tif err := zic.createRemoteZoneNodeResources(node, nodeID, chassisId); err != nil {\n\t\treturn fmt.Errorf(\"creating interconnect resources for remote zone node %s for the network %s failed : err - %w\", node.Name, zic.GetNetworkName(), err)\n\t}\n\n\treturn nil\n}", "func AddReplicationTarget(nbmaster string, httpClient *http.Client, jwt string, stsName string, candId string)(int) {\n fmt.Printf(\"\\nSending a POST request to create with defaults...\\n\")\n\n\t//reader := bufio.NewReader(os.Stdin)\n\tIdSlice := strings.Split(candId, \":\")\n\n username := apiUtil.TakeInput(\"Enter target storage server username:\")\n\tpassword := apiUtil.TakeInput(\"Enter target storage server password:\")\n\n replicationtarget := map[string]interface{}{\n \"data\": map[string]interface{}{\n \"type\": \"replicationTargetRequest\",\n \"attributes\": map[string]interface{}{\n\t\t\t\t\"targetStorageServerInfo\": map[string]interface{}{\n \"targetMasterServer\": IdSlice[3],\n\t\t\t\t\t\"targetStorageServer\": IdSlice[1],\n\t\t\t\t\t\"targetStorageServerType\": IdSlice[0],\n\t\t\t\t\t\"targetMediaServer\": IdSlice[2]},\n\t\t\t\t\"targetStorageServerCredentials\": map[string]interface{}{\n\t\t\t\t\t\"userName\": username,\n\t\t\t\t\t\"password\": password}}}}\n\t\t\t\t\n\n\n stsRequest, _ := json.Marshal(replicationtarget)\n\n uri := \"https://\" + nbmaster + \":\" + port + \"/netbackup/\" + storageUri + storageServerUri + \"PureDisk:\" + stsName + replicationTargetsUri\n\n request, _ := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(stsRequest))\n request.Header.Add(\"Content-Type\", contentType);\n request.Header.Add(\"Authorization\", jwt);\n\n fmt.Println (\"Firing request: POST: \" + uri)\n response, err := httpClient.Do(request)\n\n if err != nil {\n fmt.Printf(\"The HTTP request failed with error: %s\\n\", err)\n panic(\"Unable to add replication target.\\n\")\n } else {\n if response.StatusCode != 201 {\n responseBody, _ := ioutil.ReadAll(response.Body)\n fmt.Printf(\"%s\\n\", responseBody)\n panic(\"Unable to add replication target.\\n\")\n } else {\n fmt.Printf(\"%s created successfully.\\n\", \"\");\n //responseDetails, _ := httputil.DumpResponse(response, true);\n apiUtil.AskForResponseDisplay(response.Body)\n }\n }\n\t\n\treturn response.StatusCode;\n}", "func (self *CentralBooking) RegisterInstance(resp http.ResponseWriter, req *http.Request) {\n var err error\n var remoteAddr string\n \n if xff, ok := req.Header[\"X-Forwarded-For\"]; ok {\n remoteAddr = xff[0]\n } else {\n remoteAddr, _, err = net.SplitHostPort(req.RemoteAddr)\n if err != nil {\n log.Errorf(\"unable to parse RemoteAddr: %s\", err)\n remoteAddr = req.RemoteAddr\n }\n }\n \n logEntry := log.WithField(\"remote_ip\", remoteAddr)\n \n type payloadType struct {\n Environment string\n Provider string\n Account string\n Region string\n Instance_ID string\n Role string\n Policies []string\n }\n \n var payload payloadType\n\n body, err := ioutil.ReadAll(req.Body)\n if err != nil {\n log.Errorf(\"unable to read body: %s\", err)\n http.Error(resp, \"unable to read body\", http.StatusBadRequest)\n return\n }\n \n err = json.Unmarshal(body, &payload)\n if err != nil {\n log.Errorf(\"unable to decode payload: %s\", err)\n http.Error(resp, \"unable to decode payload\", http.StatusBadRequest)\n return\n }\n \n logEntry.Info(\"registering instance\")\n regResp, err := self.registrar.Register(&instance.RegisterRequest{\n Env: payload.Environment,\n Provider: payload.Provider,\n Account: payload.Account,\n Region: payload.Region,\n InstanceID: payload.Instance_ID,\n Role: payload.Role,\n Policies: payload.Policies,\n })\n \n if err != nil {\n sc := http.StatusInternalServerError\n \n if _, ok := err.(*instance.ValidationError); ok {\n sc = http.StatusBadRequest\n }\n \n http.Error(resp, err.Error(), sc)\n return\n }\n\n svcs, _, err := self.consulCatalog.Service(\"consul-wan\", \"\", nil)\n if err != nil {\n log.Errorf(\"unable to retrieve consul-wan service: %s\", err)\n http.Error(resp, \"unable to retrieve consul-wan service\", http.StatusInternalServerError)\n return\n }\n\n consulServers := make([]string, 0, len(svcs))\n for _, svc := range svcs {\n consulServers = append(consulServers, fmt.Sprintf(\"%s:%d\", svc.ServiceAddress, svc.ServicePort))\n }\n\n respBytes, err := json.Marshal(map[string]interface{}{\n \"temp_token\": regResp.TempToken,\n \"vault_endpoint\": self.vaultEndpoint,\n \"consul_servers\": consulServers,\n })\n if err != nil {\n log.Errorf(\"unable to marshal response body: %s\", err)\n http.Error(resp, \"failed generating response body\", http.StatusInternalServerError)\n return\n }\n\n resp.Header().Add(\"Content-Type\", \"application/json\")\n resp.WriteHeader(http.StatusOK)\n resp.Write(respBytes)\n}", "func (api *nodeAPI) Create(obj *cluster.Node) error {\n\tif api.ct.resolver != nil {\n\t\tapicl, err := api.ct.apiClient()\n\t\tif err != nil {\n\t\t\tapi.ct.logger.Errorf(\"Error creating API server clent. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = apicl.ClusterV1().Node().Create(context.Background(), obj)\n\t\tif err != nil && strings.Contains(err.Error(), \"AlreadyExists\") {\n\t\t\t_, err = apicl.ClusterV1().Node().Update(context.Background(), obj)\n\n\t\t}\n\t\treturn err\n\t}\n\n\tapi.ct.handleNodeEvent(&kvstore.WatchEvent{Object: obj, Type: kvstore.Created})\n\treturn nil\n}", "func RegisterNodeToMaster(UID, nodehandler, nodeselector string) error {\n\tbody, err := GenerateNodeReqBody(UID, nodeselector)\n\tif err != nil {\n\t\tFatalf(\"Unmarshal body failed: %v\", err)\n\t\treturn err\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{\n\t\tTransport: tr,\n\t}\n\n\tt := time.Now()\n\tnodebody, err := json.Marshal(body)\n\tif err != nil {\n\t\tFatalf(\"Marshal body failed: %v\", err)\n\t\treturn err\n\t}\n\tBodyBuf := bytes.NewReader(nodebody)\n\treq, err := http.NewRequest(http.MethodPost, nodehandler, BodyBuf)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tif err != nil {\n\t\tFatalf(\"Frame HTTP request failed: %v\", err)\n\t\treturn err\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tFatalf(\"Sending HTTP request failed: %v\", err)\n\t\treturn err\n\t}\n\tInfof(\"%s %s %v in %v\", req.Method, req.URL, resp.Status, time.Since(t))\n\tdefer resp.Body.Close()\n\n\tgomega.Expect(resp.StatusCode).Should(gomega.Equal(http.StatusCreated))\n\treturn nil\n}", "func AddCounterNode(w http.ResponseWriter, r *http.Request) {\n\t//params := mux.Vars(r)\n\tvar node CounterNode\n\t_ = json.NewDecoder(r.Body).Decode(&node)\n\tvar nodeExists = false\n\tfor _, value := range counternodes {\n\t\tif value == node.ID {\n\t\t\tnodeExists = true\n\t\t\tbreak\n\t\t}\n\t}\n\t//Dont add the node if its already exist\n\tif nodeExists == false {\n\t\tcounternodes[node.EndPoint] = node.ID\n\t\t\n\t\tfmt.Println(\"node added : \" + node.EndPoint + \" : \" + node.ID)\n\t\tw.WriteHeader(http.StatusOK)\n\t} else {\n\t\tfmt.Println(\"node already exists : \" + node.EndPoint + \" : \" + node.ID)\n\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t}\n\n\t//json.NewEncoder(w).Encode(Message{ID : id, Count : read(id)})\n}", "func ValidateAddRequestBody(body *AddRequestBody) (err error) {\n\tif body.Resource == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"resource\", \"body\"))\n\t}\n\tif body.Action == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"action\", \"body\"))\n\t}\n\treturn\n}", "func handleAddManualNode(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {\n\tc := cmd.(*rpcmodel.AddManualNodeCmd)\n\n\toneTry := c.OneTry != nil && *c.OneTry\n\n\taddr, err := network.NormalizeAddress(c.Addr, s.cfg.DAGParams.DefaultPort)\n\tif err != nil {\n\t\treturn nil, &rpcmodel.RPCError{\n\t\t\tCode: rpcmodel.ErrRPCInvalidParameter,\n\t\t\tMessage: err.Error(),\n\t\t}\n\t}\n\n\tif oneTry {\n\t\terr = s.cfg.ConnMgr.Connect(addr, false)\n\t} else {\n\t\terr = s.cfg.ConnMgr.Connect(addr, true)\n\t}\n\n\tif err != nil {\n\t\treturn nil, &rpcmodel.RPCError{\n\t\t\tCode: rpcmodel.ErrRPCInvalidParameter,\n\t\t\tMessage: err.Error(),\n\t\t}\n\t}\n\n\t// no data returned unless an error.\n\treturn nil, nil\n}", "func (s ServerCmd) Validate() error {\n\treturn nil\n}", "func (zic *ZoneInterconnectHandler) AddRemoteZoneNode(node *corev1.Node) error {\n\tstart := time.Now()\n\tklog.Infof(\"Creating interconnect resources for remote zone node %s for the network %s\", node.Name, zic.GetNetworkName())\n\n\tnodeID := util.GetNodeID(node)\n\tif nodeID == -1 {\n\t\t// Don't consider this node as cluster-manager has not allocated node id yet.\n\t\treturn fmt.Errorf(\"failed to get node id for node - %s\", node.Name)\n\t}\n\n\t// Get the chassis id.\n\tchassisId, err := util.ParseNodeChassisIDAnnotation(node)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse node chassis-id for node - %s, error: %w\", node.Name, types.NewSuppressedError(err))\n\t}\n\n\tif err := zic.createRemoteZoneNodeResources(node, nodeID, chassisId); err != nil {\n\t\treturn fmt.Errorf(\"creating interconnect resources for remote zone node %s for the network %s failed : err - %w\", node.Name, zic.GetNetworkName(), err)\n\t}\n\tklog.Infof(\"Creating Interconnect resources for node %v took: %s\", node.Name, time.Since(start))\n\treturn nil\n}", "func (_PermInterface *PermInterfaceTransactor) AddNode(opts *bind.TransactOpts, _orgId string, _enodeId string, _ip string, _port uint16, _raftport uint16) (*types.Transaction, error) {\n\treturn _PermInterface.contract.Transact(opts, \"addNode\", _orgId, _enodeId, _ip, _port, _raftport)\n}", "func ValidateAddRequestBody(body *AddRequestBody) (err error) {\n\tif body.Step != nil {\n\t\tif err2 := ValidateStepRequestBody(body.Step); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\treturn\n}", "func (s SubnetArgs) validate() error {\n\tif s.isEmpty() {\n\t\treturn nil\n\t}\n\treturn s.FromTags.validate()\n}", "func (m *NodePoolUpdate) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateInstanceTypes(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (p *Pacemaker) AddNode(rid uint64, cli TiKVClient) {\n\tlg.Debug(\"add tikv client to txn\", zap.Uint64(\"txnid\", p.txnid))\n\tp.Lock()\n\tif _, ok := p.kvnodes[rid]; !ok {\n\t\tp.kvnodes[rid] = cli\n\t}\n\tp.Unlock()\n}", "func (nc *NodeCreate) check() error {\n\tif _, ok := nc.mutation.UUID(); !ok {\n\t\treturn &ValidationError{Name: \"uuid\", err: errors.New(\"ent: missing required field \\\"uuid\\\"\")}\n\t}\n\tif _, ok := nc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(\"ent: missing required field \\\"name\\\"\")}\n\t}\n\tif _, ok := nc.mutation.Metadata(); !ok {\n\t\treturn &ValidationError{Name: \"metadata\", err: errors.New(\"ent: missing required field \\\"metadata\\\"\")}\n\t}\n\tif _, ok := nc.mutation.Desc(); !ok {\n\t\treturn &ValidationError{Name: \"desc\", err: errors.New(\"ent: missing required field \\\"desc\\\"\")}\n\t}\n\tif _, ok := nc.mutation.CreateAt(); !ok {\n\t\treturn &ValidationError{Name: \"create_at\", err: errors.New(\"ent: missing required field \\\"create_at\\\"\")}\n\t}\n\tif _, ok := nc.mutation.UpdatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"updated_at\", err: errors.New(\"ent: missing required field \\\"updated_at\\\"\")}\n\t}\n\treturn nil\n}", "func (payload *addListenPayload) Validate() (err error) {\n\tif payload.Etype == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\tif payload.Hookurl != nil {\n\t\tif ok := goa.ValidatePattern(`^https?://((\\w)+.?)+/(\\w+)$`, *payload.Hookurl); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`raw.hookurl`, *payload.Hookurl, `^https?://((\\w)+.?)+/(\\w+)$`))\n\t\t}\n\t}\n\treturn\n}", "func (p Peer) Validate() error {\n\treturn validation.ValidateStruct(\n\t\t&p,\n\t\tvalidation.Field(&p.NodeID, validation.Required),\n\t\tvalidation.Field(&p.Address, validation.Required, is.Host),\n\t)\n}", "func createNode(w http.ResponseWriter, r *http.Request) {\n\tvar newNode* Nodo\n\t//leemos el body de la petición\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Datos Inválidos\")\n\t}\n\t//tomamos los valores del body y los colocamos en una variable de struct de Nodo\n\tjson.Unmarshal(reqBody, &newNode)\n\t//fmt.Printf(\"%d\",newNode.Carnet)\n\t//insertamos la raiz\n\traiz=crearNodo(raiz,newNode)\n\tescribir,err2:=json.Marshal(raiz)\n\tif err2 != nil {\n log.Fatal(err2)\n }\n\tdata := []byte(escribir)\n err = ioutil.WriteFile(\"persiste.json\", data, 0644)\n if err != nil {\n log.Fatal(err)\n }\n\tfmt.Println(\"----------------\")\n\t//preorden(raiz)\n\t//createDot(raiz)\n\t//Si todo ha salido bien, devolvemos un status code 201 y el arbol\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\trespuesta:= &Respuesta{Message:\"Alumno creado exitosamente\"}\n\tw.WriteHeader(http.StatusCreated)\n\tjson.NewEncoder(w).Encode(respuesta)\n\n}", "func (m *CatalogueNode) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateNodes(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateTags(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (ut *addUserPayload) Validate() (err error) {\n\tif ut.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"name\"))\n\t}\n\tif ut.Email == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"email\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`request.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif ok := goa.ValidatePattern(`\\S`, *ut.Name); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`request.name`, *ut.Name, `\\S`))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 256 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 256, false))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 10 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 10, true))\n\t\t}\n\t}\n\treturn\n}", "func (n *Node) ValidateComplete() error {\n\tif n.Incomplete() {\n\t\treturn errors.New(\"missing IP address or ID\")\n\t}\n\tip := n.IP\n\tif ip.IsMulticast() || ip.IsUnspecified() {\n\t\treturn errors.New(\"invalid IP (multicast/unspecified)\")\n\t}\n\t// Validate the node key (on curve, etc.).\n\treturn nil\n}", "func (n *Node) IsValid() bool {\n\n\t// obviously a port number of zero won't work\n\tif n.TcpAddr.Port == 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (payload *CreateOutputPayload) Validate() (err error) {\n\tif payload.Alias == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"alias\"))\n\t}\n\tif payload.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"name\"))\n\t}\n\treturn\n}", "func (s *Store) Add(w http.ResponseWriter, r *http.Request) {\n\tdefer dphttp.DrainBody(r)\n\n\tctx := r.Context()\n\tlogData := log.Data{}\n\n\tlog.Info(ctx, \"add instance\", logData)\n\n\tinstance, err := unmarshalInstance(ctx, r.Body, true)\n\tif err != nil {\n\t\thandleInstanceErr(ctx, err, w, logData)\n\t\treturn\n\t}\n\n\tlogData[\"instance_id\"] = instance.InstanceID\n\n\tinstance.Links.Self = &models.LinkObject{\n\t\tHRef: fmt.Sprintf(\"%s/instances/%s\", s.Host, instance.InstanceID),\n\t}\n\n\tinstance, err = s.AddInstance(ctx, instance)\n\tif err != nil {\n\t\tlog.Error(ctx, \"add instance: store.AddInstance returned an error\", err, logData)\n\t\thandleInstanceErr(ctx, err, w, logData)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(instance)\n\tif err != nil {\n\t\tlog.Error(ctx, \"add instance: failed to marshal instance to json\", err, logData)\n\t\thandleInstanceErr(ctx, err, w, logData)\n\t\treturn\n\t}\n\n\tsetJSONContentType(w)\n\tdpresponse.SetETag(w, instance.ETag)\n\tw.WriteHeader(http.StatusCreated)\n\twriteBody(ctx, w, b, logData)\n\n\tlog.Info(ctx, \"add instance: request successful\", logData)\n}", "func (e Endpoints) AddNode(ctx context.Context, token string, node registry.Node) (err error) {\n\trequest := AddNodeRequest{\n\t\tNode: node,\n\t\tToken: token,\n\t}\n\tresponse, err := e.AddNodeEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(AddNodeResponse).Err\n}", "func validatePOSTRequest(body []byte, schema *gojsonschema.Schema) (err error) {\n\tdocLoader := gojsonschema.NewStringLoader(string(body))\n\tif result, err := schema.Validate(docLoader); err != nil && !result.Valid() {\n\t\treturn errors.New(\"Couldn't validate json\")\n\t}\n\treturn nil\n}", "func (adm Admin) AddNode(cluster string, node string) error {\n\tconn := newConnection(adm.ZkSvr)\n\terr := conn.Connect()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Disconnect()\n\n\tif ok, err := conn.IsClusterSetup(cluster); ok == false || err != nil {\n\t\treturn ErrClusterNotSetup\n\t}\n\n\t// check if node already exists under /<cluster>/CONFIGS/PARTICIPANT/<NODE>\n\tkeys := KeyBuilder{cluster}\n\tpath := keys.participantConfig(node)\n\texists, err := conn.Exists(path)\n\tmust(err)\n\tif exists {\n\t\treturn ErrNodeAlreadyExists\n\t}\n\n\t// create new node for the participant\n\tparts := strings.Split(node, \"_\")\n\tn := NewRecord(node)\n\tn.SetSimpleField(\"HELIX_HOST\", parts[0])\n\tn.SetSimpleField(\"HELIX_PORT\", parts[1])\n\n\tconn.CreateRecordWithPath(path, n)\n\tconn.CreateEmptyNode(keys.instance(node))\n\tconn.CreateEmptyNode(keys.messages(node))\n\tconn.CreateEmptyNode(keys.currentStates(node))\n\tconn.CreateEmptyNode(keys.errorsR(node))\n\tconn.CreateEmptyNode(keys.statusUpdates(node))\n\n\treturn nil\n}", "func validateNodeClientCSR(agent *aiv1beta1.Agent, csr *certificatesv1.CertificateSigningRequest, x509cr *x509.CertificateRequest) (bool, error) {\n\n\t// Organization must contain signle element \"system:nodes\"\n\tif len(x509cr.Subject.Organization) != 1 || x509cr.Subject.Organization[0] != nodeGroup {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: Organization %v does not contain single element %s\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tx509cr.Subject.Organization, nodeGroup)\n\t}\n\n\t// Since it is client CSR, DNSNames/EmailAddresses/IPAddresses must be empty\n\tif (len(x509cr.DNSNames) > 0) || (len(x509cr.EmailAddresses) > 0) || (len(x509cr.IPAddresses) > 0) {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: DNS names %v Email addresses %v IPAddresses %v are not empty\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tx509cr.DNSNames, x509cr.EmailAddresses, x509cr.IPAddresses)\n\t}\n\n\tkubeletClientUsagesLegacy := []certificatesv1.KeyUsage{\n\t\tcertificatesv1.UsageKeyEncipherment,\n\t\tcertificatesv1.UsageDigitalSignature,\n\t\tcertificatesv1.UsageClientAuth,\n\t}\n\tkubeletClientUsages := []certificatesv1.KeyUsage{\n\t\tcertificatesv1.UsageDigitalSignature,\n\t\tcertificatesv1.UsageClientAuth,\n\t}\n\tif !hasExactUsages(csr, kubeletClientUsages) && !hasExactUsages(csr, kubeletClientUsagesLegacy) {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: No exact match between CSR %v and required usages\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tcsr.Spec.Usages)\n\t}\n\n\t// CN must have prefix \"\"system:node:\"\n\tif !strings.HasPrefix(x509cr.Subject.CommonName, nodeUserPrefix) {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: Common name %s does not have prefix %s\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tx509cr.Subject.CommonName, nodeUserPrefix)\n\t}\n\n\t// This CSR must be from node bootstrapper\n\tif !isReqFromNodeBootstrapper(csr) {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: Not from bootstrapper\", csr.Name, agent.Namespace, agent.Name)\n\t}\n\treturn true, nil\n}", "func (p libvirtPlugin) Validate(req *types.Any) error {\n\treturn nil\n}", "func (payload *CreateVerificationPayload) Validate() (err error) {\n\n\treturn\n}", "func validateNumberOfNodesCLI(ng *api.NodeGroupBase) error {\n\tif ng.ScalingConfig == nil {\n\t\tng.ScalingConfig = &api.ScalingConfig{}\n\t}\n\n\tif ng.DesiredCapacity == nil && ng.MinSize == nil && ng.MaxSize == nil {\n\t\treturn fmt.Errorf(\"at least one of minimum, maximum and desired nodes must be set\")\n\t}\n\n\tif ng.DesiredCapacity != nil && *ng.DesiredCapacity < 0 {\n\t\treturn fmt.Errorf(\"number of nodes must be 0 or greater\")\n\t}\n\n\tif ng.MinSize != nil && *ng.MinSize < 0 {\n\t\treturn fmt.Errorf(\"minimum of nodes must be 0 or greater\")\n\t}\n\tif ng.MaxSize != nil && *ng.MaxSize < 0 {\n\t\treturn fmt.Errorf(\"maximum of nodes must be 0 or greater\")\n\t}\n\n\tif ng.MaxSize != nil && ng.MinSize != nil && *ng.MaxSize < *ng.MinSize {\n\t\treturn fmt.Errorf(\"maximum number of nodes must be greater than minimum number of nodes\")\n\t}\n\n\tif ng.MaxSize != nil && ng.DesiredCapacity != nil && *ng.MaxSize < *ng.DesiredCapacity {\n\t\treturn fmt.Errorf(\"maximum number of nodes must be greater than or equal to number of nodes\")\n\t}\n\n\tif ng.MinSize != nil && ng.DesiredCapacity != nil && *ng.MinSize > *ng.DesiredCapacity {\n\t\treturn fmt.Errorf(\"minimum number of nodes must be fewer than or equal to number of nodes\")\n\t}\n\treturn nil\n}", "func (t *OpenconfigSystem_System_Logging_RemoteServers_RemoteServer) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_RemoteServers_RemoteServer\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (*server) Add(ctx context.Context, req *sumpb.SumRequest) (*sumpb.SumResponse, error) {\n\ta, b := req.GetNumbers().GetA(), req.GetNumbers().GetB()\n\tlog.Println(\"A is : \", a)\n\tlog.Println(\"B is : \", b)\n\n\tsum := a + b\n\treturn &sumpb.SumResponse{Result: sum}, nil\n}", "func (h HostRule) Validation() error {\n\tif len(h) == 0 {\n\t\treturn fmt.Errorf(\"node rule cannot be enpty\")\n\t}\n\tfor _, role := range h {\n\t\tif !util.StringArrayContains(SupportNodeRule, role) {\n\t\t\treturn fmt.Errorf(\"node role %s can not be supported\", role)\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Config) Add(node *Node) error {\n\n\t// Creates the list of node replicas\n\texpectedReplicas := 1\n\tif node.Replicas != nil {\n\t\texpectedReplicas = int(*node.Replicas)\n\t}\n\n\treplicas := ReplicaList{}\n\tfor i := 1; i <= expectedReplicas; i++ {\n\t\treplica := &NodeReplica{\n\t\t\tNode: *node.DeepCopy(),\n\t\t}\n\t\treplica.Replicas = nil // resetting the replicas number for each replica to default (1)\n\n\t\treplicas = append(replicas, replica)\n\t}\n\n\t// adds replica to the config unpdating derivedConfigData\n\tfor _, replica := range replicas {\n\n\t\t// adds the replica to the list of nodes\n\t\tc.allReplicas = append(c.allReplicas, replica)\n\n\t\t// list of nodes with control plane role\n\t\tif replica.IsControlPlane() {\n\t\t\t// assign selected name for control plane node\n\t\t\treplica.Name = \"control-plane\"\n\t\t\t// stores the node in derivedConfigData\n\t\t\tc.controlPlanes = append(c.controlPlanes, replica)\n\t\t}\n\n\t\t// list of nodes with worker role\n\t\tif replica.IsWorker() {\n\t\t\t// assign selected name for worker node\n\t\t\treplica.Name = \"worker\"\n\t\t\t// stores the node in derivedConfigData\n\t\t\tc.workers = append(c.workers, replica)\n\t\t}\n\n\t\t// node with external etcd role\n\t\tif replica.IsExternalEtcd() {\n\t\t\tif c.externalEtcd != nil {\n\t\t\t\treturn errors.Errorf(\"invalid config. there are two nodes with role %q\", ExternalEtcdRole)\n\t\t\t}\n\t\t\t// assign selected name for etcd node\n\t\t\treplica.Name = \"etcd\"\n\t\t\t// stores the node in derivedConfigData\n\t\t\tc.externalEtcd = replica\n\t\t}\n\n\t\t// node with external load balancer role\n\t\tif replica.IsExternalLoadBalancer() {\n\t\t\tif c.externalLoadBalancer != nil {\n\t\t\t\treturn errors.Errorf(\"invalid config. there are two nodes with role %q\", ExternalLoadBalancerRole)\n\t\t\t}\n\t\t\t// assign selected name for load balancer node\n\t\t\treplica.Name = \"lb\"\n\t\t\t// stores the node in derivedConfigData\n\t\t\tc.externalLoadBalancer = replica\n\t\t}\n\n\t}\n\n\t// if more than one control plane node exists, fixes names to get a progressive index\n\tif len(c.controlPlanes) > 1 {\n\t\tfor i, n := range c.controlPlanes {\n\t\t\tn.Name = fmt.Sprintf(\"%s%d\", \"control-plane\", i+1)\n\t\t}\n\t}\n\n\t// if more than one worker node exists, fixes names to get a progressive index\n\tif len(c.workers) > 1 {\n\t\tfor i, n := range c.workers {\n\t\t\tn.Name = fmt.Sprintf(\"%s%d\", \"worker\", i+1)\n\t\t}\n\t}\n\n\t// ensure the list of nodes is ordered.\n\t// the ordering is key for getting a consistent and predictable behaviour\n\t// when provisioning nodes and when executing actions on nodes\n\tsort.Sort(c.allReplicas)\n\n\treturn nil\n}", "func (payload *CreateItemPayload) Validate() (err error) {\n\tif payload.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"name\"))\n\t}\n\tif payload.Description == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"description\"))\n\t}\n\n\tif payload.Image1 == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"image1\"))\n\t}\n\treturn\n}", "func (o *PostSiteCreatedBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateData(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func RegisterSubcenter(){\n method := \"PUT\"\n header_m := map[string]string{\"Content-Type\": \"application/x-www-form-urlencoded\"}\n host := getHostName()\n ipOfHost := getIp()\n urlToCenterT := urlToCenter + host\n body_send := \"ttl=\" + ttl + \"&value=\" + ipOfHost + \":21109\"\n //log.Debugf(\"host:%s, ip:%s, urlToCenter:%s, body_send:%s\", host, ipOfHost, urlToCenter, body_send)\n ut.SendHttp(body_send, 3, urlToCenterT, method, header_m)\n}" ]
[ "0.7103735", "0.6824135", "0.5912142", "0.5291574", "0.51865816", "0.5162585", "0.50906646", "0.502859", "0.49500355", "0.49242705", "0.4908517", "0.48461056", "0.483851", "0.4803192", "0.4801289", "0.47593367", "0.47554696", "0.47550145", "0.4754527", "0.4753902", "0.47470254", "0.47413287", "0.47325674", "0.473119", "0.4728897", "0.472586", "0.47135478", "0.46634352", "0.466044", "0.4660317", "0.4640358", "0.46328014", "0.46225256", "0.46116266", "0.46094385", "0.46029636", "0.45759705", "0.45681348", "0.4566124", "0.45625213", "0.4553302", "0.45508182", "0.4543057", "0.45396063", "0.45304978", "0.4527161", "0.45265767", "0.4526509", "0.45203", "0.45029595", "0.45018804", "0.45005357", "0.44897285", "0.44842628", "0.44810134", "0.44808403", "0.44739062", "0.4471136", "0.44648817", "0.44599417", "0.44593248", "0.44581413", "0.44492754", "0.44470954", "0.4443079", "0.44419417", "0.44270355", "0.44265467", "0.44239977", "0.4422068", "0.4420965", "0.44188932", "0.44178474", "0.4412838", "0.44053215", "0.44021666", "0.44008523", "0.43992835", "0.43921933", "0.43900248", "0.43759036", "0.43646777", "0.4363012", "0.43617976", "0.43616873", "0.4357534", "0.43502817", "0.43450373", "0.43396896", "0.43335187", "0.43328202", "0.4330871", "0.4325699", "0.4317547", "0.43130815", "0.43084386", "0.430511", "0.4302621", "0.42998555", "0.42967552" ]
0.69361144
1
Validate validates this add remote RDS node OK body remote RDS
func (o *AddRemoteRDSNodeOKBodyRemoteRDS) Validate(formats strfmt.Registry) error { return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o *AddRemoteRDSNodeBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *AddRemoteRDSNodeOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateRemoteRDS(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *AddRemoteRDSNodeDefaultBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateDetails(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func AddServer(data map[string]string)(err error) {\n uuid := data[\"uuid\"]\n err = ndb.GetTokenByUuid(uuid); if err!=nil{logs.Error(\"Error loading node token: %s\",err); return err}\n ipuuid,portuuid,err := ndb.ObtainPortIp(uuid)\n if err != nil {\n logs.Error(\"AddServer ERROR Obtaining Port and IP for Add a new server into STAP: \"+err.Error())\n return err\n }\n err = nodeclient.AddServer(ipuuid,portuuid, data)\n if err != nil {\n logs.Error(\"node/AddServer ERROR http data request: \"+err.Error())\n return err\n }\n return nil\n}", "func (o *Virtualserver) validate(dbRecord *common.DbRecord) (ok bool, err error) {\n\t////////////////////////////////////////////////////////////////////////////\n\t// Marshal data interface.\n\t////////////////////////////////////////////////////////////////////////////\n\tvar data virtualserver.Data\n\terr = shared.MarshalInterface(dbRecord.Data, &data)\n\tif err != nil {\n\t\treturn\n\t}\n\t////////////////////////////////////////////////////////////////////////////\n\t// Test required fields.\n\t////////////////////////////////////////////////////////////////////////////\n\tok = true\n\trequired := make(map[string]bool)\n\trequired[\"ProductCode\"] = false\n\trequired[\"IP\"] = false\n\trequired[\"Port\"] = false\n\trequired[\"LoadBalancerIP\"] = false\n\trequired[\"Name\"] = false\n\t////////////////////////////////////////////////////////////////////////////\n\tif data.ProductCode != 0 {\n\t\trequired[\"ProductCode\"] = true\n\t}\n\tif len(dbRecord.LoadBalancerIP) > 0 {\n\t\trequired[\"LoadBalancerIP\"] = true\n\t}\n\tif len(data.Ports) != 0 {\n\t\trequired[\"Port\"] = true\n\t}\n\tif data.IP != \"\" {\n\t\trequired[\"IP\"] = true\n\t}\n\tif data.Name != \"\" {\n\t\trequired[\"Name\"] = true\n\t}\n\tfor _, val := range required {\n\t\tif val == false {\n\t\t\tok = false\n\t\t}\n\t}\n\tif !ok {\n\t\terr = fmt.Errorf(\"missing required fields - %+v\", required)\n\t}\n\treturn\n}", "func (self *CentralBooking) RegisterInstance(resp http.ResponseWriter, req *http.Request) {\n var err error\n var remoteAddr string\n \n if xff, ok := req.Header[\"X-Forwarded-For\"]; ok {\n remoteAddr = xff[0]\n } else {\n remoteAddr, _, err = net.SplitHostPort(req.RemoteAddr)\n if err != nil {\n log.Errorf(\"unable to parse RemoteAddr: %s\", err)\n remoteAddr = req.RemoteAddr\n }\n }\n \n logEntry := log.WithField(\"remote_ip\", remoteAddr)\n \n type payloadType struct {\n Environment string\n Provider string\n Account string\n Region string\n Instance_ID string\n Role string\n Policies []string\n }\n \n var payload payloadType\n\n body, err := ioutil.ReadAll(req.Body)\n if err != nil {\n log.Errorf(\"unable to read body: %s\", err)\n http.Error(resp, \"unable to read body\", http.StatusBadRequest)\n return\n }\n \n err = json.Unmarshal(body, &payload)\n if err != nil {\n log.Errorf(\"unable to decode payload: %s\", err)\n http.Error(resp, \"unable to decode payload\", http.StatusBadRequest)\n return\n }\n \n logEntry.Info(\"registering instance\")\n regResp, err := self.registrar.Register(&instance.RegisterRequest{\n Env: payload.Environment,\n Provider: payload.Provider,\n Account: payload.Account,\n Region: payload.Region,\n InstanceID: payload.Instance_ID,\n Role: payload.Role,\n Policies: payload.Policies,\n })\n \n if err != nil {\n sc := http.StatusInternalServerError\n \n if _, ok := err.(*instance.ValidationError); ok {\n sc = http.StatusBadRequest\n }\n \n http.Error(resp, err.Error(), sc)\n return\n }\n\n svcs, _, err := self.consulCatalog.Service(\"consul-wan\", \"\", nil)\n if err != nil {\n log.Errorf(\"unable to retrieve consul-wan service: %s\", err)\n http.Error(resp, \"unable to retrieve consul-wan service\", http.StatusInternalServerError)\n return\n }\n\n consulServers := make([]string, 0, len(svcs))\n for _, svc := range svcs {\n consulServers = append(consulServers, fmt.Sprintf(\"%s:%d\", svc.ServiceAddress, svc.ServicePort))\n }\n\n respBytes, err := json.Marshal(map[string]interface{}{\n \"temp_token\": regResp.TempToken,\n \"vault_endpoint\": self.vaultEndpoint,\n \"consul_servers\": consulServers,\n })\n if err != nil {\n log.Errorf(\"unable to marshal response body: %s\", err)\n http.Error(resp, \"failed generating response body\", http.StatusInternalServerError)\n return\n }\n\n resp.Header().Add(\"Content-Type\", \"application/json\")\n resp.WriteHeader(http.StatusOK)\n resp.Write(respBytes)\n}", "func (c *Client) Add(ctx context.Context, node NodeInfo) error {\n\trequest := protocol.Message{}\n\tresponse := protocol.Message{}\n\n\trequest.Init(4096)\n\tresponse.Init(4096)\n\n\tprotocol.EncodeAdd(&request, node.ID, node.Address)\n\n\tif err := c.protocol.Call(ctx, &request, &response); err != nil {\n\t\treturn err\n\t}\n\n\tif err := protocol.DecodeEmpty(&response); err != nil {\n\t\treturn err\n\t}\n\n\t// If the desired role is spare, there's nothing to do, since all newly\n\t// added nodes have the spare role.\n\tif node.Role == Spare {\n\t\treturn nil\n\t}\n\n\treturn c.Assign(ctx, node.ID, node.Role)\n}", "func createServer(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar newServer server\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t fmt.Println(err)\n\t\tfmt.Fprintf(w, \"Kindly enter data with the server's address, MSA and MTA network addresses only in order to create new server\")\n\t w.WriteHeader(http.StatusInternalServerError)\n\t return\n\t}\n\tnewServer.ID = strconv.Itoa(len(servers)+1)\n\n\tjson.Unmarshal(reqBody, &newServer)\n\tservers = append(servers, newServer)\n\tw.WriteHeader(http.StatusCreated)\n\n\tjson.NewEncoder(w).Encode(newServer)\n}", "func (tapestry *Tapestry) addNode(remote Node, newnode Node) (neighbours []Node, err error) {\n\terr = makeRemoteNodeCall(remote, \"AddNode\", NodeRequest{remote, newnode}, &neighbours)\n\treturn\n}", "func (s *DNSSeeder) addNa(nNa *wire.NetAddress) bool {\n\n\tif len(s.nodes) > s.maxSize {\n\t\treturn false\n\t}\n\n\tif nNa.Port != s.Port {\n\t\treturn false\n\t}\n\n\t// generate the key and add to nodes\n\tk := net.JoinHostPort(nNa.IP.String(), strconv.Itoa(int(nNa.Port)))\n\n\tif _, dup := s.nodes[k]; dup == true {\n\t\treturn false\n\t}\n\n\t// if the reported timestamp suggests the netaddress has not been seen in the last 24 hours\n\t// then ignore this netaddress\n\tif (time.Now().Add(-(time.Hour * 24))).After(nNa.Timestamp) {\n\t\treturn false\n\t}\n\n\tnt := node{\n\t\tna: nNa,\n\t\tstatus: statusRG,\n\t\tdnsType: dns.TypeA,\n\t}\n\n\t// select the dns type based on the remote address type and port\n\tif x := nt.na.IP.To4(); x == nil {\n\t\tnt.dnsType = dns.TypeAAAA\n\t}\n\n\t// add the new node details to nodes\n\ts.nodes[k] = &nt\n\n\treturn true\n}", "func (t *OpenconfigSystem_System_Logging_RemoteServers_RemoteServer) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_RemoteServers_RemoteServer\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (ctx Context) AddNode(count int, hardwareprofile, softwareprofile string) (AddNodeResult, error) {\n\tvar result AddNodeResult\n\n\t// we trust the signature\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\taddInput := AddNodeInput{inner{count, hardwareprofile, softwareprofile}}\n\tinput, errMarshal := json.Marshal(addInput)\n\tif errMarshal != nil {\n\t\treturn result, errMarshal\n\t}\n\turl := fmt.Sprintf(\"https://%s:8443/v1/nodes\", ctx.Address)\n\treq, errRequest := http.NewRequest(\"POST\", url, bytes.NewBuffer(input))\n\tif errRequest != nil {\n\t\treturn result, errRequest\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.SetBasicAuth(ctx.User, ctx.Password)\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer resp.Body.Close()\n\n\tdecoder := json.NewDecoder(resp.Body)\n\tif err := decoder.Decode(&result); err != nil {\n\t\treturn result, err\n\t}\n\treturn result, nil\n}", "func (r *NodeDeployment) ValidateCreate() error {\n\tnodedeploymentlog.Info(\"validate create\", \"name\", r.Name)\n\n\t// TODO(user): fill in your validation logic upon object creation.\n\treturn nil\n}", "func (s *OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *CAPI) AddNode(req *btcjson.AddNodeCmd, resp None) (e error) {\n\tnrh := RPCHandlers\n\tres := nrh[\"addnode\"].Result()\n\tres.Params = req\n\tnrh[\"addnode\"].Call <- res\n\tselect {\n\tcase resp = <-res.Ch.(chan None):\n\tcase <-time.After(c.Timeout):\n\tcase <-c.quit.Wait():\n\t} \n\treturn \n}", "func validateRpc(node *Node, reqId []byte) error {\n\tif !bytes.Equal(node.Id, reqId) {\n\t\terrStr := fmt.Sprintf(\"Node ids do not match %v, %v\", node.Id, reqId)\n\t\treturn errors.New(errStr)\n\t}\n\treturn nil\n}", "func (eb *ElectrumBackend) addNode(addr, port string, network Network) error {\n\tident := electrum.NodeIdent(addr, port)\n\n\teb.nodeMu.RLock()\n\t_, existsGood := eb.nodes[ident]\n\t_, existsBad := eb.blacklistedNodes[ident]\n\teb.nodeMu.RUnlock()\n\tif existsGood {\n\t\treturn fmt.Errorf(\"already connected to %s\", addr)\n\t}\n\tif existsBad {\n\t\t// TODO: if we can't connect to a node over TCP, we should try the TLS port?\n\t\treturn fmt.Errorf(\"%s is known to be unreachable\", addr)\n\t}\n\n\tlog.Printf(\"connecting to %s\", addr)\n\tnode, err := electrum.NewNode(addr, port, network)\n\tif err != nil {\n\t\teb.nodeMu.Lock()\n\t\teb.blacklistedNodes[ident] = struct{}{}\n\t\teb.nodeMu.Unlock()\n\t\treturn err\n\t}\n\n\t// Get the server's features\n\tfeature, err := node.ServerFeatures()\n\tif err != nil {\n\t\teb.nodeMu.Lock()\n\t\teb.blacklistedNodes[ident] = struct{}{}\n\t\teb.nodeMu.Unlock()\n\t\treturn err\n\t}\n\t// Check genesis block\n\tif feature.Genesis != GenesisBlock(network) {\n\t\teb.nodeMu.Lock()\n\t\teb.blacklistedNodes[ident] = struct{}{}\n\t\teb.nodeMu.Unlock()\n\t\treturn ErrIncorrectGenesisBlock\n\t}\n\t// TODO: check pruning. Currently, servers currently don't prune, so it's fine to skip for now.\n\n\t// Check version\n\terr = checkVersion(feature.Protocol)\n\tif err != nil {\n\t\teb.nodeMu.Lock()\n\t\teb.blacklistedNodes[ident] = struct{}{}\n\t\teb.nodeMu.Unlock()\n\t\treturn err\n\t}\n\n\t// Negotiate version\n\terr = node.ServerVersion(\"1.2\")\n\tif err != nil {\n\t\teb.nodeMu.Lock()\n\t\teb.blacklistedNodes[ident] = struct{}{}\n\t\teb.nodeMu.Unlock()\n\t\treturn ErrFailedNegotiateVersion\n\t}\n\n\t// TODO: ask the server for info on the block height we care about. If the server doesn't have\n\t// that block, we'll automatically disconnect.\n\n\teb.nodeMu.Lock()\n\teb.nodes[ident] = node\n\teb.nodeMu.Unlock()\n\n\t// We can process requests\n\tgo eb.processRequests(node)\n\n\treturn nil\n}", "func (client *Client) AddShardingNodeWithOptions(request *AddShardingNodeRequest, runtime *util.RuntimeOptions) (_result *AddShardingNodeResponse, _err error) {\n\t_err = util.ValidateModel(request)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\tquery := map[string]interface{}{}\n\tif !tea.BoolValue(util.IsUnset(request.AutoPay)) {\n\t\tquery[\"AutoPay\"] = request.AutoPay\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.BusinessInfo)) {\n\t\tquery[\"BusinessInfo\"] = request.BusinessInfo\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.CouponNo)) {\n\t\tquery[\"CouponNo\"] = request.CouponNo\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ForceTrans)) {\n\t\tquery[\"ForceTrans\"] = request.ForceTrans\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.InstanceId)) {\n\t\tquery[\"InstanceId\"] = request.InstanceId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerAccount)) {\n\t\tquery[\"OwnerAccount\"] = request.OwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.OwnerId)) {\n\t\tquery[\"OwnerId\"] = request.OwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerAccount)) {\n\t\tquery[\"ResourceOwnerAccount\"] = request.ResourceOwnerAccount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ResourceOwnerId)) {\n\t\tquery[\"ResourceOwnerId\"] = request.ResourceOwnerId\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SecurityToken)) {\n\t\tquery[\"SecurityToken\"] = request.SecurityToken\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.ShardCount)) {\n\t\tquery[\"ShardCount\"] = request.ShardCount\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.SourceBiz)) {\n\t\tquery[\"SourceBiz\"] = request.SourceBiz\n\t}\n\n\tif !tea.BoolValue(util.IsUnset(request.VSwitchId)) {\n\t\tquery[\"VSwitchId\"] = request.VSwitchId\n\t}\n\n\treq := &openapi.OpenApiRequest{\n\t\tQuery: openapiutil.Query(query),\n\t}\n\tparams := &openapi.Params{\n\t\tAction: tea.String(\"AddShardingNode\"),\n\t\tVersion: tea.String(\"2015-01-01\"),\n\t\tProtocol: tea.String(\"HTTPS\"),\n\t\tPathname: tea.String(\"/\"),\n\t\tMethod: tea.String(\"POST\"),\n\t\tAuthType: tea.String(\"AK\"),\n\t\tStyle: tea.String(\"RPC\"),\n\t\tReqBodyType: tea.String(\"formData\"),\n\t\tBodyType: tea.String(\"json\"),\n\t}\n\t_result = &AddShardingNodeResponse{}\n\t_body, _err := client.CallApi(params, req, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_err = tea.Convert(_body, &_result)\n\treturn _result, _err\n}", "func (o *AddQANPostgreSQLPgStatementsAgentBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func addNode(address, username, password, name, bundle string, approve bool) (string, error) {\n\tvar ret string\n\n\t// Build the request body.\n\tenrolBody := types.NodeEnrollmentBody{\n\t\tAddress: address,\n\t\tName: name,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tAutoApprove: !approve, // user specifies if they dont want it\n\t\tCallHome: false,\n\t}\n\tif bundle != \"\" {\n\t\tenrolBody.Bundle = bundle\n\t\tenrolBody.Hostname = name\n\t\tenrolBody.CallHome = true\n\t}\n\trequest := types.EnrollmentRequest{\n\t\tEnrollment: enrolBody,\n\t}\n\treqJSON, err := json.Marshal(&request)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\turl, err := client.GetURL(nodeURI)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\treq, err := client.BuildReq(&reqJSON, url, http.MethodPost, true)\n\trawResp, err := client.HTTPClient().Do(req)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\t_, err = client.ParseReq(rawResp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\treturn \"Node added successfully\\n\", nil\n}", "func (n *Nodes) validateComplete() error {\n\tif n.Incomplete() {\n\t\treturn errors.New(\"incomplete Nodes\")\n\t}\n\tif n.UDP == 0 {\n\t\treturn errors.New(\"missing UDP port\")\n\t}\n\tif n.TCP == 0 {\n\t\treturn errors.New(\"missing TCP port\")\n\t}\n\tif n.IP.IsMulticast() || n.IP.IsUnspecified() {\n\t\treturn errors.New(\"invalid IP (multicast/unspecified)\")\n\t}\n\t_, err := n.ID.Pubkey() // validate the key (on curve, etcPtr.)\n\treturn err\n}", "func resourceNodeV1Create(d *schema.ResourceData, meta interface{}) error {\n\tclient, err := meta.(*Clients).GetIronicClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create the node object in Ironic\n\tcreateOpts := schemaToCreateOpts(d)\n\tresult, err := nodes.Create(client, createOpts).Extract()\n\tif err != nil {\n\t\td.SetId(\"\")\n\t\treturn err\n\t}\n\n\t// Setting the ID is what tells terraform we were successful in creating the node\n\tlog.Printf(\"[DEBUG] Node created with ID %s\\n\", d.Id())\n\td.SetId(result.UUID)\n\n\t// Create ports as part of the node object - you may also use the native port resource\n\tportSet := d.Get(\"ports\").(*schema.Set)\n\tif portSet != nil {\n\t\tportList := portSet.List()\n\t\tfor _, portInterface := range portList {\n\t\t\tport := portInterface.(map[string]interface{})\n\n\t\t\t// Terraform map can't handle bool... seriously.\n\t\t\tvar pxeEnabled bool\n\t\t\tif port[\"pxe_enabled\"] != nil {\n\t\t\t\tif port[\"pxe_enabled\"] == \"true\" {\n\t\t\t\t\tpxeEnabled = true\n\t\t\t\t} else {\n\t\t\t\t\tpxeEnabled = false\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t// FIXME: All values other than address and pxe\n\t\t\tportCreateOpts := ports.CreateOpts{\n\t\t\t\tNodeUUID: d.Id(),\n\t\t\t\tAddress: port[\"address\"].(string),\n\t\t\t\tPXEEnabled: &pxeEnabled,\n\t\t\t}\n\t\t\t_, err := ports.Create(client, portCreateOpts).Extract()\n\t\t\tif err != nil {\n\t\t\t\t_ = resourcePortV1Read(d, meta)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Make node manageable\n\tif d.Get(\"manage\").(bool) || d.Get(\"clean\").(bool) || d.Get(\"inspect\").(bool) {\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"manage\", nil, nil, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"could not manage: %s\", err)\n\t\t}\n\t}\n\n\t// Clean node\n\tif d.Get(\"clean\").(bool) {\n\t\tif err := setRAIDConfig(client, d); err != nil {\n\t\t\treturn fmt.Errorf(\"fail to set raid config: %s\", err)\n\t\t}\n\n\t\tvar cleanSteps []nodes.CleanStep\n\t\tif cleanSteps, err = buildManualCleaningSteps(d.Get(\"raid_interface\").(string), d.Get(\"raid_config\").(string), d.Get(\"bios_settings\").(string)); err != nil {\n\t\t\treturn fmt.Errorf(\"fail to build raid clean steps: %s\", err)\n\t\t}\n\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"clean\", nil, nil, cleanSteps); err != nil {\n\t\t\treturn fmt.Errorf(\"could not clean: %s\", err)\n\t\t}\n\t}\n\n\t// Inspect node\n\tif d.Get(\"inspect\").(bool) {\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"inspect\", nil, nil, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"could not inspect: %s\", err)\n\t\t}\n\t}\n\n\t// Make node available\n\tif d.Get(\"available\").(bool) {\n\t\tif err := ChangeProvisionStateToTarget(client, d.Id(), \"provide\", nil, nil, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"could not make node available: %s\", err)\n\t\t}\n\t}\n\n\t// Change power state, if required\n\tif targetPowerState := d.Get(\"target_power_state\").(string); targetPowerState != \"\" {\n\t\terr := changePowerState(client, d, nodes.TargetPowerState(targetPowerState))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not change power state: %s\", err)\n\t\t}\n\t}\n\n\treturn resourceNodeV1Read(d, meta)\n}", "func RegisterNode(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Register Node called\")\n\tdecoder := json.NewDecoder(r.Body)\n\tvar signedNode models.SignedPeer\n\terr := decoder.Decode(&signedNode)\n\tif err != nil {\n\t\tfmt.Println(\"Unable to decode request to register node. Incorrect format\")\n\t}\n\tvar nodeListJSON string\n\tpeerNode, ok := nodeList[signedNode.PeerNode.PeerId]\n\tif !ok {\n\t\tif(signedNode.PeerNode.VerifyPeerSignature(signedNode.SignedPeerNode)){\n\t\t\tfmt.Println(\"Signature Verified for new user. Register Successful\")\n\t\t\tnodeList[signedNode.PeerNode.PeerId] = signedNode.PeerNode\n\t\t\tnodeListJSON = nodeList.GetNodeListJSON()\n\t\t}else{\n\t\t\tnodeListJSON = \"{}\"\n\t\t}\n\t}else{\n\t\tfmt.Println(\"Peer Id already registered with this uuid.\")\n\t\tif(peerNode.VerifyPeerSignature(signedNode.SignedPeerNode)){\n\t\t\tfmt.Println(\"Verified with old public key. Updating key pair\")\n\t\t\tnodeList[signedNode.PeerNode.PeerId] = signedNode.PeerNode\n\t\t\tnodeListJSON = nodeList.GetNodeListJSON()\n\t\t}else{\n\t\t\tnodeListJSON = \"{}\"\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(nodeListJSON))\n}", "func AddReplicationTarget(nbmaster string, httpClient *http.Client, jwt string, stsName string, candId string)(int) {\n fmt.Printf(\"\\nSending a POST request to create with defaults...\\n\")\n\n\t//reader := bufio.NewReader(os.Stdin)\n\tIdSlice := strings.Split(candId, \":\")\n\n username := apiUtil.TakeInput(\"Enter target storage server username:\")\n\tpassword := apiUtil.TakeInput(\"Enter target storage server password:\")\n\n replicationtarget := map[string]interface{}{\n \"data\": map[string]interface{}{\n \"type\": \"replicationTargetRequest\",\n \"attributes\": map[string]interface{}{\n\t\t\t\t\"targetStorageServerInfo\": map[string]interface{}{\n \"targetMasterServer\": IdSlice[3],\n\t\t\t\t\t\"targetStorageServer\": IdSlice[1],\n\t\t\t\t\t\"targetStorageServerType\": IdSlice[0],\n\t\t\t\t\t\"targetMediaServer\": IdSlice[2]},\n\t\t\t\t\"targetStorageServerCredentials\": map[string]interface{}{\n\t\t\t\t\t\"userName\": username,\n\t\t\t\t\t\"password\": password}}}}\n\t\t\t\t\n\n\n stsRequest, _ := json.Marshal(replicationtarget)\n\n uri := \"https://\" + nbmaster + \":\" + port + \"/netbackup/\" + storageUri + storageServerUri + \"PureDisk:\" + stsName + replicationTargetsUri\n\n request, _ := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(stsRequest))\n request.Header.Add(\"Content-Type\", contentType);\n request.Header.Add(\"Authorization\", jwt);\n\n fmt.Println (\"Firing request: POST: \" + uri)\n response, err := httpClient.Do(request)\n\n if err != nil {\n fmt.Printf(\"The HTTP request failed with error: %s\\n\", err)\n panic(\"Unable to add replication target.\\n\")\n } else {\n if response.StatusCode != 201 {\n responseBody, _ := ioutil.ReadAll(response.Body)\n fmt.Printf(\"%s\\n\", responseBody)\n panic(\"Unable to add replication target.\\n\")\n } else {\n fmt.Printf(\"%s created successfully.\\n\", \"\");\n //responseDetails, _ := httputil.DumpResponse(response, true);\n apiUtil.AskForResponseDisplay(response.Body)\n }\n }\n\t\n\treturn response.StatusCode;\n}", "func (s SubnetArgs) validate() error {\n\tif s.isEmpty() {\n\t\treturn nil\n\t}\n\treturn s.FromTags.validate()\n}", "func (controller *ServiceController) AddHost(host *Host) (err error){\n con, err := sql.Open(\"mymysql\", controller.connection_string)\n if err != nil {\n return err\n }\n defer con.Close()\n\n _, err = con.Exec(\"INSERT INTO host ( hostid, hostname, private_network, cores, memory, last_updated) VALUES (?, ?, ?, ?, ?, ?)\",\n host.HostId().String(), host.Hostname(), host.PrivateNetwork(), host.Cores(), host.Memory(), host.LastUpdated())\n return err\n}", "func (cc *ContrailCommand) CreateNode(host vcenter.ESXIHost) error {\n\tlog.Debug(\"Create Node:\", cc.AuthToken)\n\tnodeResource := contrailCommandNodeSync{\n\t\tResources: []*nodeResources{\n\t\t\t{\n\t\t\t\tKind: \"node\",\n\t\t\t\tData: &nodeData{\n\t\t\t\t\tNodeType: \"esxi\",\n\t\t\t\t\tUUID: host.UUID,\n\t\t\t\t\tHostname: host.Hostname,\n\t\t\t\t\tFqName: []string{\"default-global-system-config\", host.Hostname},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tjsonData, err := json.Marshal(nodeResource)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Sending Request\")\n\tresp, _, err := cc.sendRequest(\"/sync\", string(jsonData), \"POST\") //nolint: bodyclose\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Debug(\"Got status : \", resp.StatusCode)\n\tswitch resp.StatusCode {\n\tdefault:\n\t\treturn fmt.Errorf(\"resource creation failed, %d\", resp.StatusCode)\n\tcase 200, 201:\n\t}\n\treturn nil\n}", "func (suite *TestAgentItSuite) TestAddNewAgent(c *C) {\n\tjsonBody := &struct {\n\t\tName string `json:\"name\"`\n\t\tHostname string `json:\"hostname\"`\n\t\tConnectionId string `json:\"connection_id\"`\n\t\tStatus bool `json:status`\n\t\tComment string `json:\"comment\"`\n\t\tIspId int `json:\"isp_id\"`\n\t\tProvinceId int `json:\"province_id\"`\n\t\tCityId int `json:\"city_id\"`\n\t\tNameTag string `json:\"name_tag\"`\n\t\tGroupTags []string `json:\"group_tags\"`\n\t} {\n\t\tName: \"new-agent-ccc\",\n\t\tHostname: \"new-host-cccc\",\n\t\tStatus: true,\n\t\tConnectionId: \"new-agent@blue.12.91.33\",\n\t\tComment: \"This is new agent by blue 12.91 ***\",\n\t\tIspId: 8,\n\t\tProvinceId: 9,\n\t\tCityId: 130,\n\t\tNameTag: \"rest-nt-1\",\n\t\tGroupTags: []string{ \"pp-rest-tag-1\", \"pp-rest-tag-2\" },\n\t}\n\n\ttestCases := []struct {\n\t\texpectedStatus int\n\t\texpectedErrorCode int\n\t} {\n\t\t{ http.StatusOK, -1 },\n\t\t{ http.StatusConflict, 1 },\n\t}\n\n\tfor _, testCase := range testCases {\n\t\tclient := sling.New().Post(httpClientConfig.String()).\n\t\t\tPath(\"/api/v1/nqm/agent\").\n\t\t\tBodyJSON(jsonBody)\n\n\t\tslintChecker := testingHttp.NewCheckSlint(c, client)\n\n\t\tjsonResp := slintChecker.GetJsonBody(testCase.expectedStatus)\n\n\t\tc.Logf(\"[Add Agent] JSON Result: %s\", json.MarshalPrettyJSON(jsonResp))\n\n\t\tswitch testCase.expectedStatus {\n\t\tcase http.StatusConflict:\n\t\t\tc.Assert(jsonResp.Get(\"error_code\").MustInt(), Equals, testCase.expectedErrorCode)\n\t\t}\n\n\t\tif testCase.expectedStatus != http.StatusOK {\n\t\t\tcontinue\n\t\t}\n\n\t\tc.Assert(jsonResp.Get(\"name\").MustString(), Equals, jsonBody.Name)\n\t\tc.Assert(jsonResp.Get(\"connection_id\").MustString(), Equals, jsonBody.ConnectionId)\n\t\tc.Assert(jsonResp.Get(\"ip_address\").MustString(), Equals, \"0.0.0.0\")\n\t\tc.Assert(jsonResp.Get(\"hostname\").MustString(), Equals, jsonBody.Hostname)\n\t\tc.Assert(jsonResp.Get(\"comment\").MustString(), Equals, jsonBody.Comment)\n\t\tc.Assert(jsonResp.Get(\"status\").MustBool(), Equals, jsonBody.Status)\n\t\tc.Assert(jsonResp.Get(\"isp\").Get(\"id\").MustInt(), Equals, jsonBody.IspId)\n\t\tc.Assert(jsonResp.Get(\"province\").Get(\"id\").MustInt(), Equals, jsonBody.ProvinceId)\n\t\tc.Assert(jsonResp.Get(\"city\").Get(\"id\").MustInt(), Equals, jsonBody.CityId)\n\t\tc.Assert(jsonResp.Get(\"name_tag\").Get(\"value\").MustString(), Equals, jsonBody.NameTag)\n\t\tc.Assert(jsonResp.Get(\"group_tags\").MustArray(), HasLen, len(jsonBody.GroupTags))\n\t}\n}", "func (zic *ZoneInterconnectHandler) AddRemoteZoneNode(node *corev1.Node) error {\n\tklog.Infof(\"Creating interconnect resources for remote zone node %s for the network %s\", node.Name, zic.GetNetworkName())\n\n\tnodeID := util.GetNodeID(node)\n\tif nodeID == -1 {\n\t\t// Don't consider this node as cluster-manager has not allocated node id yet.\n\t\treturn fmt.Errorf(\"failed to get node id for node - %s\", node.Name)\n\t}\n\n\t// Get the chassis id.\n\tchassisId, err := util.ParseNodeChassisIDAnnotation(node)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse node chassis-id for node - %s, error: %w\", node.Name, err)\n\t}\n\n\tif err := zic.createRemoteZoneNodeResources(node, nodeID, chassisId); err != nil {\n\t\treturn fmt.Errorf(\"creating interconnect resources for remote zone node %s for the network %s failed : err - %w\", node.Name, zic.GetNetworkName(), err)\n\t}\n\n\treturn nil\n}", "func NewAddRemoteRDSNodeOK() *AddRemoteRDSNodeOK {\n\treturn &AddRemoteRDSNodeOK{}\n}", "func (r *CAPIClient) AddNode(cmd ...*btcjson.AddNodeCmd) (res None, e error) {\n\tvar c *btcjson.AddNodeCmd\n\tif len(cmd) > 0 {\n\t\tc = cmd[0]\n\t}\n\tif e = r.Call(\"CAPI.AddNode\", c, &res); E.Chk(e) {\n\t}\n\treturn\n}", "func (p Peer) Validate() error {\n\treturn validation.ValidateStruct(\n\t\t&p,\n\t\tvalidation.Field(&p.NodeID, validation.Required),\n\t\tvalidation.Field(&p.Address, validation.Required, is.Host),\n\t)\n}", "func (v rdwsVpcConfig) validate() error {\n\tif v.isEmpty() {\n\t\treturn nil\n\t}\n\tif err := v.Placement.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"placement\": %w`, err)\n\t}\n\treturn nil\n}", "func (payload *addListenPayload) Validate() (err error) {\n\tif payload.Etype == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\tif payload.Hookurl != nil {\n\t\tif ok := goa.ValidatePattern(`^https?://((\\w)+.?)+/(\\w+)$`, *payload.Hookurl); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`raw.hookurl`, *payload.Hookurl, `^https?://((\\w)+.?)+/(\\w+)$`))\n\t\t}\n\t}\n\treturn\n}", "func (s *OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv4_Addresses_Address_Vrrp) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv4_Addresses_Address_Vrrp\"], s, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv4_Addresses_Address_Vrrp) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv4_Addresses_Address_Vrrp\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (zic *ZoneInterconnectHandler) AddRemoteZoneNode(node *corev1.Node) error {\n\tstart := time.Now()\n\tklog.Infof(\"Creating interconnect resources for remote zone node %s for the network %s\", node.Name, zic.GetNetworkName())\n\n\tnodeID := util.GetNodeID(node)\n\tif nodeID == -1 {\n\t\t// Don't consider this node as cluster-manager has not allocated node id yet.\n\t\treturn fmt.Errorf(\"failed to get node id for node - %s\", node.Name)\n\t}\n\n\t// Get the chassis id.\n\tchassisId, err := util.ParseNodeChassisIDAnnotation(node)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse node chassis-id for node - %s, error: %w\", node.Name, types.NewSuppressedError(err))\n\t}\n\n\tif err := zic.createRemoteZoneNodeResources(node, nodeID, chassisId); err != nil {\n\t\treturn fmt.Errorf(\"creating interconnect resources for remote zone node %s for the network %s failed : err - %w\", node.Name, zic.GetNetworkName(), err)\n\t}\n\tklog.Infof(\"Creating Interconnect resources for node %v took: %s\", node.Name, time.Since(start))\n\treturn nil\n}", "func (n *Node) validateComplete() error {\n\tif n.Incomplete() {\n\t\treturn errors.New(\"incomplete node\")\n\t}\n\tif n.UDP == 0 {\n\t\treturn errors.New(\"missing UDP port\")\n\t}\n\tif n.TCP == 0 {\n\t\treturn errors.New(\"missing TCP port\")\n\t}\n\tif n.IP.IsMulticast() || n.IP.IsUnspecified() {\n\t\treturn errors.New(\"invalid IP (multicast/unspecified)\")\n\t}\n\t_, err := n.ID.Pubkey() // validate the key (on curve, etc.)\n\treturn err\n}", "func (client *GCSBlobstore) validateRemoteConfig() error {\n\tif client.readOnly() {\n\t\treturn nil\n\t}\n\n\tbucket := client.authenticatedGCS.Bucket(client.config.BucketName)\n\t_, err := bucket.Attrs(context.Background())\n\treturn err\n}", "func validateNodeServerCSR(agent *aiv1beta1.Agent, node *corev1.Node, csr *certificatesv1.CertificateSigningRequest, x509CSR *x509.CertificateRequest) (bool, error) {\n\n\t// Username must consist from \"\"system:node:\" and the node name\n\tnodeAsking := strings.TrimPrefix(csr.Spec.Username, nodeUserPrefix)\n\tif len(nodeAsking) == 0 {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: CSR does not appear to be a node serving CSR. Empty node name after %s prefix\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tnodeUserPrefix)\n\t}\n\n\t// Check groups, we need at least:\n\t// - system:authenticated\n\tif len(csr.Spec.Groups) < 2 || !funk.ContainsString(csr.Spec.Groups, \"system:authenticated\") {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: %v is too small or not contains %q\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tcsr.Spec.Groups, \"system:authenticated\")\n\t}\n\n\tserverUsagesLegacy := []certificatesv1.KeyUsage{\n\t\tcertificatesv1.UsageDigitalSignature,\n\t\tcertificatesv1.UsageKeyEncipherment,\n\t\tcertificatesv1.UsageServerAuth,\n\t}\n\tserverUsages := []certificatesv1.KeyUsage{\n\t\tcertificatesv1.UsageDigitalSignature,\n\t\tcertificatesv1.UsageServerAuth,\n\t}\n\n\tif !hasExactUsages(csr, serverUsages) && !hasExactUsages(csr, serverUsagesLegacy) {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: No exact match between CSR %v and required usages\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tcsr.Spec.Usages)\n\t}\n\n\t// \"system:nodes\" must be one of the elements of Organization\n\tif !funk.ContainsString(x509CSR.Subject.Organization, nodeGroup) {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: Organization %v doesn't include %s\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tx509CSR.Subject.Organization, nodeGroup)\n\t}\n\n\t// CN and Username must be equal\n\tif x509CSR.Subject.CommonName != csr.Spec.Username {\n\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: Mismatched CommonName %s != %s for CSR %s\", csr.Name, agent.Namespace, agent.Name,\n\t\t\tx509CSR.Subject.CommonName, csr.Spec.Username, csr.Name)\n\t}\n\tnodeDNSNames := append(getNodeDNSNames(node), node.Name)\n\n\t// Any DNS name in CSR must exist in the nodeDNSNames\n\t// TODO: May need to modify for IPv6 only node\n\tfor _, dnsName := range x509CSR.DNSNames {\n\t\tif !funk.ContainsString(nodeDNSNames, dnsName) {\n\t\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: DNS name %s missing from available DNS names %v\", csr.Name, agent.Namespace, agent.Name,\n\t\t\t\tdnsName, nodeDNSNames)\n\t\t}\n\t}\n\tnodeIPs := getNodeIPs(node)\n\t// Any IP address in CSR must exist in nodeIPs\n\tfor _, ip := range x509CSR.IPAddresses {\n\t\tif !funk.ContainsString(nodeIPs, ip.String()) {\n\t\t\treturn false, errors.Errorf(\"CSR %s agent %s/%s: IP address %s missing from available node IPs %v\", csr.Name, agent.Namespace, agent.Name,\n\t\t\t\tip.String(), nodeIPs)\n\t\t}\n\t}\n\treturn true, nil\n}", "func (g *GuidePost) validateNodeConfig(q *msg.Request) (bool, error) {\n\tif q.Node.Config == nil {\n\t\treturn false, fmt.Errorf(\"NodeConfig subobject missing\")\n\t}\n\treturn g.validateBucketInRepository(\n\t\tq.Node.Config.RepositoryID,\n\t\tq.Node.Config.BucketID,\n\t)\n}", "func RegisterSubcenter(){\n method := \"PUT\"\n header_m := map[string]string{\"Content-Type\": \"application/x-www-form-urlencoded\"}\n host := getHostName()\n ipOfHost := getIp()\n urlToCenterT := urlToCenter + host\n body_send := \"ttl=\" + ttl + \"&value=\" + ipOfHost + \":21109\"\n //log.Debugf(\"host:%s, ip:%s, urlToCenter:%s, body_send:%s\", host, ipOfHost, urlToCenter, body_send)\n ut.SendHttp(body_send, 3, urlToCenterT, method, header_m)\n}", "func (o *PostIPAMIpsOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (t *OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Config) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_Config\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p PingreqPacket) Validate() error { return nil }", "func ValidateNode(member serf.Member) (ok bool, role, dc string) {\n\tif _, ok = member.Tags[\"id\"]; !ok {\n\t\treturn false, \"\", \"\"\n\t}\n\n\t// Get role name\n\tif role, ok = member.Tags[\"role\"]; !ok {\n\t\treturn false, \"\", \"\"\n\t} else if role != CerebrumRole {\n\t\treturn false, \"\", \"\"\n\t}\n\n\t// Get datacenter name\n\tif dc, ok = member.Tags[\"dc\"]; ok {\n\t\treturn true, role, dc\n\t}\n\treturn false, \"\", \"\"\n}", "func (s *OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Addresses_Address_Vrrp) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Addresses_Address_Vrrp\"], s, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Addresses_Address_Vrrp) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_RoutedVlan_Ipv6_Addresses_Address_Vrrp\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func validateNodeStageVolumeRequest(req *csi.NodeStageVolumeRequest) error {\n\tif req.GetVolumeCapability() == nil {\n\t\treturn errors.New(\"volume capability missing in request\")\n\t}\n\n\tif req.GetVolumeId() == \"\" {\n\t\treturn errors.New(\"volume ID missing in request\")\n\t}\n\n\tif req.GetVolumeContext() == nil || len(req.GetVolumeContext()) == 0 {\n\t\treturn errors.New(\"volume context cannot be nil or empty\")\n\t}\n\n\tif req.GetSecrets() == nil || len(req.GetSecrets()) == 0 {\n\t\treturn errors.New(\"stage secrets cannot be nil or empty\")\n\t}\n\n\treturn nil\n}", "func (s ServerCmd) Validate() error {\n\treturn nil\n}", "func (p *redfishProvisioner) ValidateManagementAccess(credentialsChanged bool) (result provisioner.Result, err error) {\n\n\t//check if the node is already registered\n\tnode, err := p.findExistingHost()\n\n\tif err != nil {\n\t\treturn result, errors.Wrap(err, \"failed to find existing host\")\n\t}\n\n\tif node == nil {\n\t\tnodeUUID, err := p.createNodeInMetamorph()\n\t\tif err != nil {\n\t\t\treturn result, errors.Wrap(err, \"failed to register host in redfish\")\n\t\t}\n\t\tp.publisher(\"Registered\", \"Registered new host\")\n\t\tp.status.ID = nodeUUID\n\t\tresult.Dirty = true\n\t\tp.log.Info(\"setting provisioning id :ID\", p.status.ID)\n\n\t} else {\n\t\tnodeUUID := node[\"NodeUUID\"].(string)\n\t\tif p.status.ID != nodeUUID {\n\t\t\t// Store the ID so other methods can assume it is set and\n\t\t\t// so we can find the node using that value next time.\n\t\t\tp.status.ID = nodeUUID\n\t\t\tresult.Dirty = true\n\t\t\tp.log.Info(\"setting provisioning id : ID\", p.status.ID)\n\t\t}\n\n\t}\n\treturn result, nil\n}", "func (*server) Add(ctx context.Context, req *sumpb.SumRequest) (*sumpb.SumResponse, error) {\n\ta, b := req.GetNumbers().GetA(), req.GetNumbers().GetB()\n\tlog.Println(\"A is : \", a)\n\tlog.Println(\"B is : \", b)\n\n\tsum := a + b\n\treturn &sumpb.SumResponse{Result: sum}, nil\n}", "func resourceVolterraVirtualNetworkCreate(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*APIClient)\n\n\tcreateMeta := &ves_io_schema.ObjectCreateMetaType{}\n\tcreateSpec := &ves_io_schema_virtual_network.CreateSpecType{}\n\tcreateReq := &ves_io_schema_virtual_network.CreateRequest{\n\t\tMetadata: createMeta,\n\t\tSpec: createSpec,\n\t}\n\n\tif v, ok := d.GetOk(\"annotations\"); ok && !isIntfNil(v) {\n\n\t\tms := map[string]string{}\n\n\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\tval := v.(string)\n\t\t\tms[k] = val\n\t\t}\n\t\tcreateMeta.Annotations = ms\n\t}\n\n\tif v, ok := d.GetOk(\"description\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Description =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"disable\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Disable =\n\t\t\tv.(bool)\n\t}\n\n\tif v, ok := d.GetOk(\"labels\"); ok && !isIntfNil(v) {\n\n\t\tms := map[string]string{}\n\n\t\tfor k, v := range v.(map[string]interface{}) {\n\t\t\tval := v.(string)\n\t\t\tms[k] = val\n\t\t}\n\t\tcreateMeta.Labels = ms\n\t}\n\n\tif v, ok := d.GetOk(\"name\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Name =\n\t\t\tv.(string)\n\t}\n\n\tif v, ok := d.GetOk(\"namespace\"); ok && !isIntfNil(v) {\n\t\tcreateMeta.Namespace =\n\t\t\tv.(string)\n\t}\n\n\t//network_choice\n\n\tnetworkChoiceTypeFound := false\n\n\tif v, ok := d.GetOk(\"global_network\"); ok && !networkChoiceTypeFound {\n\n\t\tnetworkChoiceTypeFound = true\n\n\t\tif v.(bool) {\n\t\t\tnetworkChoiceInt := &ves_io_schema_virtual_network.CreateSpecType_GlobalNetwork{}\n\t\t\tnetworkChoiceInt.GlobalNetwork = &ves_io_schema.Empty{}\n\t\t\tcreateSpec.NetworkChoice = networkChoiceInt\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"legacy_type\"); ok && !networkChoiceTypeFound {\n\n\t\tnetworkChoiceTypeFound = true\n\t\tnetworkChoiceInt := &ves_io_schema_virtual_network.CreateSpecType_LegacyType{}\n\n\t\tcreateSpec.NetworkChoice = networkChoiceInt\n\n\t\tnetworkChoiceInt.LegacyType = ves_io_schema.VirtualNetworkType(ves_io_schema.VirtualNetworkType_value[v.(string)])\n\n\t}\n\n\tif v, ok := d.GetOk(\"site_local_inside_network\"); ok && !networkChoiceTypeFound {\n\n\t\tnetworkChoiceTypeFound = true\n\n\t\tif v.(bool) {\n\t\t\tnetworkChoiceInt := &ves_io_schema_virtual_network.CreateSpecType_SiteLocalInsideNetwork{}\n\t\t\tnetworkChoiceInt.SiteLocalInsideNetwork = &ves_io_schema.Empty{}\n\t\t\tcreateSpec.NetworkChoice = networkChoiceInt\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"site_local_network\"); ok && !networkChoiceTypeFound {\n\n\t\tnetworkChoiceTypeFound = true\n\n\t\tif v.(bool) {\n\t\t\tnetworkChoiceInt := &ves_io_schema_virtual_network.CreateSpecType_SiteLocalNetwork{}\n\t\t\tnetworkChoiceInt.SiteLocalNetwork = &ves_io_schema.Empty{}\n\t\t\tcreateSpec.NetworkChoice = networkChoiceInt\n\t\t}\n\n\t}\n\n\tif v, ok := d.GetOk(\"srv6_network\"); ok && !networkChoiceTypeFound {\n\n\t\tnetworkChoiceTypeFound = true\n\t\tnetworkChoiceInt := &ves_io_schema_virtual_network.CreateSpecType_Srv6Network{}\n\t\tnetworkChoiceInt.Srv6Network = &ves_io_schema_virtual_network.PerSiteSrv6NetworkType{}\n\t\tcreateSpec.NetworkChoice = networkChoiceInt\n\n\t\tsl := v.(*schema.Set).List()\n\t\tfor _, set := range sl {\n\t\t\tcs := set.(map[string]interface{})\n\n\t\t\tif v, ok := cs[\"access_network_rtargets\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\taccessNetworkRtargets := make([]*ves_io_schema.RouteTarget, len(sl))\n\t\t\t\tnetworkChoiceInt.Srv6Network.AccessNetworkRtargets = accessNetworkRtargets\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\taccessNetworkRtargets[i] = &ves_io_schema.RouteTarget{}\n\t\t\t\t\taccessNetworkRtargetsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\trtargetChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := accessNetworkRtargetsMapStrToI[\"asn2byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn2ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget = &ves_io_schema.RouteTarget2ByteAsn{}\n\t\t\t\t\t\taccessNetworkRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := accessNetworkRtargetsMapStrToI[\"asn4byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn4ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget = &ves_io_schema.RouteTarget4ByteAsn{}\n\t\t\t\t\t\taccessNetworkRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := accessNetworkRtargetsMapStrToI[\"ipv4_addr_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Ipv4AddrRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget = &ves_io_schema.RouteTargetIPv4Addr{}\n\t\t\t\t\t\taccessNetworkRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Address = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tdefaultVipChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"anycast_vip\"]; ok && !isIntfNil(v) && !defaultVipChoiceTypeFound {\n\n\t\t\t\tdefaultVipChoiceTypeFound = true\n\t\t\t\tdefaultVipChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_AnycastVip{}\n\n\t\t\t\tnetworkChoiceInt.Srv6Network.DefaultVipChoice = defaultVipChoiceInt\n\n\t\t\t\tdefaultVipChoiceInt.AnycastVip = v.(string)\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"fleet_vip\"]; ok && !isIntfNil(v) && !defaultVipChoiceTypeFound {\n\n\t\t\t\tdefaultVipChoiceTypeFound = true\n\t\t\t\tdefaultVipChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_FleetVip{}\n\t\t\t\tdefaultVipChoiceInt.FleetVip = &ves_io_schema_virtual_network.AnyCastVIPFleetType{}\n\t\t\t\tnetworkChoiceInt.Srv6Network.DefaultVipChoice = defaultVipChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"vip_allocator\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tvipAllocatorInt := &ves_io_schema_views.ObjectRefType{}\n\t\t\t\t\t\tdefaultVipChoiceInt.FleetVip.VipAllocator = vipAllocatorInt\n\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tvaMapToStrVal := set.(map[string]interface{})\n\t\t\t\t\t\t\tif val, ok := vaMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tvipAllocatorInt.Name = val.(string)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif val, ok := vaMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tvipAllocatorInt.Namespace = val.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif val, ok := vaMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tvipAllocatorInt.Tenant = val.(string)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"interface_ip_vip\"]; ok && !isIntfNil(v) && !defaultVipChoiceTypeFound {\n\n\t\t\t\tdefaultVipChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tdefaultVipChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_InterfaceIpVip{}\n\t\t\t\t\tdefaultVipChoiceInt.InterfaceIpVip = &ves_io_schema.Empty{}\n\t\t\t\t\tnetworkChoiceInt.Srv6Network.DefaultVipChoice = defaultVipChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"enterprise_network_rtargets\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tenterpriseNetworkRtargets := make([]*ves_io_schema.RouteTarget, len(sl))\n\t\t\t\tnetworkChoiceInt.Srv6Network.EnterpriseNetworkRtargets = enterpriseNetworkRtargets\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\tenterpriseNetworkRtargets[i] = &ves_io_schema.RouteTarget{}\n\t\t\t\t\tenterpriseNetworkRtargetsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\trtargetChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := enterpriseNetworkRtargetsMapStrToI[\"asn2byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn2ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget = &ves_io_schema.RouteTarget2ByteAsn{}\n\t\t\t\t\t\tenterpriseNetworkRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := enterpriseNetworkRtargetsMapStrToI[\"asn4byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn4ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget = &ves_io_schema.RouteTarget4ByteAsn{}\n\t\t\t\t\t\tenterpriseNetworkRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := enterpriseNetworkRtargetsMapStrToI[\"ipv4_addr_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Ipv4AddrRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget = &ves_io_schema.RouteTargetIPv4Addr{}\n\t\t\t\t\t\tenterpriseNetworkRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Address = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"export_rtargets\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\texportRtargets := make([]*ves_io_schema.RouteTarget, len(sl))\n\t\t\t\tnetworkChoiceInt.Srv6Network.ExportRtargets = exportRtargets\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\texportRtargets[i] = &ves_io_schema.RouteTarget{}\n\t\t\t\t\texportRtargetsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\trtargetChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := exportRtargetsMapStrToI[\"asn2byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn2ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget = &ves_io_schema.RouteTarget2ByteAsn{}\n\t\t\t\t\t\texportRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := exportRtargetsMapStrToI[\"asn4byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn4ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget = &ves_io_schema.RouteTarget4ByteAsn{}\n\t\t\t\t\t\texportRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := exportRtargetsMapStrToI[\"ipv4_addr_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Ipv4AddrRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget = &ves_io_schema.RouteTargetIPv4Addr{}\n\t\t\t\t\t\texportRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Address = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"fleets\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tfleetsInt := make([]*ves_io_schema_views.ObjectRefType, len(sl))\n\t\t\t\tnetworkChoiceInt.Srv6Network.Fleets = fleetsInt\n\t\t\t\tfor i, ps := range sl {\n\n\t\t\t\t\tfMapToStrVal := ps.(map[string]interface{})\n\t\t\t\t\tfleetsInt[i] = &ves_io_schema_views.ObjectRefType{}\n\n\t\t\t\t\tif v, ok := fMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tfleetsInt[i].Name = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := fMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tfleetsInt[i].Namespace = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := fMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tfleetsInt[i].Tenant = v.(string)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"internet_rtargets\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.([]interface{})\n\t\t\t\tinternetRtargets := make([]*ves_io_schema.RouteTarget, len(sl))\n\t\t\t\tnetworkChoiceInt.Srv6Network.InternetRtargets = internetRtargets\n\t\t\t\tfor i, set := range sl {\n\t\t\t\t\tinternetRtargets[i] = &ves_io_schema.RouteTarget{}\n\t\t\t\t\tinternetRtargetsMapStrToI := set.(map[string]interface{})\n\n\t\t\t\t\trtargetChoiceTypeFound := false\n\n\t\t\t\t\tif v, ok := internetRtargetsMapStrToI[\"asn2byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn2ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget = &ves_io_schema.RouteTarget2ByteAsn{}\n\t\t\t\t\t\tinternetRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn2ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := internetRtargetsMapStrToI[\"asn4byte_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Asn4ByteRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget = &ves_io_schema.RouteTarget4ByteAsn{}\n\t\t\t\t\t\tinternetRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"as_number\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.AsNumber = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Asn4ByteRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := internetRtargetsMapStrToI[\"ipv4_addr_rtarget\"]; ok && !isIntfNil(v) && !rtargetChoiceTypeFound {\n\n\t\t\t\t\t\trtargetChoiceTypeFound = true\n\t\t\t\t\t\trtargetChoiceInt := &ves_io_schema.RouteTarget_Ipv4AddrRtarget{}\n\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget = &ves_io_schema.RouteTargetIPv4Addr{}\n\t\t\t\t\t\tinternetRtargets[i].RtargetChoice = rtargetChoiceInt\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\t\t\tif v, ok := cs[\"address\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Address = v.(string)\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif v, ok := cs[\"value\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\t\t\trtargetChoiceInt.Ipv4AddrRtarget.Value = uint32(v.(int))\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tnamespaceChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"no_namespace_network\"]; ok && !isIntfNil(v) && !namespaceChoiceTypeFound {\n\n\t\t\t\tnamespaceChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnamespaceChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_NoNamespaceNetwork{}\n\t\t\t\t\tnamespaceChoiceInt.NoNamespaceNetwork = &ves_io_schema.Empty{}\n\t\t\t\t\tnetworkChoiceInt.Srv6Network.NamespaceChoice = namespaceChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"srv6_network_ns_params\"]; ok && !isIntfNil(v) && !namespaceChoiceTypeFound {\n\n\t\t\t\tnamespaceChoiceTypeFound = true\n\t\t\t\tnamespaceChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_Srv6NetworkNsParams{}\n\t\t\t\tnamespaceChoiceInt.Srv6NetworkNsParams = &ves_io_schema_virtual_network.Srv6NetworkNsParametersType{}\n\t\t\t\tnetworkChoiceInt.Srv6Network.NamespaceChoice = namespaceChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnamespaceChoiceInt.Srv6NetworkNsParams.Namespace = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"remote_sid_stats_plen\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tnetworkChoiceInt.Srv6Network.RemoteSidStatsPlen = uint32(v.(int))\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"slice\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tsliceInt := &ves_io_schema_views.ObjectRefType{}\n\t\t\t\tnetworkChoiceInt.Srv6Network.Slice = sliceInt\n\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tsMapToStrVal := set.(map[string]interface{})\n\t\t\t\t\tif val, ok := sMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tsliceInt.Name = val.(string)\n\t\t\t\t\t}\n\t\t\t\t\tif val, ok := sMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tsliceInt.Namespace = val.(string)\n\t\t\t\t\t}\n\n\t\t\t\t\tif val, ok := sMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\tsliceInt.Tenant = val.(string)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tsnatPoolChoiceTypeFound := false\n\n\t\t\tif v, ok := cs[\"fleet_snat_pool\"]; ok && !isIntfNil(v) && !snatPoolChoiceTypeFound {\n\n\t\t\t\tsnatPoolChoiceTypeFound = true\n\t\t\t\tsnatPoolChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_FleetSnatPool{}\n\t\t\t\tsnatPoolChoiceInt.FleetSnatPool = &ves_io_schema_virtual_network.SNATPoolFleetType{}\n\t\t\t\tnetworkChoiceInt.Srv6Network.SnatPoolChoice = snatPoolChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"snat_pool_allocator\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tsnatPoolAllocatorInt := &ves_io_schema_views.ObjectRefType{}\n\t\t\t\t\t\tsnatPoolChoiceInt.FleetSnatPool.SnatPoolAllocator = snatPoolAllocatorInt\n\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tspaMapToStrVal := set.(map[string]interface{})\n\t\t\t\t\t\t\tif val, ok := spaMapToStrVal[\"name\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tsnatPoolAllocatorInt.Name = val.(string)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif val, ok := spaMapToStrVal[\"namespace\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tsnatPoolAllocatorInt.Namespace = val.(string)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif val, ok := spaMapToStrVal[\"tenant\"]; ok && !isIntfNil(v) {\n\t\t\t\t\t\t\t\tsnatPoolAllocatorInt.Tenant = val.(string)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"interface_ip_snat_pool\"]; ok && !isIntfNil(v) && !snatPoolChoiceTypeFound {\n\n\t\t\t\tsnatPoolChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tsnatPoolChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_InterfaceIpSnatPool{}\n\t\t\t\t\tsnatPoolChoiceInt.InterfaceIpSnatPool = &ves_io_schema.Empty{}\n\t\t\t\t\tnetworkChoiceInt.Srv6Network.SnatPoolChoice = snatPoolChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := cs[\"site_snat_pool\"]; ok && !isIntfNil(v) && !snatPoolChoiceTypeFound {\n\n\t\t\t\tsnatPoolChoiceTypeFound = true\n\t\t\t\tsnatPoolChoiceInt := &ves_io_schema_virtual_network.PerSiteSrv6NetworkType_SiteSnatPool{}\n\t\t\t\tsnatPoolChoiceInt.SiteSnatPool = &ves_io_schema_virtual_network.SNATPoolSiteType{}\n\t\t\t\tnetworkChoiceInt.Srv6Network.SnatPoolChoice = snatPoolChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"node_snat_pool\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\t\t\tnodeSnatPool := make(map[string]*ves_io_schema_virtual_network.SNATPoolType)\n\t\t\t\t\t\tsnatPoolChoiceInt.SiteSnatPool.NodeSnatPool = nodeSnatPool\n\t\t\t\t\t\tfor _, set := range sl {\n\t\t\t\t\t\t\tnodeSnatPoolMapStrToI := set.(map[string]interface{})\n\t\t\t\t\t\t\tkey, ok := nodeSnatPoolMapStrToI[\"name\"]\n\t\t\t\t\t\t\tif ok && !isIntfNil(key) {\n\t\t\t\t\t\t\t\tnodeSnatPool[key.(string)] = &ves_io_schema_virtual_network.SNATPoolType{}\n\t\t\t\t\t\t\t\tval, _ := nodeSnatPoolMapStrToI[\"value\"]\n\n\t\t\t\t\t\t\t\tnodeSnatPoolVals := val.(*schema.Set).List()\n\t\t\t\t\t\t\t\tfor _, intVal := range nodeSnatPoolVals {\n\n\t\t\t\t\t\t\t\t\tnodeSnatPoolStaticMap := intVal.(map[string]interface{})\n\n\t\t\t\t\t\t\t\t\tif w, ok := nodeSnatPoolStaticMap[\"ipv4_prefixes\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\tnodeSnatPool[key.(string)].Ipv4Prefixes = nil\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif w, ok := nodeSnatPoolStaticMap[\"ipv6_prefixes\"]; ok && !isIntfNil(w) {\n\t\t\t\t\t\t\t\t\t\tnodeSnatPool[key.(string)].Ipv6Prefixes = nil\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// break after one loop\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//static_routes\n\tif v, ok := d.GetOk(\"static_routes\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.([]interface{})\n\t\tstaticRoutes := make([]*ves_io_schema_virtual_network.StaticRouteViewType, len(sl))\n\t\tcreateSpec.StaticRoutes = staticRoutes\n\t\tfor i, set := range sl {\n\t\t\tstaticRoutes[i] = &ves_io_schema_virtual_network.StaticRouteViewType{}\n\t\t\tstaticRoutesMapStrToI := set.(map[string]interface{})\n\n\t\t\tif v, ok := staticRoutesMapStrToI[\"attrs\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tattrsList := []ves_io_schema.RouteAttrType{}\n\t\t\t\tfor _, j := range v.([]interface{}) {\n\t\t\t\t\tattrsList = append(attrsList, ves_io_schema.RouteAttrType(ves_io_schema.RouteAttrType_value[j.(string)]))\n\t\t\t\t}\n\t\t\t\tstaticRoutes[i].Attrs = attrsList\n\n\t\t\t}\n\n\t\t\tif w, ok := staticRoutesMapStrToI[\"ip_prefixes\"]; ok && !isIntfNil(w) {\n\t\t\t\tls := make([]string, len(w.([]interface{})))\n\t\t\t\tfor i, v := range w.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tstaticRoutes[i].IpPrefixes = ls\n\t\t\t}\n\n\t\t\tnextHopChoiceTypeFound := false\n\n\t\t\tif v, ok := staticRoutesMapStrToI[\"default_gateway\"]; ok && !isIntfNil(v) && !nextHopChoiceTypeFound {\n\n\t\t\t\tnextHopChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnextHopChoiceInt := &ves_io_schema_virtual_network.StaticRouteViewType_DefaultGateway{}\n\t\t\t\t\tnextHopChoiceInt.DefaultGateway = &ves_io_schema.Empty{}\n\t\t\t\t\tstaticRoutes[i].NextHopChoice = nextHopChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := staticRoutesMapStrToI[\"interface\"]; ok && !isIntfNil(v) && !nextHopChoiceTypeFound {\n\n\t\t\t\tnextHopChoiceTypeFound = true\n\t\t\t\tnextHopChoiceInt := &ves_io_schema_virtual_network.StaticRouteViewType_Interface{}\n\t\t\t\tnextHopChoiceInt.Interface = &ves_io_schema_views.ObjectRefType{}\n\t\t\t\tstaticRoutes[i].NextHopChoice = nextHopChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnextHopChoiceInt.Interface.Name = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnextHopChoiceInt.Interface.Namespace = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"tenant\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnextHopChoiceInt.Interface.Tenant = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := staticRoutesMapStrToI[\"ip_address\"]; ok && !isIntfNil(v) && !nextHopChoiceTypeFound {\n\n\t\t\t\tnextHopChoiceTypeFound = true\n\t\t\t\tnextHopChoiceInt := &ves_io_schema_virtual_network.StaticRouteViewType_IpAddress{}\n\n\t\t\t\tstaticRoutes[i].NextHopChoice = nextHopChoiceInt\n\n\t\t\t\tnextHopChoiceInt.IpAddress = v.(string)\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\t//static_v6_routes\n\tif v, ok := d.GetOk(\"static_v6_routes\"); ok && !isIntfNil(v) {\n\n\t\tsl := v.([]interface{})\n\t\tstaticV6Routes := make([]*ves_io_schema_virtual_network.StaticV6RouteViewType, len(sl))\n\t\tcreateSpec.StaticV6Routes = staticV6Routes\n\t\tfor i, set := range sl {\n\t\t\tstaticV6Routes[i] = &ves_io_schema_virtual_network.StaticV6RouteViewType{}\n\t\t\tstaticV6RoutesMapStrToI := set.(map[string]interface{})\n\n\t\t\tif v, ok := staticV6RoutesMapStrToI[\"attrs\"]; ok && !isIntfNil(v) {\n\n\t\t\t\tattrsList := []ves_io_schema.RouteAttrType{}\n\t\t\t\tfor _, j := range v.([]interface{}) {\n\t\t\t\t\tattrsList = append(attrsList, ves_io_schema.RouteAttrType(ves_io_schema.RouteAttrType_value[j.(string)]))\n\t\t\t\t}\n\t\t\t\tstaticV6Routes[i].Attrs = attrsList\n\n\t\t\t}\n\n\t\t\tif w, ok := staticV6RoutesMapStrToI[\"ip_prefixes\"]; ok && !isIntfNil(w) {\n\t\t\t\tls := make([]string, len(w.([]interface{})))\n\t\t\t\tfor i, v := range w.([]interface{}) {\n\t\t\t\t\tls[i] = v.(string)\n\t\t\t\t}\n\t\t\t\tstaticV6Routes[i].IpPrefixes = ls\n\t\t\t}\n\n\t\t\tnextHopChoiceTypeFound := false\n\n\t\t\tif v, ok := staticV6RoutesMapStrToI[\"default_gateway\"]; ok && !isIntfNil(v) && !nextHopChoiceTypeFound {\n\n\t\t\t\tnextHopChoiceTypeFound = true\n\n\t\t\t\tif v.(bool) {\n\t\t\t\t\tnextHopChoiceInt := &ves_io_schema_virtual_network.StaticV6RouteViewType_DefaultGateway{}\n\t\t\t\t\tnextHopChoiceInt.DefaultGateway = &ves_io_schema.Empty{}\n\t\t\t\t\tstaticV6Routes[i].NextHopChoice = nextHopChoiceInt\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := staticV6RoutesMapStrToI[\"interface\"]; ok && !isIntfNil(v) && !nextHopChoiceTypeFound {\n\n\t\t\t\tnextHopChoiceTypeFound = true\n\t\t\t\tnextHopChoiceInt := &ves_io_schema_virtual_network.StaticV6RouteViewType_Interface{}\n\t\t\t\tnextHopChoiceInt.Interface = &ves_io_schema_views.ObjectRefType{}\n\t\t\t\tstaticV6Routes[i].NextHopChoice = nextHopChoiceInt\n\n\t\t\t\tsl := v.(*schema.Set).List()\n\t\t\t\tfor _, set := range sl {\n\t\t\t\t\tcs := set.(map[string]interface{})\n\n\t\t\t\t\tif v, ok := cs[\"name\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnextHopChoiceInt.Interface.Name = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"namespace\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnextHopChoiceInt.Interface.Namespace = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif v, ok := cs[\"tenant\"]; ok && !isIntfNil(v) {\n\n\t\t\t\t\t\tnextHopChoiceInt.Interface.Tenant = v.(string)\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif v, ok := staticV6RoutesMapStrToI[\"ip_address\"]; ok && !isIntfNil(v) && !nextHopChoiceTypeFound {\n\n\t\t\t\tnextHopChoiceTypeFound = true\n\t\t\t\tnextHopChoiceInt := &ves_io_schema_virtual_network.StaticV6RouteViewType_IpAddress{}\n\n\t\t\t\tstaticV6Routes[i].NextHopChoice = nextHopChoiceInt\n\n\t\t\t\tnextHopChoiceInt.IpAddress = v.(string)\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tlog.Printf(\"[DEBUG] Creating Volterra VirtualNetwork object with struct: %+v\", createReq)\n\n\tcreateVirtualNetworkResp, err := client.CreateObject(context.Background(), ves_io_schema_virtual_network.ObjectType, createReq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating VirtualNetwork: %s\", err)\n\t}\n\td.SetId(createVirtualNetworkResp.GetObjSystemMetadata().GetUid())\n\n\treturn resourceVolterraVirtualNetworkRead(d, meta)\n}", "func (o *TunnelServerOptions) validate() error {\n\tif len(o.bindAddr) == 0 {\n\t\treturn fmt.Errorf(\"%s's bind address can't be empty\",\n\t\t\tversion.GetServerName())\n\t}\n\treturn nil\n}", "func (o *PostServiceListenerPortsOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (t *OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_State) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_RemoteServers_RemoteServer_State\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *AddPMMAgentBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (s *Store) Add(w http.ResponseWriter, r *http.Request) {\n\tdefer dphttp.DrainBody(r)\n\n\tctx := r.Context()\n\tlogData := log.Data{}\n\n\tlog.Info(ctx, \"add instance\", logData)\n\n\tinstance, err := unmarshalInstance(ctx, r.Body, true)\n\tif err != nil {\n\t\thandleInstanceErr(ctx, err, w, logData)\n\t\treturn\n\t}\n\n\tlogData[\"instance_id\"] = instance.InstanceID\n\n\tinstance.Links.Self = &models.LinkObject{\n\t\tHRef: fmt.Sprintf(\"%s/instances/%s\", s.Host, instance.InstanceID),\n\t}\n\n\tinstance, err = s.AddInstance(ctx, instance)\n\tif err != nil {\n\t\tlog.Error(ctx, \"add instance: store.AddInstance returned an error\", err, logData)\n\t\thandleInstanceErr(ctx, err, w, logData)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(instance)\n\tif err != nil {\n\t\tlog.Error(ctx, \"add instance: failed to marshal instance to json\", err, logData)\n\t\thandleInstanceErr(ctx, err, w, logData)\n\t\treturn\n\t}\n\n\tsetJSONContentType(w)\n\tdpresponse.SetETag(w, instance.ETag)\n\tw.WriteHeader(http.StatusCreated)\n\twriteBody(ctx, w, b, logData)\n\n\tlog.Info(ctx, \"add instance: request successful\", logData)\n}", "func validateNodeStageVolumeRequest(req *csi.NodeStageVolumeRequest) error {\n\tif req.GetVolumeCapability() == nil {\n\t\treturn fmt.Errorf(\"volume capability missing in request\")\n\t}\n\n\tif req.GetVolumeId() == \"\" {\n\t\treturn fmt.Errorf(\"volume ID missing in request\")\n\t}\n\n\tif req.GetStagingTargetPath() == \"\" {\n\t\treturn fmt.Errorf(\"staging target path missing in request\")\n\t}\n\n\tif req.GetNodeStageSecrets() == nil || len(req.GetNodeStageSecrets()) == 0 {\n\t\treturn fmt.Errorf(\"stage secrets cannot be nil or empty\")\n\t}\n\n\treturn nil\n}", "func (m *StoragepoolNodepool) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func AddServer(w http.ResponseWriter, r *http.Request) {\n\tvar newServer Server\n\n\t// Read the body\n\tbody, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\tlog.Print(err.Error())\n\t\t// Error while reading the body...\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err := json.Unmarshal(body, &newServer); err == nil {\n\t\tw.WriteHeader(http.StatusCreated)\n\t\tservers[newServer.Name] = newServer\n\n\t\tlog.Println(\"Registered \" + newServer.Name)\n\t} else {\n\t\t// If we can't unmarshal the json, we're assuming the client made a mistake\n\t\t// in formatting their request\n\t\tlog.Println(err.Error())\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t}\n\n}", "func (t *OpenconfigSystem_System_Logging_RemoteServers) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Logging_RemoteServers\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (d *portworx) ValidateNodeAfterPickingUpNodeID(delNode *api.StorageNode, newNode *api.StorageNode, storagelessNodes []*api.StorageNode) error {\n\t// If node is a storageless node below validation steps not needed\n\tif !d.validateNodeIDMigration(delNode, newNode, storagelessNodes) {\n\t\treturn fmt.Errorf(\"validation failed: NodeId: [%s] pick-up failed by new Node: [%s]\", delNode.Id, newNode.Hostname)\n\t}\n\n\tlog.Infof(\"Pools and Disks are matching after new node:[%s] picked the NodeId: [%s]\", newNode.Hostname, newNode.Id)\n\tlog.Infof(\"After recyling a node, Node [%s] is having following pools:\", newNode.Hostname)\n\tfor _, pool := range newNode.Pools {\n\t\tlog.Infof(\"Node [%s] is having pool id: [%s]\", newNode.Hostname, pool.Uuid)\n\t}\n\n\tlog.Infof(\"After recyling a node, Node [%s] is having disks: [%v]\", newNode.Hostname, newNode.Disks)\n\treturn nil\n}", "func (o *PostIPAMIpnatOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (o *AddExternalBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (h *FriendlyHost) Valid() bool {\n\treturn svchost.IsValid(h.Raw)\n}", "func (o *YurttunnelServerOptions) validate() error {\n\tif len(o.bindAddr) == 0 {\n\t\treturn fmt.Errorf(\"%s's bind address can't be empty\",\n\t\t\tprojectinfo.GetServerName())\n\t}\n\treturn nil\n}", "func (s *OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_State) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_State\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (payload *AddListenPayload) Validate() (err error) {\n\tif payload.Etype == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"etype\"))\n\t}\n\tif payload.Hookurl == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"hookurl\"))\n\t}\n\tif payload.From == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"from\"))\n\t}\n\tif ok := goa.ValidatePattern(`^https?://((\\w)+.?)+/(\\w+)$`, payload.Hookurl); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`raw.hookurl`, payload.Hookurl, `^https?://((\\w)+.?)+/(\\w+)$`))\n\t}\n\treturn\n}", "func addRemoteAddress(r *http.Request, user_id int) {\n\tvar addresses string\n\tstmt, _ := db.Prepare(\"select remote_addr from users where id=?\")\n\tres := stmt.QueryRow(user_id)\n\terr := res.Scan(&addresses)\n\tnewAddr := strings.Split(r.RemoteAddr, \":\")[0]\n\tif newAddr == \"[\" {\n\t\tnewAddr = \"localHost\"\n\t}\n\tif !strings.Contains(addresses, newAddr) && (err == nil || addresses == \"\") {\n\t\tif addresses != \"\" {\n\t\t\taddresses = addresses + \";\" + newAddr\n\t\t} else {\n\t\t\taddresses = newAddr\n\t\t}\n\n\t\tstmt, _ := db.Prepare(\"update users set remote_addr=? where id=?\")\n\t\tstmt.Exec(addresses, user_id)\n\t}\n\n}", "func (s *OpenconfigOfficeAp_System_Logging_RemoteServers) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Logging_RemoteServers\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func AddSubnet(connectionName string, rsType string, vpcName string, reqInfo cres.SubnetInfo) (*cres.VPCInfo, error) {\n\tcblog.Info(\"call AddSubnet()\")\n\n\t// check empty and trim user inputs\n connectionName, err := EmptyCheckAndTrim(\"connectionName\", connectionName)\n if err != nil {\n\t\tcblog.Error(err)\n return nil, err\n }\n\n vpcName, err = EmptyCheckAndTrim(\"vpcName\", vpcName)\n if err != nil {\n\t\tcblog.Error(err)\n return nil, err\n }\n\n\tcldConn, err := ccm.GetCloudConnection(connectionName)\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\thandler, err := cldConn.CreateVPCHandler()\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tvpcSPLock.Lock(connectionName, vpcName)\n\tdefer vpcSPLock.Unlock(connectionName, vpcName)\n\t// (1) check exist(NameID)\n\tbool_ret, err := iidRWLock.IsExistIID(iidm.SUBNETGROUP, connectionName, vpcName, reqInfo.IId)\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tif bool_ret == true {\n\t\terr := fmt.Errorf(rsType + \"-\" + reqInfo.IId.NameId + \" already exists!\")\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\t// (2) create Resource\n\tiidVPCInfo, err := iidRWLock.GetIID(iidm.IIDSGROUP, connectionName, rsVPC, cres.IID{vpcName, \"\"})\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tsubnetUUID, err := iidm.New(connectionName, rsType, reqInfo.IId.NameId)\n\tif err != nil {\n cblog.Error(err)\n return nil, err\n }\n\n\t// driverIID for driver\n\tsubnetReqNameId := reqInfo.IId.NameId\n\treqInfo.IId = cres.IID{subnetUUID, \"\"}\n\tinfo, err := handler.AddSubnet(getDriverIID(iidVPCInfo.IId), reqInfo)\n\tif err != nil {\n\t\tcblog.Error(err)\n\t\treturn nil, err\n\t}\n\n\t// (3) insert IID\n\t// for Subnet list\n\tfor _, subnetInfo := range info.SubnetInfoList {\t\t\n\t\tif subnetInfo.IId.NameId == reqInfo.IId.NameId { // NameId => SS-UUID\n\t\t\t// key-value structure: ~/{SUBNETGROUP}/{ConnectionName}/{VPC-NameId}/{Subnet-reqNameId} [subnet-driverNameId:subnet-driverSystemId] # VPC NameId => rsType\n\t\t\tsubnetSpiderIId := cres.IID{subnetReqNameId, subnetInfo.IId.NameId + \":\" + subnetInfo.IId.SystemId}\n\t\t\t_, err := iidRWLock.CreateIID(iidm.SUBNETGROUP, connectionName, vpcName, subnetSpiderIId)\n\t\t\tif err != nil {\n\t\t\t\tcblog.Error(err)\n\t\t\t\t// rollback\n\t\t\t\t// (1) for resource\n\t\t\t\tcblog.Info(\"<<ROLLBACK:TRY:VPC-SUBNET-CSP>> \" + subnetInfo.IId.SystemId)\n\t\t\t\t_, err2 := handler.RemoveSubnet(getDriverIID(iidVPCInfo.IId), subnetInfo.IId)\n\t\t\t\tif err2 != nil {\n\t\t\t\t\tcblog.Error(err2)\n\t\t\t\t\treturn nil, fmt.Errorf(err.Error() + \", \" + err2.Error())\n\t\t\t\t}\n\t\t\t\t// (2) for Subnet IID\n\t\t\t\tcblog.Info(\"<<ROLLBACK:TRY:VPC-SUBNET-IID>> \" + subnetInfo.IId.NameId)\n\t\t\t\t_, err3 := iidRWLock.DeleteIID(iidm.SUBNETGROUP, connectionName, vpcName, subnetSpiderIId) // vpcName => rsType\n\t\t\t\tif err3 != nil {\n\t\t\t\t\tcblog.Error(err3)\n\t\t\t\t\treturn nil, fmt.Errorf(err.Error() + \", \" + err3.Error())\n\t\t\t\t}\n\t\t\t\tcblog.Error(err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\t// (3) set ResourceInfo(userIID)\n\tinfo.IId = getUserIID(iidVPCInfo.IId)\n\n\t// set NameId for SubnetInfo List\n\t// create new SubnetInfo List\n\tsubnetInfoList := []cres.SubnetInfo{}\n\tfor _, subnetInfo := range info.SubnetInfoList {\t\t\n\t\tsubnetIIDInfo, err := iidRWLock.GetIIDbySystemID(iidm.SUBNETGROUP, connectionName, vpcName, subnetInfo.IId) // vpcName => rsType\n\t\tif err != nil {\n\t\t\tcblog.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif subnetIIDInfo.IId.NameId != \"\" { // insert only this user created.\n\t\t\tsubnetInfo.IId = getUserIID(subnetIIDInfo.IId)\n\t\t\tsubnetInfoList = append(subnetInfoList, subnetInfo)\n\t\t}\n\t}\n\tinfo.SubnetInfoList = subnetInfoList\n\n\treturn &info, nil\n}", "func (s *OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Config) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Logging_RemoteServers_RemoteServer_Config\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (n RequestDrivenWebServiceNetworkConfig) validate() error {\n\tif n.IsEmpty() {\n\t\treturn nil\n\t}\n\tif err := n.VPC.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"vpc\": %w`, err)\n\t}\n\treturn nil\n}", "func (s *NodesInfoService) Validate() error {\n\treturn nil\n}", "func (a API) AddNodeChk() (isNew bool) {\n\tselect {\n\tcase o := <-a.Ch.(chan AddNodeRes):\n\t\tif o.Err != nil {\n\t\t\ta.Result = o.Err\n\t\t} else {\n\t\t\ta.Result = o.Res\n\t\t}\n\t\tisNew = true\n\tdefault:\n\t}\n\treturn\n}", "func (t *OpenconfigSystem_System_Aaa_ServerGroups_ServerGroup_Servers_Server_Radius) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Aaa_ServerGroups_ServerGroup_Servers_Server_Radius\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (i ImageWithPort) validate() error {\n\tif err := i.Image.validate(); err != nil {\n\t\treturn err\n\t}\n\tif i.Port == nil {\n\t\treturn &errFieldMustBeSpecified{\n\t\t\tmissingField: \"port\",\n\t\t}\n\t}\n\treturn nil\n}", "func (nc *NodeCreate) check() error {\n\tif _, ok := nc.mutation.UUID(); !ok {\n\t\treturn &ValidationError{Name: \"uuid\", err: errors.New(\"ent: missing required field \\\"uuid\\\"\")}\n\t}\n\tif _, ok := nc.mutation.Name(); !ok {\n\t\treturn &ValidationError{Name: \"name\", err: errors.New(\"ent: missing required field \\\"name\\\"\")}\n\t}\n\tif _, ok := nc.mutation.Metadata(); !ok {\n\t\treturn &ValidationError{Name: \"metadata\", err: errors.New(\"ent: missing required field \\\"metadata\\\"\")}\n\t}\n\tif _, ok := nc.mutation.Desc(); !ok {\n\t\treturn &ValidationError{Name: \"desc\", err: errors.New(\"ent: missing required field \\\"desc\\\"\")}\n\t}\n\tif _, ok := nc.mutation.CreateAt(); !ok {\n\t\treturn &ValidationError{Name: \"create_at\", err: errors.New(\"ent: missing required field \\\"create_at\\\"\")}\n\t}\n\tif _, ok := nc.mutation.UpdatedAt(); !ok {\n\t\treturn &ValidationError{Name: \"updated_at\", err: errors.New(\"ent: missing required field \\\"updated_at\\\"\")}\n\t}\n\treturn nil\n}", "func (nS *PostMessageBody) Validate() error {\n\treturn validator.New().Struct(nS)\n}", "func (ut *addUserPayload) Validate() (err error) {\n\tif ut.Name == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"name\"))\n\t}\n\tif ut.Email == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"email\"))\n\t}\n\tif ut.Password == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`request`, \"password\"))\n\t}\n\tif ut.Email != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *ut.Email); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`request.email`, *ut.Email, goa.FormatEmail, err2))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif ok := goa.ValidatePattern(`\\S`, *ut.Name); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`request.name`, *ut.Name, `\\S`))\n\t\t}\n\t}\n\tif ut.Name != nil {\n\t\tif utf8.RuneCountInString(*ut.Name) > 256 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.name`, *ut.Name, utf8.RuneCountInString(*ut.Name), 256, false))\n\t\t}\n\t}\n\tif ut.Password != nil {\n\t\tif utf8.RuneCountInString(*ut.Password) < 10 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`request.password`, *ut.Password, utf8.RuneCountInString(*ut.Password), 10, true))\n\t\t}\n\t}\n\treturn\n}", "func add_node( conn Conn ){\n conn.expressed = false\n\n innovation_num := 0\n node := Node{ is_hidden : true }\n conn1 := Conn{ conn.inNode, node, 1, true, innovation_num }\n conn2 := Conn{ node, conn.outNode, conn.weight, true, innovation_num }\n}", "func (th *treeHead) validate(mac hash.Hash) error {\n\ttag, err := th.expectedTag(mac)\n\tif err != nil {\n\t\treturn err\n\t} else if !hmac.Equal(tag, th.Tag) {\n\t\treturn fmt.Errorf(\"integrity: failed to validate tree head\")\n\t}\n\treturn nil\n}", "func (r *Store) RCSAddRemote(ctx context.Context, name, remote, url string) error {\n\tstore, _ := r.getStore(name)\n\n\treturn store.Storage().AddRemote(ctx, remote, url)\n}", "func (r *Node) validate() field.ErrorList {\n\tvar nodeErrors field.ErrorList\n\n\tif r.Spec.Validator {\n\t\t// validate rpc must be disabled if node is validator\n\t\tif r.Spec.RPC {\n\t\t\terr := field.Invalid(field.NewPath(\"spec\").Child(\"rpc\"), r.Spec.RPC, \"must be false if node is validator\")\n\t\t\tnodeErrors = append(nodeErrors, err)\n\t\t}\n\t\t// validate ws must be disabled if node is validator\n\t\tif r.Spec.WS {\n\t\t\terr := field.Invalid(field.NewPath(\"spec\").Child(\"ws\"), r.Spec.WS, \"must be false if node is validator\")\n\t\t\tnodeErrors = append(nodeErrors, err)\n\t\t}\n\t\t// validate pruning must be disabled if node is validator\n\t\tif pruning := r.Spec.Pruning; pruning != nil && *pruning {\n\t\t\terr := field.Invalid(field.NewPath(\"spec\").Child(\"pruning\"), r.Spec.Pruning, \"must be false if node is validator\")\n\t\t\tnodeErrors = append(nodeErrors, err)\n\t\t}\n\n\t}\n\n\treturn nodeErrors\n}", "func (n NetworkConfig) validate() error {\n\tif n.IsEmpty() {\n\t\treturn nil\n\t}\n\tif err := n.VPC.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"vpc\": %w`, err)\n\t}\n\tif err := n.Connect.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"connect\": %w`, err)\n\t}\n\treturn nil\n}", "func validateOptions(opts *initClusterRegistryOptions) error {\n\topts.apiServerServiceType = v1.ServiceType(opts.apiServerServiceTypeString)\n\tif opts.apiServerServiceType != v1.ServiceTypeLoadBalancer && opts.apiServerServiceType != v1.ServiceTypeNodePort {\n\t\treturn fmt.Errorf(\"invalid %s: %s, should be either %s or %s\", apiserverServiceTypeFlag, opts.apiServerServiceType, v1.ServiceTypeLoadBalancer, v1.ServiceTypeNodePort)\n\t}\n\tif opts.apiServerAdvertiseAddress != \"\" {\n\t\tip := net.ParseIP(opts.apiServerAdvertiseAddress)\n\t\tif ip == nil {\n\t\t\treturn fmt.Errorf(\"invalid %s: %s, should be a valid ip address\", apiserverAdvertiseAddressFlag, opts.apiServerAdvertiseAddress)\n\t\t}\n\t\tif opts.apiServerServiceType != v1.ServiceTypeNodePort {\n\t\t\treturn fmt.Errorf(\"%s should be passed only with '%s=NodePort'\", apiserverAdvertiseAddressFlag, apiserverServiceTypeFlag)\n\t\t}\n\t}\n\n\tif opts.apiServerNodePortPort != 0 {\n\t\tif opts.apiServerServiceType != v1.ServiceTypeNodePort {\n\t\t\treturn fmt.Errorf(\"%s should be passed only with '%s=NodePort'\", apiserverPortFlag, apiserverServiceTypeFlag)\n\t\t}\n\t\topts.apiServerNodePortPortPtr = &opts.apiServerNodePortPort\n\t} else {\n\t\topts.apiServerNodePortPortPtr = nil\n\t}\n\tif opts.apiServerNodePortPort < 0 || opts.apiServerNodePortPort > 65535 {\n\t\treturn fmt.Errorf(\"Please provide a valid port number for %s\", apiserverPortFlag)\n\t}\n\n\treturn nil\n}", "func (a API) AddNode(cmd *btcjson.AddNodeCmd) (e error) {\n\tRPCHandlers[\"addnode\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (m *Node) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif !_Node_Host_Pattern.MatchString(m.GetHost()) {\n\t\treturn NodeValidationError{\n\t\t\tfield: \"Host\",\n\t\t\treason: \"value does not match regex pattern \\\"^\\\\\\\\*?[0-9a-zA-Z-._]+$\\\"\",\n\t\t}\n\t}\n\n\tif val := m.GetPort(); val < 1 || val > 65535 {\n\t\treturn NodeValidationError{\n\t\t\tfield: \"Port\",\n\t\t\treason: \"value must be inside range [1, 65535]\",\n\t\t}\n\t}\n\n\tif m.GetWeight() < 0 {\n\t\treturn NodeValidationError{\n\t\t\tfield: \"Weight\",\n\t\t\treason: \"value must be greater than or equal to 0\",\n\t\t}\n\t}\n\n\tfor key, val := range m.GetMetadata() {\n\t\t_ = val\n\n\t\t// no validation rules for Metadata[key]\n\n\t\tif v, ok := interface{}(val).(interface{ Validate() error }); ok {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\treturn NodeValidationError{\n\t\t\t\t\tfield: fmt.Sprintf(\"Metadata[%v]\", key),\n\t\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\t\tcause: err,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func (o *RepoMigrateCreatedBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateCloneURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateCreated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateDefaultBranch(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateDescription(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateEmpty(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateFork(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateForks(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateFullName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateHTMLURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateMirror(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateName(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateOpenIssues(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePrivate(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSSHURL(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateSize(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateStars(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateUpdated(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateWatchers(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateWebsite(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateOwner(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateParent(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validatePermissions(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (s *OpenconfigInterfaces_Interfaces_Interface_Subinterfaces_Subinterface_Ipv4_Addresses_Address_Vrrp) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_Subinterfaces_Subinterface_Ipv4_Addresses_Address_Vrrp\"], s, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func AddNode(namespace string, clusterName string, req *app.NodeReq) (*model.NodeList, error) {\n\n\t// validate namespace\n\tif err := verifyNamespace(namespace); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get a cluster-entity\n\tcluster := model.NewCluster(namespace, clusterName)\n\tif exists, err := cluster.Select(); err != nil {\n\t\treturn nil, err\n\t} else if exists == false {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Could not be found a cluster '%s'. (namespace=%s)\", clusterName, namespace))\n\t} else if cluster.Status.Phase != model.ClusterPhaseProvisioned {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Unable to add a node. status is '%s'.\", cluster.Status.Phase))\n\t}\n\n\t// get a MCIS\n\tmcis := tumblebug.NewMCIS(namespace, cluster.MCIS)\n\tif exists, err := mcis.GET(); err != nil {\n\t\treturn nil, err\n\t} else if !exists {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Can't be found a MCIS '%s'.\", cluster.MCIS))\n\t}\n\tlogger.Infof(\"[%s.%s] The inquiry has been completed..\", namespace, clusterName)\n\n\tmcisName := cluster.MCIS\n\n\tif cluster.ServiceType == app.ST_SINGLE {\n\t\tif len(mcis.VMs) > 0 {\n\t\t\tconnection := mcis.VMs[0].Config\n\t\t\tfor _, worker := range req.Worker {\n\t\t\t\tif worker.Connection != connection {\n\t\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"The new node must be the same connection config. (connection=%s)\", worker.Connection))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"There is no VMs. (cluster=%s)\", clusterName))\n\t\t}\n\t}\n\n\t// get a provisioner\n\tprovisioner := provision.NewProvisioner(cluster)\n\n\t/*\n\t\tif err := provisioner.BuildAllMachines(); err != nil {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to build provisioner's map: %v\", err))\n\t\t}\n\t*/\n\n\t// get join command\n\tworkerJoinCmd, err := provisioner.NewWorkerJoinCommand()\n\tif err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to get join-command (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Worker join-command inquiry has been completed. (command=%s)\", namespace, clusterName, workerJoinCmd)\n\n\tvar workerCSP app.CSP\n\n\t// create a MCIR & MCIS-vm\n\tidx := cluster.NextNodeIndex(app.WORKER)\n\tvar vmgroupid []string\n\tfor _, worker := range req.Worker {\n\t\tmcir := NewMCIR(namespace, app.WORKER, *worker)\n\t\treason, msg := mcir.CreateIfNotExist()\n\t\tif reason != \"\" {\n\t\t\treturn nil, errors.New(msg)\n\t\t} else {\n\t\t\tfor i := 0; i < mcir.vmCount; i++ {\n\t\t\t\tname := lang.GenerateNewNodeName(string(app.WORKER), idx)\n\t\t\t\tif i == 0 {\n\t\t\t\t\tworkerCSP = mcir.csp\n\t\t\t\t}\n\t\t\t\tvm := mcir.NewVM(namespace, name, mcisName, \"\", worker.RootDisk.Type, worker.RootDisk.Size)\n\t\t\t\tif err := vm.POST(); err != nil {\n\t\t\t\t\tcleanUpNodes(*provisioner)\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tvmgroupid = append(vmgroupid, name)\n\t\t\t\tprovisioner.AppendWorkerNodeMachine(name+\"-1\", mcir.csp, mcir.region, mcir.zone, mcir.credential)\n\t\t\t\tidx = idx + 1\n\t\t\t}\n\t\t}\n\t}\n\t// Pull out the added VMlist\n\tif _, err := mcis.GET(); err != nil {\n\t\treturn nil, err\n\t}\n\tvms := []tumblebug.VM{}\n\tfor _, mcisvm := range mcis.VMs {\n\t\tfor _, grupid := range vmgroupid {\n\t\t\tif mcisvm.VmGroupId == grupid {\n\t\t\t\tmcisvm.Namespace = namespace\n\t\t\t\tmcisvm.McisName = mcisName\n\t\t\t\tvms = append(vms, mcisvm)\n\t\t\t}\n\t\t}\n\t}\n\tlogger.Infof(\"[%s.%s] MCIS(vm) creation has been completed. (len=%d)\", namespace, clusterName, len(vms))\n\n\t// save nodes metadata\n\tif nodes, err := provisioner.BindVM(vms); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tcluster.Nodes = append(cluster.Nodes, nodes...)\n\t\tif err := cluster.PutStore(); err != nil {\n\t\t\tcleanUpNodes(*provisioner)\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity. (cause='%v')\", err))\n\t\t}\n\t}\n\n\t// kubernetes provisioning : bootstrap\n\ttime.Sleep(2 * time.Second)\n\tif err := provisioner.Bootstrap(); err != nil {\n\t\tcleanUpNodes(*provisioner)\n\t\treturn nil, errors.New(fmt.Sprintf(\"Bootstrap failed. (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Bootstrap has been completed.\", namespace, clusterName)\n\n\t// kubernetes provisioning : worker node join\n\tfor _, machine := range provisioner.WorkerNodeMachines {\n\t\tif err := machine.JoinWorker(&workerJoinCmd); err != nil {\n\t\t\tcleanUpNodes(*provisioner)\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Fail to worker-node join. (node=%s)\", machine.Name))\n\t\t}\n\t}\n\tlogger.Infof(\"[%s.%s] Woker-nodes join has been completed.\", namespace, clusterName)\n\n\t/* FIXME: after joining, check the worker is ready */\n\n\t// assign node labels (topology.cloud-barista.github.io/csp , topology.kubernetes.io/region, topology.kubernetes.io/zone)\n\tif err = provisioner.AssignNodeLabelAnnotation(); err != nil {\n\t\tlogger.Warnf(\"[%s.%s] Failed to assign node labels (cause='%v')\", namespace, clusterName, err)\n\t} else {\n\t\tlogger.Infof(\"[%s.%s] Node label assignment has been completed.\", namespace, clusterName)\n\t}\n\n\t// kubernetes provisioning : add some actions for cloud-controller-manager\n\tif provisioner.Cluster.ServiceType == app.ST_SINGLE {\n\t\tif workerCSP == app.CSP_AWS {\n\t\t\t// check whether AWS IAM roles exists and are same\n\t\t\tvar bFail bool = false\n\t\t\tvar bEmptyOrDiff bool = false\n\t\t\tvar msgError string\n\t\t\tvar awsWorkerRole string\n\n\t\t\tawsWorkerRole = req.Worker[0].Role\n\t\t\tif awsWorkerRole == \"\" {\n\t\t\t\tbEmptyOrDiff = true\n\t\t\t}\n\n\t\t\tif bEmptyOrDiff == false {\n\t\t\t\tfor _, worker := range req.Worker {\n\t\t\t\t\tif awsWorkerRole != worker.Role {\n\t\t\t\t\t\tbEmptyOrDiff = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif bEmptyOrDiff == true {\n\t\t\t\tbFail = true\n\t\t\t\tmsgError = \"Role should be assigned\"\n\t\t\t} else {\n\t\t\t\tif err := awsPrepareCCM(req.Worker[0].Connection, clusterName, vms, provisioner, \"\", awsWorkerRole); err != nil {\n\t\t\t\t\tbFail = true\n\t\t\t\t\tmsgError = \"Failed to prepare cloud-controller-manager\"\n\t\t\t\t} else {\n\t\t\t\t\t// Success\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif bFail == true {\n\t\t\t\tcleanUpNodes(*provisioner)\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity: %v)\", msgError))\n\t\t\t} else {\n\t\t\t\t// Success\n\t\t\t\tlogger.Infof(\"[%s.%s] CCM ready has been completed.\", namespace, clusterName)\n\t\t\t}\n\t\t}\n\t}\n\n\t// save nodes metadata & update status\n\tfor _, node := range cluster.Nodes {\n\t\tnode.CreatedTime = lang.GetNowUTC()\n\t}\n\tif err := cluster.PutStore(); err != nil {\n\t\tcleanUpNodes(*provisioner)\n\t\treturn nil, errors.New(fmt.Sprintf(\"Failed to add node entity. (cause='%v')\", err))\n\t}\n\tlogger.Infof(\"[%s.%s] Nodes creation has been completed.\", namespace, clusterName)\n\n\tnodes := model.NewNodeList(namespace, clusterName)\n\tnodes.Items = cluster.Nodes\n\treturn nodes, nil\n}", "func (SecurityGroupsConfig) validate() error {\n\treturn nil\n}", "func LicenseRemoteValidation(license string) bool {\n\tlicense_upper := strings.ToUpper(license) //change it to upper case\n\n\tif len(license_json.Licenses) == 0 {\n\t\tjson_data, err := Read(RemoteLicenseURL)\n\t\tif err != nil {\n\t\t\t// TODO() i18n\n\t\t\terrString := wski18n.T(\"Failed to get the remote license json.\\n\")\n\t\t\twhisk.Debug(whisk.DbgError, errString)\n\t\t\treturn false\n\t\t}\n\n\t\t//parse json\n\t\terr = json.Unmarshal(json_data, &license_json)\n\t\tif err != nil || len(license_json.Licenses) == 0 {\n\t\t\t// TODO() i18n\n\t\t\terrString := wski18n.T(\"Failed to parse the remote license json.\\n\")\n\t\t\twhisk.Debug(whisk.DbgError, errString)\n\t\t\treturn false\n\t\t}\n\t}\n\n\t//check license\n\tfor _, licenseobj := range license_json.Licenses {\n\t\tif strings.ToUpper(licenseobj.LicenseID) == license_upper {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (i ImageWithHealthcheckAndOptionalPort) validate() error {\n\tvar err error\n\tif err = i.ImageWithOptionalPort.validate(); err != nil {\n\t\treturn err\n\t}\n\tif err = i.HealthCheck.validate(); err != nil {\n\t\treturn fmt.Errorf(`validate \"healthcheck\": %w`, err)\n\t}\n\treturn nil\n}", "func (vr *VirtualResource) Create(item VirtualServerConfig) error {\n\tif err := vr.c.ModQuery(\"POST\", BasePath+VirtualEndpoint, item); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (n *NetworkBuilder) AddNode(nodeID string, subnet string, port uint, forceHidden bool) (*NetworkBuilder, error) {\n\tn.NodeID = nodeID\n\n\tif subnet == \"\" {\n\t\treturn n, fmt.Errorf(\"subnet cannot be empty\")\n\t}\n\tipnet, err := types.ParseIPNet(subnet)\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"invalid subnet\")\n\t}\n\n\tif port == 0 {\n\t\tport, err = n.pickPort()\n\t\tif err != nil {\n\t\t\treturn n, errors.Wrap(err, \"failed to pick wireguard port\")\n\t\t}\n\t}\n\n\tprivateKey, err := wgtypes.GeneratePrivateKey()\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"error during wireguard key generation\")\n\t}\n\tsk := privateKey.String()\n\n\tpk, err := crypto.KeyFromID(pkg.StrIdentifier(nodeID))\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"failed to parse nodeID\")\n\t}\n\n\tencrypted, err := crypto.Encrypt([]byte(sk), pk)\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"failed to encrypt private key\")\n\t}\n\n\tpubSubnets, err := n.getEndPointAddrs(pkg.StrIdentifier(nodeID))\n\tif err != nil {\n\t\treturn n, errors.Wrap(err, \"failed to get node public endpoints\")\n\t}\n\tvar endpoints []net.IP\n\tif !forceHidden {\n\t\tfor _, sn := range pubSubnets {\n\t\t\tendpoints = append(endpoints, sn.IP)\n\t\t}\n\t}\n\n\tnr := NetResource{\n\t\tNetworkNetResource: workloads.NetworkNetResource{\n\t\t\tNodeId: nodeID,\n\t\t\tIprange: schema.IPRange{ipnet.IPNet},\n\t\t\tWireguardListenPort: int64(port),\n\t\t\tWireguardPublicKey: privateKey.PublicKey().String(),\n\t\t\tWireguardPrivateKeyEncrypted: hex.EncodeToString(encrypted),\n\t\t},\n\t\tPubEndpoints: endpoints,\n\t}\n\n\tn.NetResources = append(n.NetResources, nr)\n\n\tif err = n.generatePeers(); err != nil {\n\t\treturn n, errors.Wrap(err, \"failed to generate peers\")\n\t}\n\n\treturn n, nil\n}", "func (n *Node) RegisterWithRingServer(ringUrl string) {\n nodeDataArray := []ConHash.NodeData {}\n //copy(tempNodeDataArray,localRing.ringNodeDataArray)\n //TODO: Can we do deduplication on the node side?\n for i := 0; i < n.NumTokens +1; i ++ {\n id := fmt.Sprintf(\"%s%d\", n.CName, i)\n hash := ConHash.HashMD5(id, 0, RING_MAX_ID)\n nodeDataArray = append(nodeDataArray, ConHash.NewNodeData(id, n.CName, hash, n.IP, n.Port))\n }\n log.Println(\"Length: \", len(nodeDataArray))\n n.NodeDataArray = nodeDataArray\n requestBody, err := json.Marshal(nodeDataArray)\n // Send the Ring Server\n //TODO: Refactor this into a function\n //TODO: Change RING_URL to be accessed from an attribute\n postURL := fmt.Sprintf(\"%s/%s\", ringUrl, REGISTER_ENDPOINT)\n resp, err := http.Post(postURL, \"application/json\", bytes.NewReader(requestBody))\n if err != nil {\n log.Println(\"Check if RingServer is up and running\")\n log.Fatalln(err)\n }\n defer resp.Body.Close()\n\n body, err := ioutil.ReadAll(resp.Body)\n //TODO: print status code instead of the response itself\n fmt.Println(\"Response from registering w Ring Server: \", string(body))\n if err != nil {\n log.Fatalln(err)\n }\n}", "func (t *OpenconfigInterfaces_Interfaces_Interface_Subinterfaces_Subinterface_Ipv4_Addresses_Address_Vrrp) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigInterfaces_Interfaces_Interface_Subinterfaces_Subinterface_Ipv4_Addresses_Address_Vrrp\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (csrv *CreateServerInput) CreateServer(con aws.EstablishConnectionInput) ([]ServerResponse, error) {\n\n\t//get the relative sessions before proceeding further\n\tec2, sesserr := con.EstablishConnection()\n\tif sesserr != nil {\n\t\treturn nil, sesserr\n\t}\n\n\t// I will make a decision which security group to pick\n\tsubInput := GetNetworksInput{SubnetIds: []string{csrv.SubnetId}}\n\tsubResult, suberr := subInput.FindSubnet(con)\n\tif suberr != nil {\n\t\treturn nil, suberr\n\t}\n\n\tif subResult != true {\n\t\treturn nil, fmt.Errorf(\"Could not find the entered SUBNET, please enter valid/existing SUBNET id\")\n\t}\n\n\tinst := new(aws.CreateServerInput)\n\n\tswitch csrv.SecGroupId {\n\tcase \"\":\n\t\tvpcRes, vpcerr := subInput.GetVpcFromSubnet(con)\n\t\tif vpcerr != nil {\n\t\t\treturn nil, vpcerr\n\t\t}\n\n\t\tsecInput := NetworkComponentInput{VpcIds: []string{vpcRes.VpcId}}\n\t\tsecRes, secerr := secInput.GetSecFromVpc(con)\n\t\tif secerr != nil {\n\t\t\treturn nil, nil\n\t\t}\n\t\tinst.SecurityGroups = secRes.SecGroupIds\n\n\tdefault:\n\t\tinst.SecurityGroups = []string{csrv.SecGroupId}\n\t}\n\n\t// I will be the spoc for the instance creation with the userdata passed to me\n\tswitch csrv.UserData {\n\tcase \"\":\n\t\tinst.UserData = b64.StdEncoding.EncodeToString([]byte(\"echo 'nothing'\"))\n\tdefault:\n\t\tinst.UserData = b64.StdEncoding.EncodeToString([]byte(csrv.UserData))\n\t}\n\n\tswitch csrv.MinCount {\n\tcase 0:\n\t\tinst.MinCount = 1\n\tdefault:\n\t\tinst.MinCount = csrv.MinCount\n\t}\n\n\tswitch csrv.MaxCount {\n\tcase 0:\n\t\tinst.MaxCount = 1\n\tdefault:\n\t\tinst.MaxCount = csrv.MaxCount\n\t}\n\n\tinst.ImageId = csrv.ImageId\n\tinst.InstanceType = csrv.InstanceType\n\tinst.KeyName = csrv.KeyName\n\tinst.AssignPubIp = csrv.AssignPubIp\n\tinst.SubnetId = csrv.SubnetId\n\t// support for custom ebs mapping will be rolled out soon\n\tserverCreateResult, err := ec2.CreateInstance(inst)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstanceIds := make([]string, 0)\n\tfor _, instance := range serverCreateResult.Instances {\n\t\tinstanceIds = append(instanceIds, *instance.InstanceId)\n\t}\n\n\t// I will make program wait until instance become running\n\twaitErr := ec2.WaitTillInstanceAvailable(\n\t\t&aws.DescribeComputeInput{\n\t\t\tInstanceIds: instanceIds,\n\t\t},\n\t)\n\tif waitErr != nil {\n\t\treturn nil, waitErr\n\t}\n\n\t// creating tags for the server\n\tfor i, instance := range instanceIds {\n\t\ttags := new(Tag)\n\t\ttags.Resource = instance\n\t\ttags.Name = \"Name\"\n\t\ttags.Value = csrv.InstanceName + \"-\" + strconv.Itoa(i)\n\t\t_, tagErr := tags.CreateTags(con)\n\t\tif tagErr != nil {\n\t\t\treturn nil, tagErr\n\t\t}\n\t}\n\n\t//fetching the details of server\n\tresult, serverr := ec2.DescribeInstance(\n\t\t&aws.DescribeComputeInput{\n\t\t\tInstanceIds: instanceIds,\n\t\t},\n\t)\n\tif serverr != nil {\n\t\treturn nil, serverr\n\t}\n\n\ttype serverResponse struct {\n\t\tname string\n\t\tinstanceId string\n\t\tipaddress string\n\t\tprivatedns string\n\t\tpublicIp string\n\t\tcreatedon string\n\t}\n\n\tresponse := make([]serverResponse, 0)\n\tcreateServerResponse := make([]ServerResponse, 0)\n\n\tif csrv.GetRaw == true {\n\t\tcreateServerResponse = append(createServerResponse, ServerResponse{CreateInstRaw: result, Cloud: \"Amazon\"})\n\t\treturn createServerResponse, nil\n\t}\n\n\t// fetching the instance details which is created in previous process\n\tfor _, reservation := range result.Reservations {\n\t\tfor _, instance := range reservation.Instances {\n\t\t\tif csrv.AssignPubIp == true {\n\t\t\t\tresponse = append(response, serverResponse{name: *instance.Tags[0].Value, instanceId: *instance.InstanceId, ipaddress: *instance.PrivateIpAddress, privatedns: *instance.PrivateDnsName, publicIp: *instance.PublicIpAddress, createdon: (*instance.LaunchTime).String()})\n\t\t\t} else {\n\t\t\t\tresponse = append(response, serverResponse{name: *instance.Tags[0].Value, instanceId: *instance.InstanceId, ipaddress: *instance.PrivateIpAddress, privatedns: *instance.PrivateDnsName, createdon: (*instance.LaunchTime).String()})\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, server := range response {\n\t\tcreateServerResponse = append(createServerResponse, ServerResponse{InstanceName: server.name, InstanceId: server.instanceId, SubnetId: csrv.SubnetId, PrivateIpAddress: server.ipaddress, PublicIpAddress: server.publicIp, PrivateDnsName: server.privatedns, CreatedOn: server.createdon, Cloud: \"Amazon\"})\n\t}\n\n\treturn createServerResponse, nil\n}" ]
[ "0.6836557", "0.68296754", "0.5618899", "0.53128964", "0.5140611", "0.47949532", "0.47500297", "0.46956733", "0.46739462", "0.46342108", "0.46221286", "0.46184957", "0.46152475", "0.4608739", "0.4607076", "0.45492345", "0.45425236", "0.45373106", "0.45265538", "0.45252773", "0.4517735", "0.4517169", "0.4504657", "0.4498629", "0.44855738", "0.44793287", "0.44731212", "0.44716254", "0.44616503", "0.44548422", "0.44479087", "0.44244695", "0.4424263", "0.44218877", "0.44210258", "0.4412748", "0.44114047", "0.4410579", "0.44074064", "0.44023302", "0.4397411", "0.4392859", "0.4388149", "0.43870974", "0.4383773", "0.43832222", "0.43827668", "0.43735364", "0.43679097", "0.43658355", "0.43589103", "0.43504524", "0.43452176", "0.4343968", "0.4341453", "0.43320268", "0.43317166", "0.43117133", "0.43092293", "0.43047154", "0.43045986", "0.43045875", "0.4303211", "0.43003127", "0.4297857", "0.42965335", "0.42874172", "0.4286974", "0.42820185", "0.42816514", "0.42806056", "0.42793387", "0.4277824", "0.4276533", "0.42753494", "0.4275065", "0.42675856", "0.42663133", "0.42626268", "0.4255754", "0.42532602", "0.4252789", "0.4251533", "0.4246069", "0.4244829", "0.4243212", "0.4241374", "0.42329505", "0.42310178", "0.42309526", "0.42245358", "0.42168704", "0.42156017", "0.42143574", "0.4212413", "0.4212056", "0.42094085", "0.42064613", "0.42064005", "0.420444" ]
0.68412226
0
Set of ARNs of the matched Image Builder Infrastructure Configurations.
func (o GetInfrastructureConfigurationsResultOutput) Arns() pulumi.StringArrayOutput { return o.ApplyT(func(v GetInfrastructureConfigurationsResult) []string { return v.Arns }).(pulumi.StringArrayOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DefaultARMImages() ImageSelector {\n\treturn defaultARMImages\n}", "func (d *aciDriver) Config() map[string]string {\n\treturn map[string]string{\n\t\t\"CNAB_AZURE_VERBOSE\": \"Increase verbosity. true, false are supported values\",\n\t\t\"CNAB_AZURE_CLIENT_ID\": \"AAD Client ID for Azure account authentication - used to authenticate to Azure for ACI creation\",\n\t\t\"CNAB_AZURE_CLIENT_SECRET\": \"AAD Client Secret for Azure account authentication - used to authenticate to Azure for ACI creation\",\n\t\t\"CNAB_AZURE_TENANT_ID\": \"Azure AAD Tenant Id Azure account authentication - used to authenticate to Azure for ACI creation\",\n\t\t\"CNAB_AZURE_SUBSCRIPTION_ID\": \"Azure Subscription Id - this is the subscription to be used for ACI creation, if not specified the default subscription is used\",\n\t\t\"CNAB_AZURE_APP_ID\": \"Azure Application Id - this is the application to be used to authenticate to Azure\",\n\t\t\"CNAB_AZURE_RESOURCE_GROUP\": \"The name of the existing Resource Group to create the ACI instance in, if not specified a Resource Group will be created\",\n\t\t\"CNAB_AZURE_LOCATION\": \"The location to create the ACI Instance in\",\n\t\t\"CNAB_AZURE_NAME\": \"The name of the ACI instance to create - if not specified a name will be generated\",\n\t\t\"CNAB_AZURE_DELETE_RESOURCES\": \"Delete RG and ACI instance created - default is true useful to set to false for debugging - only deletes RG if it was created by the driver\",\n\t\t\"CNAB_AZURE_MSI_TYPE\": \"This can be set to user or system\",\n\t\t\"CNAB_AZURE_SYSTEM_MSI_ROLE\": \"The role to be asssigned to System MSI User - used if CNAB_AZURE_ACI_MSI_TYPE == system, if this is null or empty then the role defaults to contributor\",\n\t\t\"CNAB_AZURE_SYSTEM_MSI_SCOPE\": \"The scope to apply the role to System MSI User - will attempt to set scope to the Resource Group that the ACI Instance is being created in if not set\",\n\t\t\"CNAB_AZURE_USER_MSI_RESOURCE_ID\": \"The resource Id of the MSI User - required if CNAB_AZURE_ACI_MSI_TYPE == User \",\n\t\t\"CNAB_AZURE_PROPAGATE_CREDENTIALS\": \"If this is set to true the credentials used to Launch the Driver are propagated to the invocation image in an ENV variable, the CNAB_AZURE prefix will be relaced with AZURE_, default is false\",\n\t\t\"CNAB_AZURE_USE_CLIENT_CREDS_FOR_REGISTRY_AUTH\": \"If this is set to true the CNAB_AZURE_CLIENT_ID and CNAB_AZURE_CLIENT_SECRET are also used for authentication to ACR\",\n\t\t\"CNAB_AZURE_REGISTRY_USERNAME\": \"The username for authenticating to the container registry\",\n\t\t\"CNAB_AZURE_REGISTRY_PASSWORD\": \"The password for authenticating to the container registry\",\n\t\t\"CNAB_AZURE_STATE_FILESHARE\": \"The File Share for Azure State volume\",\n\t\t\"CNAB_AZURE_STATE_STORAGE_ACCOUNT_NAME\": \"The Storage Account for the Azure State File Share\",\n\t\t\"CNAB_AZURE_STATE_STORAGE_ACCOUNT_KEY\": \"The Storage Key for the Azure State File Share\",\n\t\t\"CNAB_AZURE_STATE_MOUNT_POINT\": \"The mount point location for state volume\",\n\t\t\"CNAB_AZURE_DELETE_OUTPUTS_FROM_FILESHARE\": \"Any Outputs Created in the fileshare are deleted on completion\",\n\t\t\"CNAB_AZURE_DEBUG_CONTAINER\": \"Replaces /cnab/app/run with tail -f /dev/null so that container can be connected to and debugged\",\n\t}\n}", "func (m *Application) SetIdentifierUris(value []string)() {\n m.identifierUris = value\n}", "func (o OceanFiltersOutput) Architectures() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v OceanFilters) []string { return v.Architectures }).(pulumi.StringArrayOutput)\n}", "func getAmlAbisConfig() []archConfig {\n\treturn []archConfig{\n\t\t{\"arm\", \"armv7-a-neon\", \"\", []string{\"armeabi-v7a\"}},\n\t\t{\"arm64\", \"armv8-a\", \"\", []string{\"arm64-v8a\"}},\n\t\t{\"x86\", \"\", \"\", []string{\"x86\"}},\n\t\t{\"x86_64\", \"\", \"\", []string{\"x86_64\"}},\n\t}\n}", "func (b *ATNConfigSet) Alts() *BitSet {\n\talts := NewBitSet()\n\tfor _, it := range b.configs {\n\t\talts.add(it.GetAlt())\n\t}\n\treturn alts\n}", "func (a *ImageSliceAttribute) Anchors() []*anchor.Anchor {\n\treturn a.anchors\n}", "func (o ApplicationSpecSourceKustomizeOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationSpecSourceKustomize) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func (o OceanFiltersPtrOutput) Architectures() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *OceanFilters) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Architectures\n\t}).(pulumi.StringArrayOutput)\n}", "func (m *Application) GetIdentifierUris()([]string) {\n return m.identifierUris\n}", "func (o GetSecretsResultOutput) Arns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetSecretsResult) []string { return v.Arns }).(pulumi.StringArrayOutput)\n}", "func getNdkAbisConfig() []archConfig {\n\treturn []archConfig{\n\t\t{\"arm\", \"armv7-a\", \"\", []string{\"armeabi-v7a\"}},\n\t\t{\"arm64\", \"armv8-a\", \"\", []string{\"arm64-v8a\"}},\n\t\t{\"x86\", \"\", \"\", []string{\"x86\"}},\n\t\t{\"x86_64\", \"\", \"\", []string{\"x86_64\"}},\n\t}\n}", "func (g GuardDutyInstances) ResourceIdentifiers() []string {\n\treturn g.DetectorIds\n}", "func (r QuayAdapter) GetImageNames() ([]string, error) {\n\tlog.Debug(\"QuayAdapter::GetImages\")\n\tlog.Debug(\"BundleSpecLabel: %s\", BundleSpecLabel)\n\tlog.Debug(\"Loading image list for quay.io Org: [ %v ]\", r.config.Org)\n\n\tvar imageList []string\n\n\t// check if we're configured for specific images\n\tif len(r.config.Images) > 0 {\n\t\tlog.Debugf(\"Configured to use images: %v\", r.config.Images)\n\t\timageList = append(imageList, r.config.Images...)\n\t}\n\n\t// discover images\n\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(quayCatalogURL, r.config.URL, r.config.Org), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %v\", r.config.Token))\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to load catalog response at %s - %v\", fmt.Sprintf(quayCatalogURL, r.config.URL, r.config.Org), err)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tcatalogResp := quayImageResponse{}\n\terr = json.NewDecoder(resp.Body).Decode(&catalogResp)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to decode Catalog response from '%s'\", fmt.Sprintf(quayCatalogURL, r.config.URL, r.config.Org))\n\t\treturn nil, err\n\t}\n\n\tfor _, repo := range catalogResp.Repositories {\n\t\timageList = append(imageList, repo.Name)\n\t}\n\n\tif len(imageList) == 0 {\n\t\tlog.Warn(\"image list is empty. No images were discovered\")\n\t\treturn imageList, nil\n\t}\n\n\tvar uniqueList []string\n\timageMap := make(map[string]struct{})\n\tfor _, image := range imageList {\n\t\timageMap[image] = struct{}{}\n\t}\n\n\t// create a unique image list\n\tfor key := range imageMap {\n\t\tuniqueList = append(uniqueList, key)\n\t}\n\treturn uniqueList, nil\n}", "func (o LookupDatasetGroupResultOutput) DatasetArns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupDatasetGroupResult) []string { return v.DatasetArns }).(pulumi.StringArrayOutput)\n}", "func (m MultiRESTMapper) AliasesForResource(resource string) (aliases []string, has bool) {\n\tfor _, t := range m {\n\t\taliases, has = t.AliasesForResource(resource)\n\t\tif has {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func WithInstancers(i Instancers) Option {\n\treturn func(e *environment) {\n\t\te.instancers = i.Copy()\n\t}\n}", "func (o ApplicationStatusSyncComparedToSourceKustomizeOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationStatusSyncComparedToSourceKustomize) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func (o LookupAuthorizerResultOutput) ProviderArns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupAuthorizerResult) []string { return v.ProviderArns }).(pulumi.StringArrayOutput)\n}", "func (o ApplicationStatusSummaryOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationStatusSummary) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func (o SecurityProfileOutput) TargetArns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *SecurityProfile) pulumi.StringArrayOutput { return v.TargetArns }).(pulumi.StringArrayOutput)\n}", "func (o TriggerBuildOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TriggerBuild) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func (o ApplicationOperationSyncSourceKustomizeOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationOperationSyncSourceKustomize) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func (ref ostreeReference) PolicyConfigurationNamespaces() []string {\n\trepo, _, gotTag := strings.Cut(ref.image, \":\")\n\tif !gotTag { // Coverage: Should never happen, NewReference above ensures ref.image has a :tag.\n\t\tpanic(fmt.Sprintf(\"Internal inconsistency: ref.image value %q does not have a :tag\", ref.image))\n\t}\n\tname := repo\n\tres := []string{}\n\tfor {\n\t\tres = append(res, fmt.Sprintf(\"%s:%s\", ref.repo, name))\n\n\t\tlastSlash := strings.LastIndex(name, \"/\")\n\t\tif lastSlash == -1 {\n\t\t\tbreak\n\t\t}\n\t\tname = name[:lastSlash]\n\t}\n\treturn res\n}", "func GetImageOverrides() map[string]string {\n\timageOverrides := make(map[string]string)\n\n\t// First check for environment variables containing the 'OPERAND_IMAGE_' prefix\n\tfor _, e := range os.Environ() {\n\t\tkeyValuePair := strings.SplitN(e, \"=\", 2)\n\t\tif strings.HasPrefix(keyValuePair[0], OperandImagePrefix) {\n\t\t\tkey := strings.ToLower(strings.Replace(keyValuePair[0], OperandImagePrefix, \"\", -1))\n\t\t\timageOverrides[key] = keyValuePair[1]\n\t\t}\n\t}\n\n\t// If entries exist containing operand image prefix, return\n\tif len(imageOverrides) > 0 {\n\t\tlogf.Info(\"Found image overrides from environment variables set by operand image prefix\")\n\t\treturn imageOverrides\n\t}\n\n\t// If no image overrides found, check 'RELATED_IMAGE_' prefix\n\tfor _, e := range os.Environ() {\n\t\tkeyValuePair := strings.SplitN(e, \"=\", 2)\n\t\tif strings.HasPrefix(keyValuePair[0], OSBSImagePrefix) {\n\t\t\tkey := strings.ToLower(strings.Replace(keyValuePair[0], OSBSImagePrefix, \"\", -1))\n\t\t\timageOverrides[key] = keyValuePair[1]\n\t\t}\n\t}\n\n\t// If entries exist containing related image prefix, return\n\tif len(imageOverrides) > 0 {\n\t\tlogf.Info(\"Found image overrides from environment variables set by related image prefix\")\n\t}\n\n\treturn imageOverrides\n}", "func (evnot *EventNotifier) GetARNList(onlyActive bool) []string {\n\tarns := []string{}\n\tif evnot == nil {\n\t\treturn arns\n\t}\n\tregion := globalSite.Region\n\tfor targetID, target := range evnot.targetList.TargetMap() {\n\t\t// httpclient target is part of ListenNotification\n\t\t// which doesn't need to be listed as part of the ARN list\n\t\t// This list is only meant for external targets, filter\n\t\t// this out pro-actively.\n\t\tif !strings.HasPrefix(targetID.ID, \"httpclient+\") {\n\t\t\tif onlyActive {\n\t\t\t\tif _, err := target.IsActive(); err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tarns = append(arns, targetID.ToARN(region).String())\n\t\t}\n\t}\n\n\treturn arns\n}", "func (o ApplicationSpecSourceKustomizePtrOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecSourceKustomize) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Images\n\t}).(pulumi.StringArrayOutput)\n}", "func (o ApplicationStatusHistorySourceKustomizeOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationStatusHistorySourceKustomize) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func (o TriggerBuildArtifactsOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TriggerBuildArtifacts) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func (o ReplicationSetOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReplicationSet) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}", "func (o ApplicationStatusOperationStateOperationSyncSourceKustomizeOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateOperationSyncSourceKustomize) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func Configure(p *config.Provider) {\n\tp.AddResourceConfigurator(\"aws_rds_cluster\", func(r *config.Resource) {\n\t\tr.Version = common.VersionV1Alpha2\n\t\tr.ExternalName = config.ExternalName{\n\t\t\tSetIdentifierArgumentFn: func(base map[string]interface{}, name string) {\n\t\t\t\tbase[\"cluster_identifier\"] = name\n\t\t\t},\n\t\t\tOmittedFields: []string{\n\t\t\t\t\"cluster_identifier\",\n\t\t\t\t\"cluster_identifier_prefix\",\n\t\t\t},\n\t\t\tGetExternalNameFn: config.IDAsExternalName,\n\t\t\tGetIDFn: config.ExternalNameAsID,\n\t\t}\n\t\tr.References = config.References{\n\t\t\t\"s3_import.bucket_name\": {\n\t\t\t\tType: \"github.com/crossplane-contrib/provider-jet-aws/apis/s3/v1alpha2.Bucket\",\n\t\t\t},\n\t\t\t\"vpc_security_group_ids\": {\n\t\t\t\tType: \"github.com/crossplane-contrib/provider-jet-aws/apis/ec2/v1alpha2.SecurityGroup\",\n\t\t\t\tRefFieldName: \"VpcSecurityGroupIdRefs\",\n\t\t\t\tSelectorFieldName: \"VpcSecurityGroupIdSelector\",\n\t\t\t},\n\t\t\t\"restore_to_point_in_time.source_cluster_identifier\": {\n\t\t\t\tType: \"Cluster\",\n\t\t\t},\n\t\t\t\"db_subnet_group_name\": {\n\t\t\t\tType: \"SubnetGroup\",\n\t\t\t},\n\t\t}\n\t\tr.UseAsync = true\n\t})\n\n\tp.AddResourceConfigurator(\"aws_db_instance\", func(r *config.Resource) {\n\t\tr.Version = common.VersionV1Alpha2\n\t\tr.ExternalName = config.ExternalName{\n\t\t\tSetIdentifierArgumentFn: func(base map[string]interface{}, name string) {\n\t\t\t\tbase[\"identifier\"] = name\n\t\t\t},\n\t\t\tOmittedFields: []string{\n\t\t\t\t\"identifier\",\n\t\t\t\t\"identifier_prefix\",\n\t\t\t},\n\t\t\tGetExternalNameFn: config.IDAsExternalName,\n\t\t\tGetIDFn: config.ExternalNameAsID,\n\t\t}\n\t\tr.References = config.References{\n\t\t\t\"restore_to_point_in_time.source_db_instance_identifier\": {\n\t\t\t\tType: \"Instance\",\n\t\t\t},\n\t\t\t\"s3_import.bucket_name\": {\n\t\t\t\tType: \"github.com/crossplane-contrib/provider-jet-aws/apis/s3/v1alpha2.Bucket\",\n\t\t\t},\n\t\t\t\"kms_key_id\": {\n\t\t\t\tType: \"github.com/crossplane-contrib/provider-jet-aws/apis/kms/v1alpha2.Key\",\n\t\t\t},\n\t\t\t\"performance_insights_kms_key_id\": {\n\t\t\t\tType: \"github.com/crossplane-contrib/provider-jet-aws/apis/kms/v1alpha2.Key\",\n\t\t\t},\n\t\t\t\"restore_to_point_in_time.source_cluster_identifier\": {\n\t\t\t\tType: \"Cluster\",\n\t\t\t},\n\t\t\t\"security_group_names\": {\n\t\t\t\tType: \"github.com/crossplane-contrib/provider-jet-aws/apis/ec2/v1alpha2.SecurityGroup\",\n\t\t\t\tRefFieldName: \"SecurityGroupNameRefs\",\n\t\t\t\tSelectorFieldName: \"SecurityGroupNameSelector\",\n\t\t\t},\n\t\t\t\"vpc_security_group_ids\": {\n\t\t\t\tType: \"github.com/crossplane-contrib/provider-jet-aws/apis/ec2/v1alpha2.SecurityGroup\",\n\t\t\t\tRefFieldName: \"VpcSecurityGroupIdRefs\",\n\t\t\t\tSelectorFieldName: \"VpcSecurityGroupIdSelector\",\n\t\t\t},\n\t\t\t\"parameter_group_name\": {\n\t\t\t\tType: \"ParameterGroup\",\n\t\t\t},\n\t\t\t\"db_subnet_group_name\": {\n\t\t\t\tType: \"SubnetGroup\",\n\t\t\t},\n\t\t}\n\t\tr.UseAsync = true\n\t})\n\tp.AddResourceConfigurator(\"aws_db_parameter_group\", func(r *config.Resource) {\n\t\tr.Version = common.VersionV1Alpha2\n\t\tr.ExternalName = config.NameAsIdentifier\n\t})\n\tp.AddResourceConfigurator(\"aws_db_subnet_group\", func(r *config.Resource) {\n\t\tr.Version = common.VersionV1Alpha2\n\t\tr.ExternalName = config.NameAsIdentifier\n\t})\n}", "func (mg *Service) ResolveReferences(ctx context.Context, c client.Reader) error {\n\tr := reference.NewAPIResolver(c, mg)\n\n\tvar rsp reference.ResolutionResponse\n\tvar mrsp reference.MultiResolutionResponse\n\tvar err error\n\n\trsp, err = r.Resolve(ctx, reference.ResolutionRequest{\n\t\tCurrentValue: reference.FromPtrValue(mg.Spec.ForProvider.Cluster),\n\t\tExtract: common.ARNExtractor(),\n\t\tReference: mg.Spec.ForProvider.ClusterRef,\n\t\tSelector: mg.Spec.ForProvider.ClusterSelector,\n\t\tTo: reference.To{\n\t\t\tList: &ClusterList{},\n\t\t\tManaged: &Cluster{},\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"mg.Spec.ForProvider.Cluster\")\n\t}\n\tmg.Spec.ForProvider.Cluster = reference.ToPtrValue(rsp.ResolvedValue)\n\tmg.Spec.ForProvider.ClusterRef = rsp.ResolvedReference\n\n\trsp, err = r.Resolve(ctx, reference.ResolutionRequest{\n\t\tCurrentValue: reference.FromPtrValue(mg.Spec.ForProvider.IAMRole),\n\t\tExtract: common.ARNExtractor(),\n\t\tReference: mg.Spec.ForProvider.IAMRoleRef,\n\t\tSelector: mg.Spec.ForProvider.IAMRoleSelector,\n\t\tTo: reference.To{\n\t\t\tList: &v1alpha21.RoleList{},\n\t\t\tManaged: &v1alpha21.Role{},\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"mg.Spec.ForProvider.IAMRole\")\n\t}\n\tmg.Spec.ForProvider.IAMRole = reference.ToPtrValue(rsp.ResolvedValue)\n\tmg.Spec.ForProvider.IAMRoleRef = rsp.ResolvedReference\n\n\tfor i3 := 0; i3 < len(mg.Spec.ForProvider.NetworkConfiguration); i3++ {\n\t\tmrsp, err = r.ResolveMultiple(ctx, reference.MultiResolutionRequest{\n\t\t\tCurrentValues: reference.FromPtrValues(mg.Spec.ForProvider.NetworkConfiguration[i3].SecurityGroups),\n\t\t\tExtract: reference.ExternalName(),\n\t\t\tReferences: mg.Spec.ForProvider.NetworkConfiguration[i3].SecurityGroupRefs,\n\t\t\tSelector: mg.Spec.ForProvider.NetworkConfiguration[i3].SecurityGroupSelector,\n\t\t\tTo: reference.To{\n\t\t\t\tList: &v1alpha22.SecurityGroupList{},\n\t\t\t\tManaged: &v1alpha22.SecurityGroup{},\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"mg.Spec.ForProvider.NetworkConfiguration[i3].SecurityGroups\")\n\t\t}\n\t\tmg.Spec.ForProvider.NetworkConfiguration[i3].SecurityGroups = reference.ToPtrValues(mrsp.ResolvedValues)\n\t\tmg.Spec.ForProvider.NetworkConfiguration[i3].SecurityGroupRefs = mrsp.ResolvedReferences\n\n\t}\n\tfor i3 := 0; i3 < len(mg.Spec.ForProvider.NetworkConfiguration); i3++ {\n\t\tmrsp, err = r.ResolveMultiple(ctx, reference.MultiResolutionRequest{\n\t\t\tCurrentValues: reference.FromPtrValues(mg.Spec.ForProvider.NetworkConfiguration[i3].Subnets),\n\t\t\tExtract: reference.ExternalName(),\n\t\t\tReferences: mg.Spec.ForProvider.NetworkConfiguration[i3].SubnetRefs,\n\t\t\tSelector: mg.Spec.ForProvider.NetworkConfiguration[i3].SubnetSelector,\n\t\t\tTo: reference.To{\n\t\t\t\tList: &v1alpha22.SubnetList{},\n\t\t\t\tManaged: &v1alpha22.Subnet{},\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"mg.Spec.ForProvider.NetworkConfiguration[i3].Subnets\")\n\t\t}\n\t\tmg.Spec.ForProvider.NetworkConfiguration[i3].Subnets = reference.ToPtrValues(mrsp.ResolvedValues)\n\t\tmg.Spec.ForProvider.NetworkConfiguration[i3].SubnetRefs = mrsp.ResolvedReferences\n\n\t}\n\n\treturn nil\n}", "func (c *Command) Aliases() map[string]struct{} {\n\treturn map[string]struct{}{\n\t\t\"burgundy\": struct{}{},\n\t}\n}", "func init() {\n\tcfg, err := config.LoadDefaultConfig(context.TODO(), config.WithSharedConfigProfile(\"tavern-automation\"))\n\tif err != nil {\n\t\tlog.Fatal(\"ERROR: Unable to resolve credentials for tavern-automation: \", err)\n\t}\n\n\tstsc = sts.NewFromConfig(cfg)\n\torgc = organizations.NewFromConfig(cfg)\n\tec2c = ec2.NewFromConfig(cfg)\n\n\t// NOTE: By default, only describes regions that are enabled in the root org account, not all Regions\n\tresp, err := ec2c.DescribeRegions(context.TODO(), &ec2.DescribeRegionsInput{})\n\tif err != nil {\n\t\tlog.Fatal(\"ERROR: Unable to describe regions\", err)\n\t}\n\n\tfor _, region := range resp.Regions {\n\t\tregions = append(regions, *region.RegionName)\n\t}\n\tfmt.Println(\"INFO: Listing all enabled regions:\")\n\tfmt.Println(regions)\n}", "func main() {\n\n\tc := new(bluemix.Config)\n\n\tvar imageTag string\n\t// should same form of registry.ng.bluemix.net/<namespace>/<imagename>\n\tflag.StringVar(&imageTag, \"t\", \"registry.ng.bluemix.net/ibmcloud-go/build\", \"tag\")\n\n\tvar dockerFile string\n\tflag.StringVar(&dockerFile, \"f\", \"Dockerfile\", \"Dockerfile\")\n\n\tvar region string\n\tflag.StringVar(&region, \"region\", \"us-south\", \"region\")\n\n\tflag.Parse()\n\n\tc.Region = region\n\tdirectory := flag.Args()\n\n\tfmt.Println(directory)\n\ttrace.Logger = trace.NewLogger(\"true\")\n\tif len(directory) < 1 || directory[0] == \"\" {\n\n\t\tflag.Usage()\n\t\tfmt.Println(\"Example: ./build -f Dockerfile -t registry.ng.bluemix.net/ibmcloud-go/imagtest .\")\n\t\tos.Exit(1)\n\t}\n\n\tsession, _ := session.New(c)\n\n\tiamAPI, err := iamv1.New(session)\n\tidentityAPI := iamAPI.Identity()\n\tuserInfo, err := identityAPI.UserInfo()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tregistryClient, err := registryv1.New(session)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tnamespaceHeaderStruct := registryv1.NamespaceTargetHeader{\n\t\tAccountID: userInfo.Account.Bss,\n\t}\n\n\tnamespace := strings.Split(imageTag, \"/\")\n\tif len(namespace) != 3 {\n\t\tlog.Fatal(\"Image Tag not correct format\")\n\t}\n\n\tnamespaces, err := registryClient.Namespaces().GetNamespaces(namespaceHeaderStruct)\n\tfound := false\n\tfor _, a := range namespaces {\n\t\tif a == namespace[1] {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\t_, err := registryClient.Namespaces().AddNamespace(namespace[1], namespaceHeaderStruct)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t}\n\n\theaderStruct := registryv1.BuildTargetHeader{\n\t\tAccountID: userInfo.Account.Bss,\n\t}\n\n\trequestStruct := registryv1.DefaultImageBuildRequest()\n\trequestStruct.T = imageTag\n\trequestStruct.Dockerfile = dockerFile\n\n\ttarName, err := tarGzContext(directory[0])\n\tif err != nil {\n\n\t}\n\ttarFile, err := os.Open(tarName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttarReader := bufio.NewReader(tarFile)\n\t//Too much binary output\n\ttrace.Logger = trace.NewLogger(\"false\")\n\n\tfmt.Println(\"Building...\")\n\terr = registryClient.Builds().ImageBuild(*requestStruct, tarReader, headerStruct, os.Stdout)\n\n\timageHeaderStruct := registryv1.ImageTargetHeader{\n\t\tAccountID: userInfo.Account.Bss,\n\t}\n\n\tfmt.Println(\"\\nInspecting Built Image...\")\n\timage, err := registryClient.Images().InspectImage(imageTag, imageHeaderStruct)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tjsonBytes, err := json.MarshalIndent(image, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(string(jsonBytes))\n\n\tfmt.Println(\"\\nScanning Built Image...\")\n\timageVulnerabiliyRequst := registryv1.DefaultImageVulnerabilitiesRequest()\n\timageReport, err := registryClient.Images().ImageVulnerabilities(imageTag, *imageVulnerabiliyRequst, imageHeaderStruct)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tjsonBytes, err = json.MarshalIndent(imageReport, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(string(jsonBytes))\n}", "func WithNamespaceLister(namespaceLister coreListersV1.NamespaceLister) Option {\n\treturn func(b *registry) {\n\t\tfor _, item := range b.registry {\n\t\t\tif iface, ok := item.(BackendSetNamespaceLister); ok {\n\t\t\t\tiface.SetNamespaceLister(namespaceLister)\n\t\t\t}\n\t\t}\n\t}\n}", "func (i *Image) Animals(width, height int) string {\n\treturn i.Image().ImageURL(width, height, \"animals\")\n}", "func (e *Server) Association() []interface{} {\n\tret := []interface{}{}\n\tfor _, x := range e.Processors {\n\t\tret = append(ret, &x)\n\t}\n\tfor _, x := range e.Memory {\n\t\tret = append(ret, &x)\n\t}\n\tfor _, x := range e.EthernetInterfaces {\n\t\tfor _, y := range x.IPv4Addresses {\n\t\t\tret = append(ret, &y)\n\t\t}\n\t\tfor _, y := range x.IPv6Addresses {\n\t\t\tret = append(ret, &y)\n\t\t}\n\t\tfor _, y := range x.VLANs {\n\t\t\tret = append(ret, &y)\n\t\t}\n\t\tret = append(ret, &x)\n\t}\n\tfor _, x := range e.NetworkInterfaces {\n\t\tret = append(ret, &x)\n\t}\n\tfor _, x := range e.Storages {\n\t\tfor _, y := range x.StorageControllers {\n\t\t\tret = append(ret, &y)\n\t\t}\n\t\tret = append(ret, &x)\n\t}\n\tfor _, x := range e.Power.PowerControl {\n\t\tret = append(ret, &x)\n\t}\n\tfor _, x := range e.Power.PowerSupplies {\n\t\tret = append(ret, &x)\n\t}\n\tfor _, x := range e.Power.Redundancy {\n\t\tret = append(ret, &x)\n\t}\n\tret = append(ret, &e.Power)\n\tfor _, x := range e.Thermal.Fans {\n\t\tret = append(ret, &x)\n\t}\n\tret = append(ret, &e.Thermal)\n\tfor _, x := range e.Boards {\n\t\tret = append(ret, &x)\n\t}\n\tfor _, x := range e.NetworkAdapters {\n\t\tfor _, y := range x.Controllers {\n\t\t\tfor _, z := range y.NetworkPorts {\n\t\t\t\tret = append(ret, &z)\n\t\t\t}\n\t\t\tret = append(ret, &y)\n\t\t}\n\t\tret = append(ret, &x)\n\t}\n\tfor _, x := range e.Drives {\n\t\tfor _, y := range x.Location {\n\t\t\tret = append(ret, y.PostalAddress)\n\t\t\tret = append(ret, y.Placement)\n\t\t\tret = append(ret, &y)\n\t\t}\n\t\tret = append(ret, &x)\n\t}\n\tfor _, x := range e.PCIeDevices {\n\t\tfor _, y := range x.PCIeFunctions {\n\t\t\tret = append(ret, &y)\n\t\t}\n\t\tret = append(ret, &x)\n\t}\n\treturn ret\n}", "func (es ExternalServices) URNs() []string {\n\turns := make([]string, len(es))\n\tfor i := range es {\n\t\turns[i] = es[i].URN()\n\t}\n\treturn urns\n}", "func ArbitrateConfigs(c *Configure) {\n\t//check the ClusterName, ClusterName is used to Identify the clusters in the Local NetWork\n\tif c.HttpPort == c.MsgPort {\n\t\tpanic(\"port conflict\")\n\t}\n\tif c.HttpPort > math.MaxInt16 || c.HttpPort < 1024 {\n\t\tpanic(fmt.Errorf(\"illegal http port %d\", c.HttpPort))\n\t}\n\n\tif c.MsgPort > math.MaxInt16 || c.MsgPort < 1024 {\n\t\tpanic(fmt.Errorf(\"illegal msg port %d\", c.MsgPort))\n\t}\n\n\tif c.Retry > 10 {\n\t\tc.Retry = 10\n\t}\n\tif c.Retry < 1 {\n\t\tc.Retry = 1\n\t}\n\tif c.SyncType < 0 || c.SyncType > 2 {\n\t\tc.SyncType = 0\n\t}\n\tif c.Threshold < 1000 {\n\t\tc.Threshold = 1000\n\t}\n\tif c.Threshold > 1000000 {\n\t\tc.Threshold = 1000000\n\t}\n}", "func (o ApplicationStatusOperationStateSyncResultSourceKustomizeOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateSyncResultSourceKustomize) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func (o GetAuthorizersResultOutput) Ids() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetAuthorizersResult) []string { return v.Ids }).(pulumi.StringArrayOutput)\n}", "func ReplicaSetImages(rs appsv1.ReplicaSet) []string {\n\timages := []string{}\n\tfor _, ic := range rs.Spec.Template.Spec.InitContainers {\n\t\timages = append(images, ic.Image)\n\t}\n\tfor _, c := range rs.Spec.Template.Spec.Containers {\n\t\timages = append(images, c.Image)\n\t}\n\treturn images\n}", "func Init(instance *iter8v1alpha2.Experiment, client client.Client) *Targets {\n\tout := &Targets{\n\t\tService: &corev1.Service{},\n\t\tBaseline: &appsv1.Deployment{},\n\t\tCandidates: make([]*appsv1.Deployment, len(instance.Spec.Candidates)),\n\t\tnamespace: instance.ServiceNamespace(),\n\t\tclient: client,\n\t}\n\n\tmHosts, mGateways := make(map[string]bool), make(map[string]bool)\n\tservice := instance.Spec.Service\n\tfor _, host := range service.Hosts {\n\t\tif _, ok := mHosts[host.Name]; !ok {\n\t\t\tout.Hosts = append(out.Hosts, host.Name)\n\t\t\tmHosts[host.Name] = true\n\t\t}\n\n\t\tif _, ok := mHosts[host.Gateway]; !ok {\n\t\t\tout.Gateways = append(out.Gateways, host.Gateway)\n\t\t\tmGateways[host.Gateway] = true\n\t\t}\n\t}\n\n\tout.Port = instance.Spec.Service.Port\n\treturn out\n}", "func setRepositories() []repositories {\n\trepos := []repositories{\n\t\t{\n\t\t\tname: \"terraform\",\n\t\t\trepo: \"hashicorp/terraform\",\n\t\t},\n\t\t{\n\t\t\tname: \"ansible\",\n\t\t\trepo: \"ansible/ansible\",\n\t\t},\n\t}\n\treturn repos\n}", "func (o ApplicationStatusSyncComparedToSourceKustomizePtrOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusSyncComparedToSourceKustomize) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Images\n\t}).(pulumi.StringArrayOutput)\n}", "func (r *ReplicaSet) Images() map[string]string {\n\timages := map[string]string{}\n\n\tfor _, c := range r.raw.Spec.Template.Spec.Containers {\n\t\timages[c.Name] = c.Image\n\t}\n\n\treturn images\n}", "func allLibraries(a app.App) (app.LibraryConfigs, error) {\n\tif a == nil {\n\t\treturn nil, errors.Errorf(\"nil receiver\")\n\t}\n\n\tcombined := app.LibraryConfigs{}\n\n\tlibs, err := a.Libraries()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"checking libraries\")\n\t}\n\tfor _, lib := range libs {\n\t\tcombined[lib.Name] = lib\n\t}\n\n\tenvs, err := a.Environments()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"checking environments\")\n\t}\n\tfor _, env := range envs {\n\t\tfor _, lib := range env.Libraries {\n\t\t\t// NOTE We do not check for collisions at this time\n\t\t\tcombined[lib.Name] = lib\n\t\t}\n\t}\n\n\treturn combined, nil\n}", "func (o SecretBackendRoleOutput) RoleArns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *SecretBackendRole) pulumi.StringArrayOutput { return v.RoleArns }).(pulumi.StringArrayOutput)\n}", "func main() {\n c, err := identity.NewIdentityClientWithConfigurationProvider(common.DefaultConfigProvider())\n if err != nil {\n fmt.Println(\"Error:\", err)\n return\n }\n\n // The OCID of the tenancy containing the compartment.\n tenancyID, err := common.DefaultConfigProvider().TenancyOCID()\n if err != nil {\n fmt.Println(\"Error:\", err)\n return\n }\n\n request := identity.ListAvailabilityDomainsRequest{\n CompartmentId: &tenancyID,\n }\n\n r, err := c.ListAvailabilityDomains(context.Background(), request)\n if err != nil {\n fmt.Println(\"Error:\", err)\n return\n }\n\n fmt.Printf(\"List of available domains: %v\\n\", r.Items)\n\n return\n}", "func SetupImages(i Images) {\n\timages = i\n}", "func List(ctx context.Context, svc iaas.Service, networkID string, all bool, terraform bool) ([]*abstract.Subnet, fail.Error) {\n\tif !terraform {\n\t\treturn operations.ListSubnets(ctx, svc, networkID, all)\n\t}\n\n\tvar neptune []*abstract.Subnet\n\traw, err := operations.ListTerraformSubnets(ctx, svc, networkID, \"\", terraform)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, val := range raw { // FIXME: Another mapping problem\n\t\tns := abstract.NewSubnet()\n\t\tns.ID = val.Identity\n\t\tns.Name = val.Name\n\t\tneptune = append(neptune, ns)\n\t}\n\n\treturn neptune, nil\n}", "func (a *albClient) Lbs() []string {\n\treturn a.targetGroupArns\n}", "func (addon Addon) Images(clusterVersion *version.Version, imageTag string) []string {\n\timages := []string{}\n\tfor _, cb := range addon.getImageCallbacks {\n\t\timage := cb(clusterVersion, imageTag)\n\t\tif image != \"\" {\n\t\t\timages = append(images, image)\n\t\t}\n\t}\n\treturn images\n}", "func (h *Host) Aliases() []string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\ts := make([]string, len(h.aliases))\n\tcopy(s, h.aliases)\n\treturn s\n}", "func initImageNames() map[int]string {\n\tswitch getTestArch() {\n\tcase \"s390x\":\n\t\treturn map[int]string{\n\t\t\tbusyboxImage: \"busybox@sha256:4f47c01fa91355af2865ac10fef5bf6ec9c7f42ad2321377c21e844427972977\",\n\t\t\tregistryImage: \"ibmcom/registry:2.6.2.5\",\n\t\t\tkanikoImage: \"gcr.io/kaniko-project/executor:s390x-9ed158c1f63a059cde4fd5f8b95af51d452d9aa7\",\n\t\t\tdockerizeImage: \"ibmcom/dockerize-s390x\",\n\t\t}\n\tcase \"ppc64le\":\n\t\treturn map[int]string{\n\t\t\tbusyboxImage: \"busybox@sha256:4f47c01fa91355af2865ac10fef5bf6ec9c7f42ad2321377c21e844427972977\",\n\t\t\tregistryImage: \"ppc64le/registry:2\",\n\t\t\tkanikoImage: \"ibmcom/kaniko-project-executor-ppc64le:v0.17.1\",\n\t\t\tdockerizeImage: \"ibmcom/dockerize-ppc64le\",\n\t\t}\n\tdefault:\n\t\treturn map[int]string{\n\t\t\tbusyboxImage: \"busybox@sha256:895ab622e92e18d6b461d671081757af7dbaa3b00e3e28e12505af7817f73649\",\n\t\t\tregistryImage: \"registry\",\n\t\t\tkanikoImage: \"gcr.io/kaniko-project/executor:v1.3.0\",\n\t\t\tdockerizeImage: \"jwilder/dockerize\",\n\t\t}\n\t}\n}", "func (e *Enum) Aliases() []string {\n\treturn e.aliases\n}", "func GetAllImages(cfg *v1.ClusterConfiguration, kubeadmCfg *kubeadmapi.ClusterConfiguration, operatorVersion string) []string {\n\timgs := images.GetControlPlaneImages(kubeadmCfg)\n\t//for _, component := range []string{\n\t//constants.OnecloudOperator,\n\t//} {\n\t//imgs = append(imgs, GetOnecloudImage(component, cfg, kubeadmCfg))\n\t//}\n\trepoPrefix := kubeadmCfg.ImageRepository\n\tfor img, version := range map[string]string{\n\t\tconstants.CalicoKubeControllers: constants.DefaultCalicoVersion,\n\t\tconstants.CalicoNode: constants.DefaultCalicoVersion,\n\t\tconstants.CalicoCNI: constants.DefaultCalicoVersion,\n\t\tconstants.RancherLocalPathProvisioner: constants.DefaultLocalProvisionerVersion,\n\t\tconstants.IngressControllerTraefik: constants.DefaultTraefikVersion,\n\t\tconstants.OnecloudOperator: operatorVersion,\n\t} {\n\t\timgs = append(imgs, GetGenericImage(repoPrefix, img, version))\n\t}\n\treturn imgs\n}", "func (o ImagePipelineOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ImagePipeline) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}", "func (c *CurrentTrackCommand) Aliases() []string {\n\treturn viper.GetStringSlice(\"commands.currenttrack.aliases\")\n}", "func AddIndependentPropertyGeneratorsForNetworkInterfaceDnsSettings_ARM(gens map[string]gopter.Gen) {\n\tgens[\"DnsServers\"] = gen.SliceOf(gen.AlphaString())\n\tgens[\"InternalDnsNameLabel\"] = gen.PtrOf(gen.AlphaString())\n}", "func GetAllResources(targetRegions []string, excludeAfter time.Time, resourceTypes []string, configObj config.Config) (*AwsAccountResources, error) {\n\taccount := AwsAccountResources{\n\t\tResources: make(map[string]AwsRegionResource),\n\t}\n\n\tcount := 1\n\ttotalRegions := len(targetRegions)\n\tvar resourcesCache = map[string]map[string][]*string{}\n\n\tfor _, region := range targetRegions {\n\t\tlogging.Logger.Infof(\"Checking region [%d/%d]: %s\", count, totalRegions, region)\n\n\t\tsession, err := session.NewSession(&awsgo.Config{\n\t\t\tRegion: awsgo.String(region)},\n\t\t)\n\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t}\n\n\t\tresourcesInRegion := AwsRegionResource{}\n\n\t\t// The order in which resources are nuked is important\n\t\t// because of dependencies between resources\n\n\t\t// ASG Names\n\t\tasGroups := ASGroups{}\n\t\tif IsNukeable(asGroups.ResourceName(), resourceTypes) {\n\t\t\tgroupNames, err := getAllAutoScalingGroups(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(groupNames) > 0 {\n\t\t\t\tasGroups.GroupNames = awsgo.StringValueSlice(groupNames)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, asGroups)\n\t\t\t}\n\t\t}\n\t\t// End ASG Names\n\n\t\t// Launch Configuration Names\n\t\tconfigs := LaunchConfigs{}\n\t\tif IsNukeable(configs.ResourceName(), resourceTypes) {\n\t\t\tconfigNames, err := getAllLaunchConfigurations(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(configNames) > 0 {\n\t\t\t\tconfigs.LaunchConfigurationNames = awsgo.StringValueSlice(configNames)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, configs)\n\t\t\t}\n\t\t}\n\t\t// End Launch Configuration Names\n\n\t\t// LoadBalancer Names\n\t\tloadBalancers := LoadBalancers{}\n\t\tif IsNukeable(loadBalancers.ResourceName(), resourceTypes) {\n\t\t\telbNames, err := getAllElbInstances(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(elbNames) > 0 {\n\t\t\t\tloadBalancers.Names = awsgo.StringValueSlice(elbNames)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, loadBalancers)\n\t\t\t}\n\t\t}\n\t\t// End LoadBalancer Names\n\n\t\t// LoadBalancerV2 Arns\n\t\tloadBalancersV2 := LoadBalancersV2{}\n\t\tif IsNukeable(loadBalancersV2.ResourceName(), resourceTypes) {\n\t\t\telbv2Arns, err := getAllElbv2Instances(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(elbv2Arns) > 0 {\n\t\t\t\tloadBalancersV2.Arns = awsgo.StringValueSlice(elbv2Arns)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, loadBalancersV2)\n\t\t\t}\n\t\t}\n\t\t// End LoadBalancerV2 Arns\n\n\t\t// EC2 Instances\n\t\tec2Instances := EC2Instances{}\n\t\tif IsNukeable(ec2Instances.ResourceName(), resourceTypes) {\n\t\t\tinstanceIds, err := getAllEc2Instances(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(instanceIds) > 0 {\n\t\t\t\tec2Instances.InstanceIds = awsgo.StringValueSlice(instanceIds)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, ec2Instances)\n\t\t\t}\n\t\t}\n\t\t// End EC2 Instances\n\n\t\t// EBS Volumes\n\t\tebsVolumes := EBSVolumes{}\n\t\tif IsNukeable(ebsVolumes.ResourceName(), resourceTypes) {\n\t\t\tvolumeIds, err := getAllEbsVolumes(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(volumeIds) > 0 {\n\t\t\t\tebsVolumes.VolumeIds = awsgo.StringValueSlice(volumeIds)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, ebsVolumes)\n\t\t\t}\n\t\t}\n\t\t// End EBS Volumes\n\n\t\t// EIP Addresses\n\t\teipAddresses := EIPAddresses{}\n\t\tif IsNukeable(eipAddresses.ResourceName(), resourceTypes) {\n\t\t\tallocationIds, err := getAllEIPAddresses(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(allocationIds) > 0 {\n\t\t\t\teipAddresses.AllocationIds = awsgo.StringValueSlice(allocationIds)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, eipAddresses)\n\t\t\t}\n\t\t}\n\t\t// End EIP Addresses\n\n\t\t// AMIs\n\t\tamis := AMIs{}\n\t\tif IsNukeable(amis.ResourceName(), resourceTypes) {\n\t\t\timageIds, err := getAllAMIs(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(imageIds) > 0 {\n\t\t\t\tamis.ImageIds = awsgo.StringValueSlice(imageIds)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, amis)\n\t\t\t}\n\t\t}\n\t\t// End AMIs\n\n\t\t// Snapshots\n\t\tsnapshots := Snapshots{}\n\t\tif IsNukeable(snapshots.ResourceName(), resourceTypes) {\n\t\t\tsnapshotIds, err := getAllSnapshots(session, region, excludeAfter)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(snapshotIds) > 0 {\n\t\t\t\tsnapshots.SnapshotIds = awsgo.StringValueSlice(snapshotIds)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, snapshots)\n\t\t\t}\n\t\t}\n\t\t// End Snapshots\n\n\t\t// ECS resources\n\t\tecsServices := ECSServices{}\n\t\tif IsNukeable(ecsServices.ResourceName(), resourceTypes) {\n\t\t\tclusterArns, err := getAllEcsClusters(session)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\t\t\tif len(clusterArns) > 0 {\n\t\t\t\tserviceArns, serviceClusterMap, err := getAllEcsServices(session, clusterArns, excludeAfter)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t\t}\n\t\t\t\tecsServices.Services = awsgo.StringValueSlice(serviceArns)\n\t\t\t\tecsServices.ServiceClusterMap = serviceClusterMap\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, ecsServices)\n\t\t\t}\n\t\t}\n\t\t// End ECS resources\n\n\t\t// EKS resources\n\t\teksClusters := EKSClusters{}\n\t\tif IsNukeable(eksClusters.ResourceName(), resourceTypes) {\n\t\t\tif eksSupportedRegion(region) {\n\t\t\t\teksClusterNames, err := getAllEksClusters(session, excludeAfter)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t\t}\n\t\t\t\tif len(eksClusterNames) > 0 {\n\t\t\t\t\teksClusters.Clusters = awsgo.StringValueSlice(eksClusterNames)\n\t\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, eksClusters)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// End EKS resources\n\n\t\t// RDS DB Instances\n\t\tdbInstances := DBInstances{}\n\t\tif IsNukeable(dbInstances.ResourceName(), resourceTypes) {\n\t\t\tinstanceNames, err := getAllRdsInstances(session, excludeAfter)\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\n\t\t\tif len(instanceNames) > 0 {\n\t\t\t\tdbInstances.InstanceNames = awsgo.StringValueSlice(instanceNames)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, dbInstances)\n\t\t\t}\n\t\t}\n\t\t// End RDS DB Instances\n\n\t\t// RDS DB Clusters\n\t\t// These reference the Aurora Clusters, for the use it's the same resource (rds), but AWS\n\t\t// has different abstractions for each.\n\t\tdbClusters := DBClusters{}\n\t\tif IsNukeable(dbClusters.ResourceName(), resourceTypes) {\n\t\t\tclustersNames, err := getAllRdsClusters(session, excludeAfter)\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t}\n\n\t\t\tif len(clustersNames) > 0 {\n\t\t\t\tdbClusters.InstanceNames = awsgo.StringValueSlice(clustersNames)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, dbClusters)\n\t\t\t}\n\t\t}\n\t\t// End RDS DB Clusters\n\n\t\t// S3 Buckets\n\t\ts3Buckets := S3Buckets{}\n\t\tif IsNukeable(s3Buckets.ResourceName(), resourceTypes) {\n\t\t\tvar bucketNamesPerRegion map[string][]*string\n\n\t\t\t// AWS S3 buckets list operation lists all buckets irrespective of regions.\n\t\t\t// For each bucket we have to make a separate call to find the bucket region.\n\t\t\t// Hence for x buckets and a total of y target regions - we need to make:\n\t\t\t// (x + 1) * y calls i.e. 1 call to list all x buckets, x calls to find out\n\t\t\t// each bucket's region and repeat the process for each of the y regions.\n\n\t\t\t// getAllS3Buckets returns a map of regions to buckets and we call it only once -\n\t\t\t// thereby reducing total calls from (x + 1) * y to only (x + 1) for the first region -\n\t\t\t// followed by a cache lookup for rest of the regions.\n\n\t\t\t// Cache lookup to check if we already obtained bucket names per region\n\t\t\tbucketNamesPerRegion, ok := resourcesCache[\"S3\"]\n\n\t\t\tif !ok {\n\t\t\t\tbucketNamesPerRegion, err = getAllS3Buckets(session, excludeAfter, targetRegions, \"\", s3Buckets.MaxConcurrentGetSize(), configObj)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.WithStackTrace(err)\n\t\t\t\t}\n\n\t\t\t\tresourcesCache[\"S3\"] = make(map[string][]*string)\n\n\t\t\t\tfor bucketRegion, _ := range bucketNamesPerRegion {\n\t\t\t\t\tresourcesCache[\"S3\"][bucketRegion] = bucketNamesPerRegion[bucketRegion]\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbucketNames, ok := resourcesCache[\"S3\"][region]\n\n\t\t\tif ok && len(bucketNames) > 0 {\n\t\t\t\ts3Buckets.Names = aws.StringValueSlice(bucketNames)\n\t\t\t\tresourcesInRegion.Resources = append(resourcesInRegion.Resources, s3Buckets)\n\t\t\t}\n\t\t}\n\t\t// End S3 Buckets\n\n\t\tif len(resourcesInRegion.Resources) > 0 {\n\t\t\taccount.Resources[region] = resourcesInRegion\n\t\t}\n\t\tcount++\n\t}\n\n\treturn &account, nil\n}", "func (r *Distribution) Aliases() pulumi.ArrayOutput {\n\treturn (pulumi.ArrayOutput)(r.s.State[\"aliases\"])\n}", "func AppendAllRIRSubnets(mmdb *maxminddb.Reader, entries map[string]string, rirFiles []string, isIPv4Only, lowercase bool, includeCountries, excludeCountries map[string]struct{}) error {\n\tfor _, rirFile := range rirFiles {\n\t\tcsvFile, e := os.Open(rirFile)\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t\tdefer csvFile.Close()\n\t\treader := csv.NewReader(bufio.NewReader(csvFile))\n\t\treader.Comma = '|'\n\t\treader.Comment = '#'\n\t\t// some delegated dbs are not uniform\n\t\treader.FieldsPerRecord = -1\n\t\tif e := appendRIRSubnets(mmdb, reader, entries, isIPv4Only, lowercase, includeCountries, excludeCountries); e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}", "func (npMgr *NetworkPolicyManager) InitAllNsList() error {\n\tallNs := npMgr.nsMap[util.KubeAllNamespacesFlag]\n\tfor nsName := range npMgr.nsMap {\n\t\tif nsName == util.KubeAllNamespacesFlag {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := allNs.ipsMgr.AddToList(util.KubeAllNamespacesFlag, nsName); err != nil {\n\t\t\tlog.Errorf(\"Error: failed to add namespace set %s to list %s\", nsName, util.KubeAllNamespacesFlag)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o RegexPatternSetOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RegexPatternSet) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}", "func (o RegexPatternSetOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RegexPatternSet) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}", "func (o ImagePipelineOutput) InfrastructureConfigurationArn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ImagePipeline) pulumi.StringPtrOutput { return v.InfrastructureConfigurationArn }).(pulumi.StringPtrOutput)\n}", "func imageNamesMapping() map[string]string {\n\n\tswitch getTestArch() {\n\tcase \"s390x\":\n\t\treturn map[string]string{\n\t\t\t\"registry\": getTestImage(registryImage),\n\t\t\t\"node\": \"node:alpine3.11\",\n\t\t\t\"gcr.io/cloud-builders/git\": \"alpine/git:latest\",\n\t\t\t\"docker:dind\": \"ibmcom/docker-s390x:dind\",\n\t\t\t\"docker\": \"docker:18.06.3\",\n\t\t\t\"mikefarah/yq:3\": \"danielxlee/yq:2.4.0\",\n\t\t\t\"stedolan/jq\": \"ibmcom/jq-s390x:latest\",\n\t\t\t\"gcr.io/kaniko-project/executor:v1.3.0\": getTestImage(kanikoImage),\n\t\t}\n\tcase \"ppc64le\":\n\t\treturn map[string]string{\n\t\t\t\"registry\": getTestImage(registryImage),\n\t\t\t\"node\": \"node:alpine3.11\",\n\t\t\t\"gcr.io/cloud-builders/git\": \"alpine/git:latest\",\n\t\t\t\"docker:dind\": \"ibmcom/docker-ppc64le:19.03-dind\",\n\t\t\t\"docker\": \"docker:18.06.3\",\n\t\t\t\"mikefarah/yq:3\": \"danielxlee/yq:2.4.0\",\n\t\t\t\"stedolan/jq\": \"ibmcom/jq-ppc64le:latest\",\n\t\t\t\"gcr.io/kaniko-project/executor:v1.3.0\": getTestImage(kanikoImage),\n\t\t}\n\n\t}\n\n\treturn make(map[string]string)\n}", "func (o GetInfrastructureConfigurationsResultOutput) Names() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetInfrastructureConfigurationsResult) []string { return v.Names }).(pulumi.StringArrayOutput)\n}", "func (t *TMDB) NetworkAlternativeNames(id int64) (*CompanyAlternativeNames, error) {\n\tc := new(CompanyAlternativeNames)\n\tif err := t.get(c, fmt.Sprintf(\"/3/network/%d/alternative_names\", id), url.Values{}); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}", "func GetOriginalImageConfigs() map[ImageID]Config {\n\treturn originalImageConfigs\n}", "func (ncs NvmeControllers) Addresses() (*hardware.PCIAddressSet, error) {\n\tpas := hardware.MustNewPCIAddressSet()\n\tfor _, c := range ncs {\n\t\tif err := pas.AddStrings(c.PciAddr); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn pas, nil\n}", "func rbacConfig() *any.Any {\n\tconf := &filterNetworkRbac.RBAC{\n\t\tStatPrefix: \"ip_restrictions.\",\n\t\tRules: &rbac.RBAC{\n\t\t\tAction: rbac.RBAC_ALLOW,\n\t\t\tPolicies: map[string]*rbac.Policy{\n\t\t\t\t\"allow_host\": {\n\t\t\t\t\tPermissions: []*rbac.Permission{{\n\t\t\t\t\t\tRule: &rbac.Permission_Any{Any: true},\n\t\t\t\t\t}},\n\t\t\t\t\tPrincipals: []*rbac.Principal{{\n\t\t\t\t\t\tIdentifier: &rbac.Principal_SourceIp{SourceIp: &core.CidrRange{\n\t\t\t\t\t\t\tAddressPrefix: \"1.1.1.1\",\n\t\t\t\t\t\t\tPrefixLen: &wrappers.UInt32Value{Value: 16},\n\t\t\t\t\t\t}},\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\trbacConf, err := ptypes.MarshalAny(conf)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn rbacConf\n}", "func (o LookupDedicatedIpPoolResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupDedicatedIpPoolResult) string { return v.Arn }).(pulumi.StringOutput)\n}", "func (o ApplicationStatusSummaryPtrOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusSummary) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Images\n\t}).(pulumi.StringArrayOutput)\n}", "func RegisterAEIFlags(flagset *flag.FlagSet) *AEISettings {\n\ts := new(AEISettings)\n\tflagset.StringVar(&s.ProtoVersion, \"protocol_version\", \"1\", \"AEI protocol-version.\")\n\tflagset.StringVar(&s.BotName, \"bot_name\", \"bot_alpha_zoo\", \"Bot name reported by AEI `id`.\")\n\tflagset.StringVar(&s.BotVersion, \"bot_version\", \"0\", \"Bot verion reported by AEI `id`.\")\n\tflagset.StringVar(&s.BotAuthor, \"bot_author\", \"Alan Zaffetti\", \"Bot author reported by AEI `id`.\")\n\tflagset.BoolVar(&s.LogProtocolTraffic, \"log_protocol_traffic\", false, \"Log all AEI protocol messages sent and received to stderr.\")\n\treturn s\n}", "func ociSubnetsToAnnotationValue(subnets []string) []interface{} {\n\tifs := make([]interface{}, len(subnets))\n\tfor i, s := range subnets {\n\t\tifs[i] = s\n\t}\n\treturn ifs\n}", "func (o LookupReplicationSetResultOutput) Arn() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupReplicationSetResult) *string { return v.Arn }).(pulumi.StringPtrOutput)\n}", "func (client *BaseClient) URIList() []string {\n\treturn client.uriList\n}", "func ConstructRoleArns(groups []string) []string {\n\tvar roleGroups []string\n\tfor _, group := range groups {\n\t\ts := strings.Split(group, \"#\")\n\t\t_, roleName, accountNumber := s[0], s[1], s[2]\n\t\troleGroups = append(roleGroups, fmt.Sprintf(\"arn:aws:iam::%s:role/%s\", accountNumber, roleName))\n\t}\n\treturn roleGroups\n}", "func (c *Canary) AttachToOriginalTargetGroups(config schemas.Config) error {\n\t//Apply AutoScaling Policies\n\tfor _, region := range c.Stack.Regions {\n\t\t//If region id is passed from command line, then deployer will deploy in that region only.\n\t\tif config.Region != \"\" && config.Region != region.Region {\n\t\t\tc.Logger.Debug(\"This region is skipped by user : \" + region.Region)\n\t\t\tcontinue\n\t\t}\n\n\t\tclient, err := selectClientFromList(c.AWSClients, region.Region)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.Logger.Debugf(\"Get target group ARN of original target groups: %s\", c.PrevTargetGroups[region.Region])\n\t\ttargetGroupARNs, err := client.ELBV2Service.GetTargetGroupARNs(c.PrevTargetGroups[region.Region])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif targetGroupARNs == nil {\n\t\t\treturn fmt.Errorf(\"there is no target group specified\")\n\t\t}\n\n\t\tc.Logger.Debugf(\"Attach autoscaling group to original target groups: %s\", c.AsgNames[region.Region])\n\t\tif err := client.EC2Service.AttachAsgToTargetGroups(c.AsgNames[region.Region], targetGroupARNs); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tc.Logger.Debug(\"Finish attaching autoscaling group to original target groups\")\n\treturn nil\n}", "func (o JobExtractOutput) DestinationUris() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v JobExtract) []string { return v.DestinationUris }).(pulumi.StringArrayOutput)\n}", "func (o IopingSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermOutput) Namespaces() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v IopingSpecPodConfigPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTerm) []string {\n\t\treturn v.Namespaces\n\t}).(pulumi.StringArrayOutput)\n}", "func (o LookupConfigurationResultOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupConfigurationResult) string { return v.Arn }).(pulumi.StringOutput)\n}", "func (o *MirrorOptions) Full(ctx context.Context, cfg v1alpha1.ImageSetConfiguration) (image.AssociationSet, error) {\n\to.complete()\n\n\tcleanup, err := o.mktempDir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !o.SkipCleanup {\n\t\tdefer cleanup()\n\t}\n\n\treg, err := o.createRegistry()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating container registry: %v\", err)\n\t}\n\tdefer reg.Destroy()\n\n\tallAssocs := image.AssociationSet{}\n\tfor _, ctlg := range cfg.Mirror.Operators {\n\t\tctlgRef, err := imagesource.ParseReference(ctlg.Catalog)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing catalog: %v\", err)\n\t\t}\n\t\tctlgRef.Ref = ctlgRef.Ref.DockerClientDefaults()\n\n\t\tcatLogger := o.Logger.WithField(\"catalog\", ctlg.Catalog)\n\t\tvar dc *declcfg.DeclarativeConfig\n\t\tif ctlg.HeadsOnly {\n\t\t\t// Generate and mirror a heads-only diff using only the catalog as a new ref.\n\t\t\tdc, err = action.Diff{\n\t\t\t\tRegistry: reg,\n\t\t\t\tNewRefs: []string{ctlg.Catalog},\n\t\t\t\tLogger: catLogger,\n\t\t\t\tIncludeConfig: ctlg.DiffIncludeConfig,\n\t\t\t}.Run(ctx)\n\t\t} else {\n\t\t\t// Mirror the entire catalog.\n\t\t\tdc, err = action.Render{\n\t\t\t\tRegistry: reg,\n\t\t\t\tRefs: []string{ctlg.Catalog},\n\t\t\t}.Run(ctx)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tisBlocked := func(ref imgreference.DockerImageReference) bool {\n\t\t\treturn bundle.IsBlocked(cfg, ref)\n\t\t}\n\t\tmappings, err := o.mirror(ctx, dc, ctlgRef, ctlg, isBlocked)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tassocs, err := o.associateDeclarativeConfigImageLayers(ctlgRef, dc, mappings)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tallAssocs.Merge(assocs)\n\t}\n\n\treturn allAssocs, nil\n}", "func (o EntityRecognizerOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *EntityRecognizer) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}", "func initConfig() {\n\tcfgBldr := &config.ConfigurationBuilder{}\n\tSettings = &accountControllerConfiguration{}\n\tif err := cfgBldr.Unmarshal(Settings); err != nil {\n\t\tlog.Fatalf(\"Could not load configuration: %s\", err.Error())\n\t}\n\n\t// load up the values into the various settings...\n\terr := cfgBldr.WithEnv(\"AWS_CURRENT_REGION\", \"AWS_CURRENT_REGION\", \"us-east-1\").Build()\n\tif err != nil {\n\t\tlog.Printf(\"Error: %+v\", err)\n\t}\n\tsvcBldr := &config.ServiceBuilder{Config: cfgBldr}\n\n\t_, err = svcBldr.\n\t\t// AWS services...\n\t\tWithDynamoDB().\n\t\tWithSTS().\n\t\tWithS3().\n\t\tWithSNS().\n\t\tWithSQS().\n\t\t// DCE services...\n\t\tWithStorageService().\n\t\tWithDataService().\n\t\tBuild()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tServices = svcBldr\n\n\tpolicyName = Config.GetEnvVar(\"PRINCIPAL_POLICY_NAME\", \"DCEPrincipalDefaultPolicy\")\n\tartifactsBucket = Config.GetEnvVar(\"ARTIFACTS_BUCKET\", \"DefaultArtifactBucket\")\n\tprincipalPolicyS3Key = Config.GetEnvVar(\"PRINCIPAL_POLICY_S3_KEY\", \"DefaultPrincipalPolicyS3Key\")\n\tprincipalRoleName = Config.GetEnvVar(\"PRINCIPAL_ROLE_NAME\", \"DCEPrincipal\")\n\tprincipalIAMDenyTags = strings.Split(Config.GetEnvVar(\"PRINCIPAL_IAM_DENY_TAGS\", \"DefaultPrincipalIamDenyTags\"), \",\")\n\tprincipalMaxSessionDuration = int64(Config.GetEnvIntVar(\"PRINCIPAL_MAX_SESSION_DURATION\", 100))\n\ttags = []*iam.Tag{\n\t\t{Key: aws.String(\"Terraform\"), Value: aws.String(\"False\")},\n\t\t{Key: aws.String(\"Source\"), Value: aws.String(\"github.com/Optum/dce//cmd/lambda/accounts\")},\n\t\t{Key: aws.String(\"Environment\"), Value: aws.String(Config.GetEnvVar(\"TAG_ENVIRONMENT\", \"DefaultTagEnvironment\"))},\n\t\t{Key: aws.String(\"Contact\"), Value: aws.String(Config.GetEnvVar(\"TAG_CONTACT\", \"DefaultTagContact\"))},\n\t\t{Key: aws.String(\"AppName\"), Value: aws.String(Config.GetEnvVar(\"TAG_APP_NAME\", \"DefaultTagAppName\"))},\n\t}\n\taccountCreatedTopicArn = Config.GetEnvVar(\"ACCOUNT_CREATED_TOPIC_ARN\", \"DefaultAccountCreatedTopicArn\")\n\tresetQueueURL = Config.GetEnvVar(\"RESET_SQS_URL\", \"DefaultResetSQSUrl\")\n\tallowedRegions = strings.Split(Config.GetEnvVar(\"ALLOWED_REGIONS\", \"us-east-1\"), \",\")\n}", "func AddRelatedPropertyGeneratorsForNetworkRuleSet_ARM(gens map[string]gopter.Gen) {\n\tgens[\"IpRules\"] = gen.SliceOf(IpRule_ARMGenerator())\n}", "func (o ResolverFirewallDomainListOutput) Arn() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ResolverFirewallDomainList) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)\n}", "func (o SpokeLinkedInterconnectAttachmentsOutput) Uris() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v SpokeLinkedInterconnectAttachments) []string { return v.Uris }).(pulumi.StringArrayOutput)\n}", "func loadTargetApis() (Configs, error) {\n\tvar configs Configs\n\t//allApps := false\n\n\traw, err := ioutil.ReadFile(*configFile)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn configs, err\n\t}\n\n\tjson.Unmarshal(raw, &configs)\n\n\treturn configs, err\n}", "func (o EndpointOutput) Aliases() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v Endpoint) []string { return v.Aliases }).(pulumi.StringArrayOutput)\n}", "func (o QperfSpecClientConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermOutput) Namespaces() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v QperfSpecClientConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTerm) []string {\n\t\treturn v.Namespaces\n\t}).(pulumi.StringArrayOutput)\n}", "func Setup(conf config.Config) error {\n\tfor _, netIDStr := range conf.Filters.NetIDs {\n\t\tvar netID lorawan.NetID\n\t\tif err := netID.UnmarshalText([]byte(netIDStr)); err != nil {\n\t\t\treturn errors.Wrap(err, \"unmarshal NetID error\")\n\t\t}\n\n\t\tnetIDs = append(netIDs, netID)\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"net_id\": netID,\n\t\t}).Info(\"filters: NetID filter configured\")\n\t}\n\n\tfor _, set := range conf.Filters.JoinEUIs {\n\t\tvar joinEUISet [2]lorawan.EUI64\n\n\t\tfor i, s := range set {\n\t\t\tvar joinEUI lorawan.EUI64\n\t\t\tif err := joinEUI.UnmarshalText([]byte(s)); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"unmarshal JoinEUI error\")\n\t\t\t}\n\n\t\t\tjoinEUISet[i] = joinEUI\n\t\t}\n\n\t\tjoinEUIs = append(joinEUIs, joinEUISet)\n\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"join_eui_from\": joinEUISet[0],\n\t\t\t\"join_eui_to\": joinEUISet[1],\n\t\t}).Info(\"filters: JoinEUI range configured\")\n\t}\n\n\treturn nil\n}", "func (o LookupProvisioningConfigResultOutput) Networks() NetworkConfigResponseArrayOutput {\n\treturn o.ApplyT(func(v LookupProvisioningConfigResult) []NetworkConfigResponse { return v.Networks }).(NetworkConfigResponseArrayOutput)\n}", "func (o Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermOutput) Namespaces() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v Iperf3SpecClientConfigurationPodSchedulingAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTerm) []string {\n\t\treturn v.Namespaces\n\t}).(pulumi.StringArrayOutput)\n}", "func (o ApplicationStatusOperationStateOperationSyncSourceKustomizePtrOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusOperationStateOperationSyncSourceKustomize) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Images\n\t}).(pulumi.StringArrayOutput)\n}", "func (o ApplicationOperationSyncSourceKustomizePtrOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *ApplicationOperationSyncSourceKustomize) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Images\n\t}).(pulumi.StringArrayOutput)\n}" ]
[ "0.49807295", "0.49396202", "0.48274466", "0.46540582", "0.46500695", "0.4544582", "0.45358956", "0.45227125", "0.4485528", "0.44812265", "0.44389182", "0.44133228", "0.43842816", "0.4356478", "0.43466344", "0.4339544", "0.43235326", "0.4293703", "0.4269512", "0.42656103", "0.42616293", "0.42615363", "0.42302746", "0.42109266", "0.42072493", "0.41958198", "0.41943282", "0.4193731", "0.41922122", "0.41891545", "0.4185255", "0.41522643", "0.41511977", "0.41474947", "0.41440663", "0.41419676", "0.41350943", "0.41310278", "0.41194907", "0.4118156", "0.41113758", "0.41009614", "0.40906283", "0.40887272", "0.40618926", "0.405807", "0.40535054", "0.4052865", "0.40528497", "0.40506548", "0.40480426", "0.40463465", "0.40311515", "0.40311489", "0.40267685", "0.402525", "0.40190232", "0.40150538", "0.40097025", "0.4009681", "0.40094823", "0.400127", "0.39958635", "0.3995546", "0.39947066", "0.39929786", "0.39922145", "0.39922145", "0.39919934", "0.39889067", "0.39885804", "0.39636472", "0.39615932", "0.39597768", "0.39570224", "0.3955264", "0.3952262", "0.39462256", "0.3944837", "0.39393598", "0.39391333", "0.3936311", "0.39342314", "0.39338413", "0.3929984", "0.39265335", "0.39260736", "0.3920613", "0.39155325", "0.39101726", "0.39096826", "0.39094457", "0.38968128", "0.3896771", "0.3895021", "0.38939083", "0.3889855", "0.38857478", "0.38857087", "0.38855177" ]
0.5901255
0
The providerassigned unique ID for this managed resource.
func (o GetInfrastructureConfigurationsResultOutput) Id() pulumi.StringOutput { return o.ApplyT(func(v GetInfrastructureConfigurationsResult) string { return v.Id }).(pulumi.StringOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MachineScope) ProviderID() string {\n\treturn ptr.Deref(m.AzureMachine.Spec.ProviderID, \"\")\n}", "func (id ResourceGroupProviderId) ID() string {\n\tfmtString := \"/subscriptions/%s/resourceGroups/%s/providers/%s/%s/%s/%s/%s\"\n\treturn fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.ProviderName, id.ResourceParentType, id.ResourceParentName, id.ResourceType, id.ResourceName)\n}", "func (o AuthRequirementOutput) ProviderId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AuthRequirement) *string { return v.ProviderId }).(pulumi.StringPtrOutput)\n}", "func (o AuthProviderOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AuthProvider) *string { return v.Id }).(pulumi.StringPtrOutput)\n}", "func (p *PinpointSMS) ID() string {\n\treturn providerID\n}", "func (r Resource) ID() string {\n\treturn r.id\n}", "func (tr *CapacityProvider) GetID() string {\n\tif tr.Status.AtProvider.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *tr.Status.AtProvider.ID\n}", "func (s *scwServer) ProviderID() string {\n\treturn \"\"\n}", "func (c *Client) GetID() string {\n\treturn c.providerIdent\n}", "func (p *ResourcePool) ID() string {\n\treturn fmt.Sprintf(\"resourcepool(%s)\", p.manager.Name())\n}", "func (m *Machine) GenerateProviderID() (string, error) {\n\tif m.vmiInstance == nil {\n\t\treturn \"\", errors.New(\"Underlying Kubevirt VM is NOT running\")\n\t}\n\n\tproviderID := fmt.Sprintf(\"kubevirt://%s\", m.machineContext.KubevirtMachine.Name)\n\n\treturn providerID, nil\n}", "func (c *Client) ProviderID() gitprovider.ProviderID {\n\treturn ProviderID\n}", "func (o *LocalDatabaseProvider) GetId() string {\n\tif o == nil || o.Id == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Id\n}", "func providerConfigID(pc *schema.OpenIDConnectAuthProvider) string {\n\tif pc.ConfigID != \"\" {\n\t\treturn pc.ConfigID\n\t}\n\tdata, err := json.Marshal(pc)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tb := sha256.Sum256(data)\n\treturn base64.RawURLEncoding.EncodeToString(b[:16])\n}", "func (o AuthRequirementResponseOutput) ProviderId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AuthRequirementResponse) string { return v.ProviderId }).(pulumi.StringOutput)\n}", "func GetInstanceProviderID(ctx context.Context, cloud Interface, nodeName types.NodeName) (string, error) {\n\tinstances, ok := cloud.Instances()\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"failed to get instances from cloud provider\")\n\t}\n\tinstanceID, err := instances.InstanceID(ctx, nodeName)\n\tif err != nil {\n\t\tif err == NotImplemented {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\treturn \"\", fmt.Errorf(\"failed to get instance ID from cloud provider: %v\", err)\n\t}\n\treturn cloud.ProviderName() + \"://\" + instanceID, nil\n}", "func (c *CIDOffer) GetProviderID() *nodeid.NodeID {\n\treturn c.providerID\n}", "func (i *Resource) Id() string {\n\treturn i.data.Id\n}", "func (c *Consumer) ID() string { return c.id }", "func (d *IPFSStore) GenerateResourceId() (ResourceId, error) {\n objdata := make([]byte, 256)\n rand.Read(objdata)\n\n //FIXME: This could probably be done better somewhere else ...\n s, e := d.client.ObjectPutData(objdata)\n if e != nil { return ResourceId(\"\"), e }\n\n return ResourceId(d.TypeId() + \":\" + s.Hash), nil\n}", "func (o *IdentityCredentialIdentifierOidcProperties) GetProvider() string {\n\tif o == nil || o.Provider == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Provider\n}", "func (tr *Service) GetID() string {\n\tif tr.Status.AtProvider.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *tr.Status.AtProvider.ID\n}", "func (r *EBSVolumeResizer) GetProviderVolumeID(pv *v1.PersistentVolume) (string, error) {\n\tvolumeID := pv.Spec.AWSElasticBlockStore.VolumeID\n\tif volumeID == \"\" {\n\t\treturn \"\", fmt.Errorf(\"got empty volume id for volume %v\", pv)\n\t}\n\n\treturn r.ExtractVolumeID(volumeID)\n}", "func (o CassandraKeyspaceResourceOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CassandraKeyspaceResource) string { return v.Id }).(pulumi.StringOutput)\n}", "func (r ManagedResource) id() ReferenceID { return r.ID }", "func (c *EBSVolumeResizer) GetProviderVolumeID(pv *v1.PersistentVolume) (string, error) {\n\tvolumeID := pv.Spec.AWSElasticBlockStore.VolumeID\n\tif volumeID == \"\" {\n\t\treturn \"\", fmt.Errorf(\"volume id is empty for volume %q\", pv.Name)\n\t}\n\tidx := strings.LastIndex(volumeID, constants.EBSVolumeIDStart) + 1\n\tif idx == 0 {\n\t\treturn \"\", fmt.Errorf(\"malfored EBS volume id %q\", volumeID)\n\t}\n\treturn volumeID[idx:], nil\n}", "func (n *resPool) ID() string {\n\treturn n.id\n}", "func (tr *Cluster) GetID() string {\n\tif tr.Status.AtProvider.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *tr.Status.AtProvider.ID\n}", "func ResourceProviderID(input string) (*ResourceProviderId, error) {\n\tid, err := azure.ParseAzureResourceID(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresourceId := ResourceProviderId{\n\t\tSubscriptionId: id.SubscriptionID,\n\t\tResourceProvider: id.Provider,\n\t}\n\n\tif resourceId.SubscriptionId == \"\" {\n\t\treturn nil, fmt.Errorf(\"ID was missing the 'subscriptions' element\")\n\t}\n\n\tif resourceId.ResourceProvider == \"\" {\n\t\treturn nil, fmt.Errorf(\"ID was missing the 'providers' element\")\n\t}\n\n\tif err := id.ValidateNoEmptySegments(input); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &resourceId, nil\n}", "func (o *os) GetUniqueId() gdnative.String {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetUniqueId()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"_OS\", \"get_unique_id\")\n\n\t// Call the parent method.\n\t// String\n\tretPtr := gdnative.NewEmptyString()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewStringFromPointer(retPtr)\n\treturn ret\n}", "func (s *Server) ID() string {\n\treturn s.Config().GetUuid()\n}", "func (a *Agent) ID() string {\n\n\tresult, err := a.sentry.PublicKeyBase64()\n\tif err != nil {\n\t\terr = stacktrace.Propagate(err, \"could not get node ID\")\n\t\tpanic(err)\n\t}\n\treturn result\n}", "func (c VpnCredential) GetID() string { return c.ID }", "func (m *WindowsUniversalAppX) GetIdentityResourceIdentifier()(*string) {\n return m.identityResourceIdentifier\n}", "func (c *Config) GetIdP() string { //nolint: golint\n\treturn c.member.GetString(identityProviderName)\n}", "func (c *CreateRedfishResource) AggregateID() eh.UUID { return c.ID }", "func (tr *Account) GetID() string {\n\tif tr.Status.AtProvider.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *tr.Status.AtProvider.ID\n}", "func (tr *CassandraKeySpace) GetID() string {\n\tif tr.Status.AtProvider.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *tr.Status.AtProvider.ID\n}", "func (o MongoDBDatabaseResourceOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MongoDBDatabaseResource) string { return v.Id }).(pulumi.StringOutput)\n}", "func (e *environ) UniqueID() string {\n\treturn e.uid\n}", "func (o GremlinDatabaseResourceOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GremlinDatabaseResource) string { return v.Id }).(pulumi.StringOutput)\n}", "func (c *localComponent) ID() dependency.Instance {\n\treturn dependency.PolicyBackend\n}", "func (o ProviderOutput) ClientId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Provider) pulumi.StringPtrOutput { return v.ClientId }).(pulumi.StringPtrOutput)\n}", "func getInstanceID(providerID string) string {\n\tproviderTokens := strings.Split(providerID, \"/\")\n\treturn providerTokens[len(providerTokens)-1]\n}", "func getInstanceID(providerID string) string {\n\tproviderTokens := strings.Split(providerID, \"/\")\n\treturn providerTokens[len(providerTokens)-1]\n}", "func (pk PublicKey) ID() string {\n\treturn stringEntry(pk[IDProperty])\n}", "func (o SqlDatabaseResourceOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SqlDatabaseResource) string { return v.Id }).(pulumi.StringOutput)\n}", "func (tr *MongoDatabase) GetID() string {\n\tif tr.Status.AtProvider.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *tr.Status.AtProvider.ID\n}", "func (mgr *Manager) UUID() string {\n\treturn mgr.uuid\n}", "func NewID() string {\n\treturn ksuid.New().String()\n}", "func (u User) ID() string {\n\tif u.IsAnonymous() {\n\t\treturn \"user/anonymous\"\n\t}\n\treturn \"user/\" + string(u)\n}", "func (tr *MongoCollection) GetID() string {\n\tif tr.Status.AtProvider.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *tr.Status.AtProvider.ID\n}", "func (u *User) ID() string { return u.userData.ID.Hex() }", "func (r *GenericResource) GUID() string {\n\treturn r.Metadata.Labels[LabelGUID]\n}", "func (o MongoDBCollectionResourceOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MongoDBCollectionResource) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o SqlContainerResourceOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SqlContainerResource) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GremlinGraphResourceOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GremlinGraphResource) string { return v.Id }).(pulumi.StringOutput)\n}", "func (c *MockAzureCloud) ProviderID() kops.CloudProviderID {\n\treturn kops.CloudProviderAzure\n}", "func (p *Peer) ID() string {\n\treturn fmt.Sprintf(\"%s.%s\", p.Organization, p.Name)\n}", "func newID() string {\n\treturn \"_\" + uuid.New().String()\n}", "func (o ResourcePolicyExemptionOutput) ResourceId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyExemption) pulumi.StringOutput { return v.ResourceId }).(pulumi.StringOutput)\n}", "func (auth *Authentication) ID() string {\n\treturn auth.UserID\n}", "func identityResourceID(t *testing.T, identityName string) string {\n\tt.Helper()\n\treturn fmt.Sprintf(\"/subscriptions/sub-id/resourceGroups/group-name/providers/Microsoft.ManagedIdentity/userAssignedIdentities/%s\", identityName)\n}", "func ID() (string, error) {\n\tid, err := hardwareId()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"hardwareid: %v\", err)\n\t}\n\treturn id, nil\n}", "func (contextConf *LibcomposeContextProperty) Id() string {\n\treturn OPERATION_PROPERTY_LIBCOMPOSE_CONTEXT\n}", "func (c Client) GetIdentifier() network.Identifier { return c.identify }", "func (id NodeConfigurationId) ID() string {\n\tfmtString := \"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Automation/automationAccounts/%s/nodeConfigurations/%s\"\n\treturn fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.AutomationAccountName, id.NodeConfigurationName)\n}", "func GetGoID() int64", "func (c *ClaimContent) ID() string {\n\tvar json = jsoniter.ConfigCompatibleWithStandardLibrary\n\tdata, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\t// now simply using sha3.\n\t// TODO change hmac method with algorith\n\tid := sha3.Sum224(data)\n\treturn base64.URLEncoding.EncodeToString(id[:])\n}", "func (o CassandraTableResourceOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v CassandraTableResource) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o DatasourceOutput) ResourceID() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Datasource) string { return v.ResourceID }).(pulumi.StringOutput)\n}", "func (m *AuthenticationContext) GetId()(*string) {\n val, err := m.GetBackingStore().Get(\"id\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o CassandraKeyspaceResourcePtrOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *CassandraKeyspaceResource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Id\n\t}).(pulumi.StringPtrOutput)\n}", "func (tr *SQLDatabase) GetID() string {\n\tif tr.Status.AtProvider.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *tr.Status.AtProvider.ID\n}", "func (p ObjectID) ID() string {\n\treturn fmt.Sprintf(\"%d.%d.%d\",\n\t\tp.SpaceType(),\n\t\tp.ObjectType(),\n\t\tp.Instance(),\n\t)\n}", "func (m *_MonitoringParameters) GetIdentifier() string {\n\treturn \"742\"\n}", "func (c *ConsumerGroupInfo) ID() string {\n\treturn c.id\n}", "func (e *ChainEncryptor) ID() string {\n\treturn e.id\n}", "func (o GremlinDatabaseResourcePtrOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *GremlinDatabaseResource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Id\n\t}).(pulumi.StringPtrOutput)\n}", "func (ca *NullClientAdapter) ID() string {\n\treturn ca.ClientID\n}", "func (pe *ProgramExt) UUID() string {\n\treturn fmt.Sprintf(\"%s_%s\", pe.Manager, pe.Config)\n}", "func (o AnalyzerStorageAccountOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AnalyzerStorageAccount) string { return v.Id }).(pulumi.StringOutput)\n}", "func (c *Connector) ID() string {\n\tc.cmu.Lock()\n\tdefer c.cmu.Unlock()\n\treturn c.id\n}", "func (tr *GremlinDatabase) GetID() string {\n\tif tr.Status.AtProvider.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *tr.Status.AtProvider.ID\n}", "func (tr *Table) GetID() string {\n\tif tr.Status.AtProvider.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *tr.Status.AtProvider.ID\n}", "func (b *base) ID() string { return b.IDx }", "func (store Storage) UUID() string {\n\treturn \"\"\n}", "func (c *Connection) ID() string {\n\treturn fmt.Sprintf(\"[%s@%d_%d]\", c.url, c.id, c.cc)\n}", "func (p *ProvisionTokenV2) GetResourceID() int64 {\n\treturn p.Metadata.ID\n}", "func (p *Person) ID() string {\n\treturn fmt.Sprintf(\"Person's identifier: %s\", p.Citizen.ID())\n}", "func (p *partitionImpl) ID() string {\n\treturn p.internalData.Id\n}", "func (id SubscriptionId) ID() string {\n\tfmtString := \"/providers/Microsoft.Management/managementGroups/%s/subscriptions/%s\"\n\treturn fmt.Sprintf(fmtString, id.GroupId, id.SubscriptionId)\n}", "func (key *ConfigKeyProperty) Id() string {\n\treturn OPERATION_PROPERTY_CONFIG_KEY\n}", "func (c *RemoveRedfishResource) AggregateID() eh.UUID { return c.ID }", "func (s *ServiceContext) ID() string {\n\treturn path.Base(s.Source.Location)\n}", "func (i *InstanceIdentity) GetIdentifier() string {\n\tident := strings.Join([]string{i.AccountID, i.InstanceID}, \"-\")\n\th := sha1.New()\n\th.Write([]byte(ident))\n\tbid := h.Sum(nil)\n\treturn fmt.Sprintf(\"%x\", bid)\n}", "func (r *ResourceGroup) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (o GremlinGraphResourcePtrOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *GremlinGraphResource) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Id\n\t}).(pulumi.StringPtrOutput)\n}", "func (id NetworkGroupId) ID() string {\n\tfmtString := \"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/networkManagers/%s/networkGroups/%s\"\n\treturn fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.NetworkManagerName, id.NetworkGroupName)\n}", "func (tr *CassandraTable) GetID() string {\n\tif tr.Status.AtProvider.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *tr.Status.AtProvider.ID\n}", "func (sub *Subscription) ID() string {\n return sub.id\n}" ]
[ "0.682701", "0.6808371", "0.629306", "0.6281841", "0.6188704", "0.61797756", "0.61281586", "0.6087287", "0.6057715", "0.6057062", "0.60541266", "0.60401195", "0.6015796", "0.5990656", "0.59881324", "0.59791076", "0.5976729", "0.5970298", "0.5959781", "0.58148205", "0.5813212", "0.57924324", "0.57854486", "0.5757655", "0.5734714", "0.57058173", "0.5700836", "0.56929165", "0.5685064", "0.56752914", "0.5661092", "0.566013", "0.5656271", "0.5651034", "0.56201017", "0.56173444", "0.5617123", "0.5603601", "0.5596125", "0.5580794", "0.5575892", "0.55753857", "0.5569519", "0.5568644", "0.5568644", "0.55654234", "0.5564191", "0.5557033", "0.5545406", "0.55379474", "0.55364335", "0.5529504", "0.5525688", "0.55185235", "0.55114543", "0.55031013", "0.5501458", "0.5493865", "0.549331", "0.5491594", "0.5487331", "0.5475745", "0.5468239", "0.5451577", "0.54507154", "0.5441096", "0.5429236", "0.54220027", "0.540713", "0.54058826", "0.5396819", "0.5386145", "0.5386108", "0.53828335", "0.53795457", "0.53687364", "0.53669024", "0.53622156", "0.53577524", "0.5355876", "0.53518933", "0.53492266", "0.5348656", "0.53483963", "0.53475356", "0.5341561", "0.5340841", "0.53308415", "0.5330798", "0.53288215", "0.5324396", "0.53206575", "0.5319735", "0.53194684", "0.53177714", "0.5315455", "0.53118354", "0.5311709", "0.53098077", "0.53094625", "0.5306288" ]
0.0
-1
Set of names of the matched Image Builder Infrastructure Configurations.
func (o GetInfrastructureConfigurationsResultOutput) Names() pulumi.StringArrayOutput { return o.ApplyT(func(v GetInfrastructureConfigurationsResult) []string { return v.Names }).(pulumi.StringArrayOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func initImageNames() map[int]string {\n\tswitch getTestArch() {\n\tcase \"s390x\":\n\t\treturn map[int]string{\n\t\t\tbusyboxImage: \"busybox@sha256:4f47c01fa91355af2865ac10fef5bf6ec9c7f42ad2321377c21e844427972977\",\n\t\t\tregistryImage: \"ibmcom/registry:2.6.2.5\",\n\t\t\tkanikoImage: \"gcr.io/kaniko-project/executor:s390x-9ed158c1f63a059cde4fd5f8b95af51d452d9aa7\",\n\t\t\tdockerizeImage: \"ibmcom/dockerize-s390x\",\n\t\t}\n\tcase \"ppc64le\":\n\t\treturn map[int]string{\n\t\t\tbusyboxImage: \"busybox@sha256:4f47c01fa91355af2865ac10fef5bf6ec9c7f42ad2321377c21e844427972977\",\n\t\t\tregistryImage: \"ppc64le/registry:2\",\n\t\t\tkanikoImage: \"ibmcom/kaniko-project-executor-ppc64le:v0.17.1\",\n\t\t\tdockerizeImage: \"ibmcom/dockerize-ppc64le\",\n\t\t}\n\tdefault:\n\t\treturn map[int]string{\n\t\t\tbusyboxImage: \"busybox@sha256:895ab622e92e18d6b461d671081757af7dbaa3b00e3e28e12505af7817f73649\",\n\t\t\tregistryImage: \"registry\",\n\t\t\tkanikoImage: \"gcr.io/kaniko-project/executor:v1.3.0\",\n\t\t\tdockerizeImage: \"jwilder/dockerize\",\n\t\t}\n\t}\n}", "func (d *aciDriver) Config() map[string]string {\n\treturn map[string]string{\n\t\t\"CNAB_AZURE_VERBOSE\": \"Increase verbosity. true, false are supported values\",\n\t\t\"CNAB_AZURE_CLIENT_ID\": \"AAD Client ID for Azure account authentication - used to authenticate to Azure for ACI creation\",\n\t\t\"CNAB_AZURE_CLIENT_SECRET\": \"AAD Client Secret for Azure account authentication - used to authenticate to Azure for ACI creation\",\n\t\t\"CNAB_AZURE_TENANT_ID\": \"Azure AAD Tenant Id Azure account authentication - used to authenticate to Azure for ACI creation\",\n\t\t\"CNAB_AZURE_SUBSCRIPTION_ID\": \"Azure Subscription Id - this is the subscription to be used for ACI creation, if not specified the default subscription is used\",\n\t\t\"CNAB_AZURE_APP_ID\": \"Azure Application Id - this is the application to be used to authenticate to Azure\",\n\t\t\"CNAB_AZURE_RESOURCE_GROUP\": \"The name of the existing Resource Group to create the ACI instance in, if not specified a Resource Group will be created\",\n\t\t\"CNAB_AZURE_LOCATION\": \"The location to create the ACI Instance in\",\n\t\t\"CNAB_AZURE_NAME\": \"The name of the ACI instance to create - if not specified a name will be generated\",\n\t\t\"CNAB_AZURE_DELETE_RESOURCES\": \"Delete RG and ACI instance created - default is true useful to set to false for debugging - only deletes RG if it was created by the driver\",\n\t\t\"CNAB_AZURE_MSI_TYPE\": \"This can be set to user or system\",\n\t\t\"CNAB_AZURE_SYSTEM_MSI_ROLE\": \"The role to be asssigned to System MSI User - used if CNAB_AZURE_ACI_MSI_TYPE == system, if this is null or empty then the role defaults to contributor\",\n\t\t\"CNAB_AZURE_SYSTEM_MSI_SCOPE\": \"The scope to apply the role to System MSI User - will attempt to set scope to the Resource Group that the ACI Instance is being created in if not set\",\n\t\t\"CNAB_AZURE_USER_MSI_RESOURCE_ID\": \"The resource Id of the MSI User - required if CNAB_AZURE_ACI_MSI_TYPE == User \",\n\t\t\"CNAB_AZURE_PROPAGATE_CREDENTIALS\": \"If this is set to true the credentials used to Launch the Driver are propagated to the invocation image in an ENV variable, the CNAB_AZURE prefix will be relaced with AZURE_, default is false\",\n\t\t\"CNAB_AZURE_USE_CLIENT_CREDS_FOR_REGISTRY_AUTH\": \"If this is set to true the CNAB_AZURE_CLIENT_ID and CNAB_AZURE_CLIENT_SECRET are also used for authentication to ACR\",\n\t\t\"CNAB_AZURE_REGISTRY_USERNAME\": \"The username for authenticating to the container registry\",\n\t\t\"CNAB_AZURE_REGISTRY_PASSWORD\": \"The password for authenticating to the container registry\",\n\t\t\"CNAB_AZURE_STATE_FILESHARE\": \"The File Share for Azure State volume\",\n\t\t\"CNAB_AZURE_STATE_STORAGE_ACCOUNT_NAME\": \"The Storage Account for the Azure State File Share\",\n\t\t\"CNAB_AZURE_STATE_STORAGE_ACCOUNT_KEY\": \"The Storage Key for the Azure State File Share\",\n\t\t\"CNAB_AZURE_STATE_MOUNT_POINT\": \"The mount point location for state volume\",\n\t\t\"CNAB_AZURE_DELETE_OUTPUTS_FROM_FILESHARE\": \"Any Outputs Created in the fileshare are deleted on completion\",\n\t\t\"CNAB_AZURE_DEBUG_CONTAINER\": \"Replaces /cnab/app/run with tail -f /dev/null so that container can be connected to and debugged\",\n\t}\n}", "func (p *eksClusterProvider) ConfigurationItems() config.ConfigurationSet {\n\tcs := aws.SharedConfig()\n\n\tcs.String(\"region-filter\", \"\", \"A filter to apply to the AWS regions list, e.g. 'us-' will only show US regions\") //nolint: errcheck\n\tcs.String(\"role-arn\", \"\", \"ARN of the AWS role to be assumed\") //nolint: errcheck\n\tcs.String(\"role-filter\", \"\", \"A filter to apply to the roles list, e.g. 'EKS' will only show roles that contain EKS in the name\") //nolint: errcheck\n\n\treturn cs\n}", "func imageNamesMapping() map[string]string {\n\n\tswitch getTestArch() {\n\tcase \"s390x\":\n\t\treturn map[string]string{\n\t\t\t\"registry\": getTestImage(registryImage),\n\t\t\t\"node\": \"node:alpine3.11\",\n\t\t\t\"gcr.io/cloud-builders/git\": \"alpine/git:latest\",\n\t\t\t\"docker:dind\": \"ibmcom/docker-s390x:dind\",\n\t\t\t\"docker\": \"docker:18.06.3\",\n\t\t\t\"mikefarah/yq:3\": \"danielxlee/yq:2.4.0\",\n\t\t\t\"stedolan/jq\": \"ibmcom/jq-s390x:latest\",\n\t\t\t\"gcr.io/kaniko-project/executor:v1.3.0\": getTestImage(kanikoImage),\n\t\t}\n\tcase \"ppc64le\":\n\t\treturn map[string]string{\n\t\t\t\"registry\": getTestImage(registryImage),\n\t\t\t\"node\": \"node:alpine3.11\",\n\t\t\t\"gcr.io/cloud-builders/git\": \"alpine/git:latest\",\n\t\t\t\"docker:dind\": \"ibmcom/docker-ppc64le:19.03-dind\",\n\t\t\t\"docker\": \"docker:18.06.3\",\n\t\t\t\"mikefarah/yq:3\": \"danielxlee/yq:2.4.0\",\n\t\t\t\"stedolan/jq\": \"ibmcom/jq-ppc64le:latest\",\n\t\t\t\"gcr.io/kaniko-project/executor:v1.3.0\": getTestImage(kanikoImage),\n\t\t}\n\n\t}\n\n\treturn make(map[string]string)\n}", "func (s *Split) Configurations() map[string]string {\n\treturn s.splitData.Configurations\n}", "func (o RegistryTaskDockerStepOutput) ImageNames() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v RegistryTaskDockerStep) []string { return v.ImageNames }).(pulumi.StringArrayOutput)\n}", "func (p *ProviderConfig) GetAllProviderNames() []string {\n\tproviderNames := make([]string, 0)\n\n\tfor name := range p.Alibaba {\n\t\tproviderNames = append(providerNames, name)\n\t}\n\tfor name := range p.Anexia {\n\t\tproviderNames = append(providerNames, name)\n\t}\n\tfor name := range p.Aws {\n\t\tproviderNames = append(providerNames, name)\n\t}\n\tfor name := range p.Azure {\n\t\tproviderNames = append(providerNames, name)\n\t}\n\tfor name := range p.Digitalocean {\n\t\tproviderNames = append(providerNames, name)\n\t}\n\tfor name := range p.Fake {\n\t\tproviderNames = append(providerNames, name)\n\t}\n\tfor name := range p.Gcp {\n\t\tproviderNames = append(providerNames, name)\n\t}\n\tfor name := range p.Hetzner {\n\t\tproviderNames = append(providerNames, name)\n\t}\n\tfor name := range p.Kubevirt {\n\t\tproviderNames = append(providerNames, name)\n\t}\n\tfor name := range p.Openstack {\n\t\tproviderNames = append(providerNames, name)\n\t}\n\tfor name := range p.Packet {\n\t\tproviderNames = append(providerNames, name)\n\t}\n\tfor name := range p.Vsphere {\n\t\tproviderNames = append(providerNames, name)\n\t}\n\n\treturn providerNames\n}", "func GetConfigsByDI(dimensionInfo string) map[string]interface{} {\n\treturn DefaultConf.ConfigFactory.GetConfigurationsByDimensionInfo(dimensionInfo)\n}", "func (r *ReplicaSet) Images() map[string]string {\n\timages := map[string]string{}\n\n\tfor _, c := range r.raw.Spec.Template.Spec.Containers {\n\t\timages[c.Name] = c.Image\n\t}\n\n\treturn images\n}", "func GetImageOverrides() map[string]string {\n\timageOverrides := make(map[string]string)\n\n\t// First check for environment variables containing the 'OPERAND_IMAGE_' prefix\n\tfor _, e := range os.Environ() {\n\t\tkeyValuePair := strings.SplitN(e, \"=\", 2)\n\t\tif strings.HasPrefix(keyValuePair[0], OperandImagePrefix) {\n\t\t\tkey := strings.ToLower(strings.Replace(keyValuePair[0], OperandImagePrefix, \"\", -1))\n\t\t\timageOverrides[key] = keyValuePair[1]\n\t\t}\n\t}\n\n\t// If entries exist containing operand image prefix, return\n\tif len(imageOverrides) > 0 {\n\t\tlogf.Info(\"Found image overrides from environment variables set by operand image prefix\")\n\t\treturn imageOverrides\n\t}\n\n\t// If no image overrides found, check 'RELATED_IMAGE_' prefix\n\tfor _, e := range os.Environ() {\n\t\tkeyValuePair := strings.SplitN(e, \"=\", 2)\n\t\tif strings.HasPrefix(keyValuePair[0], OSBSImagePrefix) {\n\t\t\tkey := strings.ToLower(strings.Replace(keyValuePair[0], OSBSImagePrefix, \"\", -1))\n\t\t\timageOverrides[key] = keyValuePair[1]\n\t\t}\n\t}\n\n\t// If entries exist containing related image prefix, return\n\tif len(imageOverrides) > 0 {\n\t\tlogf.Info(\"Found image overrides from environment variables set by related image prefix\")\n\t}\n\n\treturn imageOverrides\n}", "func AllConfigOptions() []string {\n\treturn allConfigOptions\n}", "func GetAll() interface{} { return viper.AllKeys() }", "func (r QuayAdapter) GetImageNames() ([]string, error) {\n\tlog.Debug(\"QuayAdapter::GetImages\")\n\tlog.Debug(\"BundleSpecLabel: %s\", BundleSpecLabel)\n\tlog.Debug(\"Loading image list for quay.io Org: [ %v ]\", r.config.Org)\n\n\tvar imageList []string\n\n\t// check if we're configured for specific images\n\tif len(r.config.Images) > 0 {\n\t\tlog.Debugf(\"Configured to use images: %v\", r.config.Images)\n\t\timageList = append(imageList, r.config.Images...)\n\t}\n\n\t// discover images\n\treq, err := http.NewRequest(\"GET\", fmt.Sprintf(quayCatalogURL, r.config.URL, r.config.Org), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %v\", r.config.Token))\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to load catalog response at %s - %v\", fmt.Sprintf(quayCatalogURL, r.config.URL, r.config.Org), err)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tcatalogResp := quayImageResponse{}\n\terr = json.NewDecoder(resp.Body).Decode(&catalogResp)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to decode Catalog response from '%s'\", fmt.Sprintf(quayCatalogURL, r.config.URL, r.config.Org))\n\t\treturn nil, err\n\t}\n\n\tfor _, repo := range catalogResp.Repositories {\n\t\timageList = append(imageList, repo.Name)\n\t}\n\n\tif len(imageList) == 0 {\n\t\tlog.Warn(\"image list is empty. No images were discovered\")\n\t\treturn imageList, nil\n\t}\n\n\tvar uniqueList []string\n\timageMap := make(map[string]struct{})\n\tfor _, image := range imageList {\n\t\timageMap[image] = struct{}{}\n\t}\n\n\t// create a unique image list\n\tfor key := range imageMap {\n\t\tuniqueList = append(uniqueList, key)\n\t}\n\treturn uniqueList, nil\n}", "func (o ApplicationSpecSourceKustomizeOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationSpecSourceKustomize) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func ServiceNames(svr ...string) []string {\n\treturn append(svr,\n\t\t\"erda.msp.configcenter.ConfigCenterService\",\n\t)\n}", "func getRegistryDeploymentLabels(pkgName string) map[string]string {\n\tlabels := makeRegistryLabels(pkgName)\n\tlabels[\"server-name\"] = getRegistryServerName(pkgName)\n\treturn labels\n}", "func (c *Client) GetInstitutions() (map[string]interface{}, error) {\n\tlog.info(\"========== GET INSTITUTIONS ==========\")\n\turl := buildURL(path[\"institutions\"])\n\n\treturn c.do(\"GET\", url, \"\", nil)\n}", "func (c *CleanerOptions) WebhookConfigurationsName() []string {\n\treturn strings.Split(c.WebhookConfigurations, \" \")\n}", "func RemoveImage(removeAll bool, names []string) error {\n\tconfig := configutil.GetBaseConfig()\n\n\tif len(names) == 0 && removeAll == false {\n\t\treturn fmt.Errorf(\"You have to specify at least one image\")\n\t}\n\n\tnewImageList := make(map[string]*v1.ImageConfig)\n\n\tif !removeAll && config.Images != nil {\n\n\tImagesLoop:\n\t\tfor nameInConfig, imageConfig := range *config.Images {\n\t\t\tfor _, deletionName := range names {\n\t\t\t\tif deletionName == nameInConfig {\n\t\t\t\t\tcontinue ImagesLoop\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnewImageList[nameInConfig] = imageConfig\n\t\t}\n\t}\n\n\tconfig.Images = &newImageList\n\n\terr := configutil.SaveBaseConfig()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Couldn't save config file: %v\", err)\n\t}\n\n\treturn nil\n}", "func GetOriginalImageConfigs() map[ImageID]Config {\n\treturn originalImageConfigs\n}", "func (p *EC2Provisioner) ListImageOptions(region string) ([]string, error) {\n\t// Set requested region\n\tp.WithRegion(region)\n\n\t// Query for easily supported images\n\toutput, err := p.client.DescribeImages(&ec2.DescribeImagesInput{\n\t\tOwners: []*string{aws.String(\"amazon\")},\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\t// Only display Amazon for ease of use\n\t\t\t\tName: aws.String(\"name\"),\n\t\t\t\tValues: []*string{aws.String(\"amzn*\")},\n\t\t\t},\n\t\t\t{\n\t\t\t\t// Docker needs machine to run properly\n\t\t\t\tName: aws.String(\"image-type\"),\n\t\t\t\tValues: []*string{aws.String(\"machine\")},\n\t\t\t},\n\t\t\t{\n\t\t\t\t// No funny business\n\t\t\t\tName: aws.String(\"architecture\"),\n\t\t\t\tValues: []*string{aws.String(\"x86_64\")},\n\t\t\t},\n\t\t\t{\n\t\t\t\t// Most standard instances only support EBS\n\t\t\t\tName: aws.String(\"root-device-type\"),\n\t\t\t\tValues: []*string{aws.String(\"ebs\")},\n\t\t\t},\n\t\t\t{\n\t\t\t\t// Paravirtual images don't work - see #500\n\t\t\t\tName: aws.String(\"virtualization-type\"),\n\t\t\t\tValues: []*string{aws.String(\"hvm\")},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Sort by date\n\tsort.Slice(output.Images, func(i, j int) bool {\n\t\tiCreated := common.ParseDate(*output.Images[i].CreationDate)\n\t\tif iCreated == nil {\n\t\t\treturn false\n\t\t}\n\t\tjCreated := common.ParseDate(*output.Images[j].CreationDate)\n\t\tif jCreated == nil {\n\t\t\treturn true\n\t\t}\n\t\treturn iCreated.After(*jCreated)\n\t})\n\n\t// Format image names for printing\n\timages := []string{}\n\tfor _, image := range output.Images {\n\t\tif len(images) == 10 {\n\t\t\tbreak\n\t\t}\n\t\t// Ignore nameless images\n\t\tif image.Name != nil {\n\t\t\t// Rudimentary filter to remove ECS images - see https://github.com/ubclaunchpad/inertia/issues/633\n\t\t\tif strings.Contains(*image.ImageId, \"ECS\") || strings.Contains(*image.Description, \"ECS\") {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\timages = append(images, fmt.Sprintf(\"%s (%s)\", *image.ImageId, *image.Description))\n\t\t}\n\n\t}\n\treturn images, nil\n}", "func (n *resPool) Resources() map[string]*respool.ResourceConfig {\n\tn.RLock()\n\tdefer n.RUnlock()\n\treturn n.resourceConfigs\n}", "func (c *configImpl) GetAll() map[string]gophercloud.AuthOptions {\n\tif len(c.clouds) == 0 {\n\t\treturn nil\n\t}\n\tcs := map[string]gophercloud.AuthOptions{}\n\tfor k, v := range c.clouds {\n\t\tcs[k] = v\n\t}\n\treturn cs\n}", "func (g GuardDutyInstances) ResourceIdentifiers() []string {\n\treturn g.DetectorIds\n}", "func (r OpenstackAdapter) GetImageNames() ([]string, error) {\n\tvar apbNames []string\n\tvar projects []string\n\n\tif len(r.Config.Org) == 0 {\n\t\ttoken, err := r.getUnscopedToken()\n\t\tif err != nil {\n\t\t\treturn apbNames, err\n\t\t}\n\t\tprojects, err = r.getObjectList(token, \"projects\", \"/identity/v3/auth/projects\", \"\")\n\t\tif err != nil {\n\t\t\treturn apbNames, err\n\t\t}\n\t} else {\n\t\tprojects = append(projects, r.Config.Org)\n\t}\n\n\tfor _, project := range projects {\n\t\tfor _, service := range services {\n\t\t\tapbNames = append(apbNames, fmt.Sprintf(\"openstack-%v-%v-project-apb\", service, project))\n\t\t}\n\t}\n\n\treturn apbNames, nil\n}", "func (o ApplicationStatusOperationStateOperationSyncSourceKustomizeOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateOperationSyncSourceKustomize) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func TestDaemon_ListImagesWithOptions(t *testing.T) {\n\td, start, clean, _, _, _ := mockDaemon(t)\n\tstart()\n\tdefer clean()\n\n\tctx := context.Background()\n\n\tspecAll := update.ResourceSpec(update.ResourceSpecAll)\n\n\t// Service 1\n\tsvcID, err := resource.ParseID(wl)\n\tassert.NoError(t, err)\n\tcurrentImageRef, err := image.ParseRef(currentHelloImage)\n\tassert.NoError(t, err)\n\tnewImageRef, err := image.ParseRef(newHelloImage)\n\tassert.NoError(t, err)\n\toldImageRef, err := image.ParseRef(oldHelloImage)\n\tassert.NoError(t, err)\n\n\t// Service 2\n\tanotherSvcID, err := resource.ParseID(anotherWl)\n\tassert.NoError(t, err)\n\tanotherImageRef, err := image.ParseRef(anotherImage)\n\tassert.NoError(t, err)\n\n\ttests := []struct {\n\t\tname string\n\t\topts v10.ListImagesOptions\n\n\t\texpectedImages []v6.ImageStatus\n\t\texpectedNumImages int\n\t\tshouldError bool\n\t}{\n\t\t{\n\t\t\tname: \"All services\",\n\t\t\topts: v10.ListImagesOptions{Spec: specAll},\n\t\t\texpectedImages: []v6.ImageStatus{\n\t\t\t\t{\n\t\t\t\t\tID: svcID,\n\t\t\t\t\tContainers: []v6.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: container,\n\t\t\t\t\t\t\tCurrent: image.Info{ID: currentImageRef},\n\t\t\t\t\t\t\tLatestFiltered: image.Info{ID: newImageRef},\n\t\t\t\t\t\t\tAvailable: []image.Info{\n\t\t\t\t\t\t\t\t{ID: newImageRef},\n\t\t\t\t\t\t\t\t{ID: currentImageRef},\n\t\t\t\t\t\t\t\t{ID: oldImageRef},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tAvailableImagesCount: 3,\n\t\t\t\t\t\t\tNewAvailableImagesCount: 1,\n\t\t\t\t\t\t\tFilteredImagesCount: 3,\n\t\t\t\t\t\t\tNewFilteredImagesCount: 1,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tID: anotherSvcID,\n\t\t\t\t\tContainers: []v6.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: anotherContainer,\n\t\t\t\t\t\t\tCurrent: image.Info{ID: anotherImageRef},\n\t\t\t\t\t\t\tLatestFiltered: image.Info{},\n\t\t\t\t\t\t\tAvailable: []image.Info{\n\t\t\t\t\t\t\t\t{ID: anotherImageRef},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tAvailableImagesCount: 1,\n\t\t\t\t\t\t\tNewAvailableImagesCount: 0,\n\t\t\t\t\t\t\tFilteredImagesCount: 0, // Excludes latest\n\t\t\t\t\t\t\tNewFilteredImagesCount: 0,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Specific service\",\n\t\t\topts: v10.ListImagesOptions{Spec: update.ResourceSpec(wl)},\n\t\t\texpectedImages: []v6.ImageStatus{\n\t\t\t\t{\n\t\t\t\t\tID: svcID,\n\t\t\t\t\tContainers: []v6.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: container,\n\t\t\t\t\t\t\tCurrent: image.Info{ID: currentImageRef},\n\t\t\t\t\t\t\tLatestFiltered: image.Info{ID: newImageRef},\n\t\t\t\t\t\t\tAvailable: []image.Info{\n\t\t\t\t\t\t\t\t{ID: newImageRef},\n\t\t\t\t\t\t\t\t{ID: currentImageRef},\n\t\t\t\t\t\t\t\t{ID: oldImageRef},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tAvailableImagesCount: 3,\n\t\t\t\t\t\t\tNewAvailableImagesCount: 1,\n\t\t\t\t\t\t\tFilteredImagesCount: 3,\n\t\t\t\t\t\t\tNewFilteredImagesCount: 1,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Override container field selection\",\n\t\t\topts: v10.ListImagesOptions{\n\t\t\t\tSpec: specAll,\n\t\t\t\tOverrideContainerFields: []string{\"Name\", \"Current\", \"NewAvailableImagesCount\"},\n\t\t\t},\n\t\t\texpectedImages: []v6.ImageStatus{\n\t\t\t\t{\n\t\t\t\t\tID: svcID,\n\t\t\t\t\tContainers: []v6.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: container,\n\t\t\t\t\t\t\tCurrent: image.Info{ID: currentImageRef},\n\t\t\t\t\t\t\tNewAvailableImagesCount: 1,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tID: anotherSvcID,\n\t\t\t\t\tContainers: []v6.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: anotherContainer,\n\t\t\t\t\t\t\tCurrent: image.Info{ID: anotherImageRef},\n\t\t\t\t\t\t\tNewAvailableImagesCount: 0,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Override container field selection with invalid field\",\n\t\t\topts: v10.ListImagesOptions{\n\t\t\t\tSpec: specAll,\n\t\t\t\tOverrideContainerFields: []string{\"InvalidField\"},\n\t\t\t},\n\t\t\texpectedImages: nil,\n\t\t\tshouldError: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Specific namespace\",\n\t\t\topts: v10.ListImagesOptions{\n\t\t\t\tSpec: specAll,\n\t\t\t\tNamespace: ns,\n\t\t\t},\n\t\t\texpectedImages: []v6.ImageStatus{\n\t\t\t\t{\n\t\t\t\t\tID: svcID,\n\t\t\t\t\tContainers: []v6.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: container,\n\t\t\t\t\t\t\tCurrent: image.Info{ID: currentImageRef},\n\t\t\t\t\t\t\tLatestFiltered: image.Info{ID: newImageRef},\n\t\t\t\t\t\t\tAvailable: []image.Info{\n\t\t\t\t\t\t\t\t{ID: newImageRef},\n\t\t\t\t\t\t\t\t{ID: currentImageRef},\n\t\t\t\t\t\t\t\t{ID: oldImageRef},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tAvailableImagesCount: 3,\n\t\t\t\t\t\t\tNewAvailableImagesCount: 1,\n\t\t\t\t\t\t\tFilteredImagesCount: 3,\n\t\t\t\t\t\t\tNewFilteredImagesCount: 1,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Specific namespace and service\",\n\t\t\topts: v10.ListImagesOptions{\n\t\t\t\tSpec: update.ResourceSpec(wl),\n\t\t\t\tNamespace: ns,\n\t\t\t},\n\t\t\texpectedImages: nil,\n\t\t\tshouldError: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tis, err := d.ListImagesWithOptions(ctx, tt.opts)\n\t\t\tassert.Equal(t, tt.shouldError, err != nil)\n\n\t\t\t// Clear CreatedAt fields for testing\n\t\t\tfor ri, r := range is {\n\t\t\t\tfor ci, c := range r.Containers {\n\t\t\t\t\tis[ri].Containers[ci].Current.CreatedAt = time.Time{}\n\t\t\t\t\tis[ri].Containers[ci].LatestFiltered.CreatedAt = time.Time{}\n\t\t\t\t\tfor ai := range c.Available {\n\t\t\t\t\t\tis[ri].Containers[ci].Available[ai].CreatedAt = time.Time{}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.expectedImages, is)\n\t\t})\n\t}\n}", "func (project Project) getEnvironmentNames() []string {\n\tkeys := []string{}\n\n\tfor key := range project.Environments {\n\t\tkeys = append(keys, key)\n\t}\n\n\treturn keys\n}", "func (sc *StackerConfig) Substitutions() []string {\n\treturn []string{\n\t\tfmt.Sprintf(\"STACKER_ROOTFS_DIR=%s\", sc.RootFSDir),\n\t\tfmt.Sprintf(\"STACKER_STACKER_DIR=%s\", sc.StackerDir),\n\t\tfmt.Sprintf(\"STACKER_OCI_DIR=%s\", sc.OCIDir),\n\t}\n}", "func GetBuilders() []string {\n\tkeys := make([]string, 0, len(SupportedBuilders))\n\tfor key := range SupportedBuilders {\n\t\tkeys = append(keys, key)\n\t}\n\treturn keys\n}", "func PoolConfigs() (map[string]interface{}, error) {\n\tcmd := &Cmd{}\n\tres := make(map[string]interface{})\n\terr := NvlistIoctl(zfsHandle.Fd(), ZFS_IOC_POOL_CONFIGS, \"\", cmd, nil, res, nil)\n\treturn res, err\n}", "func labelsForConjurConfig(name string) map[string]string {\n\treturn map[string]string{\"app\": \"conjur-config\", \"conjur-config-cr\": name}\n}", "func (b *ExperimentBuilder) Options() (map[string]OptionInfo, error) {\n\tresult := make(map[string]OptionInfo)\n\tptrinfo := reflect.ValueOf(b.config)\n\tif ptrinfo.Kind() != reflect.Ptr {\n\t\treturn nil, errors.New(\"config is not a pointer\")\n\t}\n\tstructinfo := ptrinfo.Elem().Type()\n\tif structinfo.Kind() != reflect.Struct {\n\t\treturn nil, errors.New(\"config is not a struct\")\n\t}\n\tfor i := 0; i < structinfo.NumField(); i++ {\n\t\tfield := structinfo.Field(i)\n\t\tresult[field.Name] = OptionInfo{\n\t\t\tDoc: field.Tag.Get(\"ooni\"),\n\t\t\tType: field.Type.String(),\n\t\t}\n\t}\n\treturn result, nil\n}", "func (r *SoftwareImageResource) ListAll() (*SoftwareImageConfigList, error) {\n\tvar list SoftwareImageConfigList\n\tif err := r.c.ReadQuery(BasePath+SoftwareImageEndpoint, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &list, nil\n}", "func (o ApplicationOperationSyncSourceKustomizeOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationOperationSyncSourceKustomize) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func (p *Proxy) ServerNames() ([]string, error) {\n ns := []string{\"Error-Getting-Server-Names\"}\n rcon, err := p.GetRcon()\n if err != nil { return ns, err }\n\n command := fmt.Sprintf(\"bconf getServers().getKeys()\")\n reply, err := rcon.Send(command)\n if err != nil { return ns, err }\n\n reply = strings.Trim(reply, \"[] \\n\")\n names := strings.Split(reply, \",\")\n for i, n := range names {\n names[i] = strings.Trim(n, \" \")\n }\n return names, nil\n}", "func (s *Service) ComConfigsByName(teamName, env, zone, name string) (confs []*model.CommonConf, err error) {\n\tvar team *model.Team\n\tif team, err = s.TeamByName(teamName, env, zone); err != nil {\n\t\treturn\n\t}\n\tif err = s.dao.DB.Select(\"id,team_id,name,state,mark,operator,ctime,mtime\").Where(\"name = ? and team_id = ?\",\n\t\tname, team.ID).Order(\"id desc\").Limit(10).Find(&confs).Error; err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func GetConfigs() map[string]interface{} {\n\treturn archaius.GetConfigs()\n}", "func ReferencedImages(deployment *deployapi.Deployment) map[string]string {\n\tresult := make(map[string]string)\n\n\tif deployment == nil {\n\t\treturn result\n\t}\n\n\tfor _, container := range deployment.ControllerTemplate.Template.Spec.Containers {\n\t\tname, version := ParseContainerImage(container.Image)\n\t\tresult[name] = version\n\t}\n\n\treturn result\n}", "func (c *Config) Name() string { return IntegrationName }", "func InfraRegistry() []Prompt {\n\treturn []Prompt{\n\t\t{\n\t\t\tName: \"imageRegistry\",\n\t\t\tQuestion: \"Which docker image registry do you want to use?\",\n\t\t\tChoices: []string{\"ECR\", \"Nexus\"},\n\t\t\tDefault: \"ECR\",\n\t\t},\n\t}\n}", "func (o ApplicationStatusSyncComparedToSourceKustomizeOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationStatusSyncComparedToSourceKustomize) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func configureFlags(api *operations.EsiAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func GetEndpointsConfig() []string {\n\tos.Setenv(\"ETCDCTL_API\", viper.GetString(\"Etcd.Api\"))\n\t//fmt.Println(\"ETCD Api version: \", os.Getenv(\"ETCDCTL_API\"))\n\tos.Setenv(\"ETCDCTL_ENDPOINTS\", viper.GetString(\"Etcd.Endpoints\"))\n\t//fmt.Println(\"ETCD ENDPOINTS: \", os.Getenv(\"ETCDCTL_ENDPOINTS\"))\n\tos.Setenv(\"ETCDCTL_CERT\", viper.GetString(\"Etcd.Cert\"))\n\t//fmt.Println(\"ETCD CERT: \", os.Getenv(\"ETCDCTL_CERT\"))\n\tos.Setenv(\"ETCDCTL_CACERT\", viper.GetString(\"Etcd.CaCert\"))\n\t//fmt.Println(\"ETCD CACERT: \", os.Getenv(\"ETCDCTL_CACERT\"))\n\tos.Setenv(\"ETCDCTL_KEY\", viper.GetString(\"Etcd.Key\"))\n\t//fmt.Println(\"ETCD KEY: \", os.Getenv(\"ETCDCTL_KEY\"))\n\treturn []string{(viper.GetViper().GetString(\"Etcd.Endpoints\"))}\n}", "func deploymentLabels(ctx *core.DeploymentContext) map[string]string {\n\treturn map[string]string{\n\t\triserLabel(\"deployment\"): ctx.DeploymentConfig.Name,\n\t\triserLabel(\"environment\"): ctx.DeploymentConfig.EnvironmentName,\n\t\triserLabel(\"app\"): string(ctx.DeploymentConfig.App.Name),\n\t}\n}", "func PossibleConfigurationNameValues() []ConfigurationName {\n\treturn []ConfigurationName{\n\t\tConfigurationNameDefault,\n\t}\n}", "func AllDriversName() []string {\n\t// probing all volume plugins.\n\tbackendDrivers.GetAll()\n\n\tbackendDrivers.Lock()\n\tdefer backendDrivers.Unlock()\n\n\tvar names []string\n\tfor n := range backendDrivers.drivers {\n\t\tnames = append(names, n)\n\t}\n\n\t// sort the names.\n\tsort.Strings(names)\n\n\treturn names\n}", "func (o TriggerBuildOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v TriggerBuild) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func (g *Generator) ConfigLabels() map[string]string {\n\t// We have to make a copy to preserve the privacy of g.image.Config.\n\tcopy := map[string]string{}\n\tfor k, v := range g.image.Config.Labels {\n\t\tcopy[k] = v\n\t}\n\treturn copy\n}", "func ReplicaSetImages(rs appsv1.ReplicaSet) []string {\n\timages := []string{}\n\tfor _, ic := range rs.Spec.Template.Spec.InitContainers {\n\t\timages = append(images, ic.Image)\n\t}\n\tfor _, c := range rs.Spec.Template.Spec.Containers {\n\t\timages = append(images, c.Image)\n\t}\n\treturn images\n}", "func (a *ApplyImpl) Set() []string {\n\treturn a.ApplyOptions.Set\n}", "func (c *environmentClient) List(appName string, opts ...ListEnvOption) (map[string]string, error) {\n\tif appName == \"\" {\n\t\treturn nil, errors.New(\"invalid app name\")\n\t}\n\tcfg := ListEnvOptionDefaults().Extend(opts).toConfig()\n\n\ts, err := c.fetchService(cfg.Namespace, appName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresults := map[string]string{}\n\tfor _, env := range s.Spec.RunLatest.Configuration.RevisionTemplate.Spec.Container.Env {\n\t\tresults[env.Name] = env.Value\n\t}\n\n\treturn results, err\n}", "func (h *cmdlineHandler) toolPaths() map[string]string {\n\t// fmt.Println(\"\\r\\nExtracting Utility Location Information from .config\\r\\n-------------\")\n\tvar u utilities.Utils\n\tvar ls []string = u.ReturnLinesFromFile(h.ConfigFilePath)\n\t//fmt.Println(ls)\t//\t[]\n\n\tvar toolList map[string]string = make(map[string]string)\n\tvar tool string\n\tvar toolpath string\n\tvar i int = 0\n\tfor i < len(ls) {\n\t\t//fmt.Println(ls[i], \" = becomes =>\")\n\t\ttool, toolpath = forl(ls[i])\n\t\ttoolList[tool] = toolpath\n\t\ti++\n\t}\n\th.verifyTools(toolList) //\tExits on Error.\n\treturn toolList\n}", "func essentials(mirror string, v semver.Version) []string {\n\timgs := []string{\n\t\t// use the same order as: `kubeadm config images list`\n\t\tcomponentImage(\"kube-apiserver\", v, mirror),\n\t\tcomponentImage(\"kube-controller-manager\", v, mirror),\n\t\tcomponentImage(\"kube-scheduler\", v, mirror),\n\t\tcomponentImage(\"kube-proxy\", v, mirror),\n\t\tPause(v, mirror),\n\t\tetcd(v, mirror),\n\t\tcoreDNS(v, mirror),\n\t}\n\treturn imgs\n}", "func (c *Config) ProviderConfigsByFullName() map[string]*ProviderConfig {\n\tret := make(map[string]*ProviderConfig, len(c.ProviderConfigs))\n\n\tfor _, pc := range c.ProviderConfigs {\n\t\tret[pc.FullName()] = pc\n\t}\n\n\treturn ret\n}", "func (o ApplicationStatusOperationStateSyncResultSourceKustomizeOutput) Images() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateSyncResultSourceKustomize) []string { return v.Images }).(pulumi.StringArrayOutput)\n}", "func GetMicroservicesConfigurationList(client asfClient.AsfV1alpha1Interface, k8sclient kubernetes.Interface, projectName string, appName string, profile string, branch string, dsQuery *dataselect.DataSelectQuery) (*MicroservicesConfigurationList, error) {\n\t//log.Println(\"Getting list of microservice applications\")\n\n\tvar err, criticalError error\n\tvar nonCriticalErrors []error\n\n\tconfigurations := make([]Configuration, 0)\n\n\tmsEnv, err := msenv.GetMicroservicesEnvironmentByProjectName(client, k8sclient, projectName)\n\tif err != nil {\n\t\tlog.Println(\"error while get microservice envrionment\", err)\n\n\t}\n\n\tnonCriticalErrors, criticalError = errors.HandleError(err)\n\tif criticalError != nil {\n\t\treturn nil, criticalError\n\t}\n\n\tconfigserverUrl := GetConfigServerURLs(*msEnv)\n\n\tif configserverUrl == \"\" {\n\t\tlog.Println(\"faild to get eureka url for project \" + projectName)\n\t\treturn nil, errs.New(\"faild to get eureka url for project \" + projectName)\n\t}\n\n\turl := fmt.Sprintf(\"%s%s/%s/%s\", configserverUrl, appName, profile, branch)\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tc := &http.Client{Transport: tr}\n\tresp, err := c.Get(url)\n\tif err != nil {\n\t\tlog.Println(\"Couldn't load configuration, cannot start. Terminating. Error: \" + err.Error())\n\t\treturn nil, errs.New(\"faild to get configuration for project \" + projectName)\n\n\t}\n\tif resp.StatusCode > 299 || resp.StatusCode < 200 {\n\t\tlog.Println(\"Non-200 rcode of \", resp.StatusCode)\n\n\t\treturn nil, errs.New(\"faild to get configuration for project \" + projectName)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\t//resp.Close = true\n\tif err != nil {\n\t\tlog.Println(\"Couldn't load configuration, cannot start. Terminating. Error: \" + err.Error())\n\t\treturn nil, errs.New(\"faild to get configuration for project \" + projectName)\n\t}\n\n\tconfigMaplist := parseConfiguration(body, appName, profile, branch)\n\n\tfor _, config := range configMaplist {\n\t\tconfigurations = append(configurations, *config)\n\t}\n\n\t//applications = fakeApplications()\n\n\treturn toList(configurations, nonCriticalErrors, dsQuery), nil\n}", "func (c *ConfigContainer) Strings(key string) ([]string, error) {\n\tv, err := c.String(key)\n\tif v == \"\" || err != nil {\n\t\treturn nil, err\n\t}\n\treturn strings.Split(v, \";\"), nil\n}", "func GetImageConfigs() map[ImageID]Config {\n\treturn imageConfigs\n}", "func imageConfig(diffIDs []digest.Digest) ocispec.Image {\n\timg := ocispec.Image{\n\t\tArchitecture: runtime.GOARCH,\n\t\tOS: runtime.GOOS,\n\t}\n\timg.RootFS.Type = \"layers\"\n\timg.RootFS.DiffIDs = diffIDs\n\timg.Config.WorkingDir = \"/\"\n\timg.Config.Env = []string{\"PATH=\" + system.DefaultPathEnv}\n\treturn img\n}", "func (o BucketIntelligentTieringConfigurationFilterOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v BucketIntelligentTieringConfigurationFilter) map[string]string { return v.Tags }).(pulumi.StringMapOutput)\n}", "func (o AnalyticsConfigurationFilterOutput) Tags() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v AnalyticsConfigurationFilter) map[string]string { return v.Tags }).(pulumi.StringMapOutput)\n}", "func AddDI(dimensionInfo string) (map[string]string, error) {\n\tconfig, err := DefaultConf.ConfigFactory.AddByDimensionInfo(dimensionInfo)\n\treturn config, err\n}", "func storeSubstitutionMappingAttributeNamesInSet(ctx context.Context, deploymentID, nodeName string, set map[string]struct{}) error {\n\n\tsubstMapping, err := getDeploymentSubstitutionMapping(ctx, deploymentID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcapabilityToAttrNames := make(map[string][]string)\n\texploreParents := true\n\t// Get the capabilities exposed for this node\n\tfor _, capMapping := range substMapping.Capabilities {\n\t\tif len(capMapping.Mapping) > 1 {\n\t\t\tcapability := capMapping.Mapping[1]\n\t\t\tvar attributeNames []string\n\n\t\t\tif capMapping.Mapping[0] == nodeName {\n\t\t\t\tif capMapping.Attributes != nil {\n\t\t\t\t\tattributeNames := make([]string, len(capMapping.Attributes))\n\t\t\t\t\ti := 0\n\t\t\t\t\tfor name := range capMapping.Attributes {\n\t\t\t\t\t\tattributeNames[i] = name\n\t\t\t\t\t\ti++\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Expose all attributes\n\t\t\t\t\tattributeNames, err = GetNodeCapabilityAttributeNames(ctx, deploymentID, nodeName, capability, exploreParents)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcapabilityToAttrNames[capability] = attributeNames\n\t\t\t}\n\t\t}\n\t}\n\n\t// See http://alien4cloud.github.io/#/documentation/2.0.0/user_guide/services_management.html\n\t// Alien4Cloud is managing capability attributes as node template attributes with\n\t// the format capabilities.<capability name>.<attribute name>\n\tfor capability, names := range capabilityToAttrNames {\n\t\tfor _, attr := range names {\n\t\t\tset[fmt.Sprintf(capabilityFormat, capability, attr)] = struct{}{}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (i *NVDCVEFeedJSON10DefCVEItem) Config() []iface.LogicalTest {\n\treturn i.Configurations.ifaceNodes\n}", "func WithInstancers(i Instancers) Option {\n\treturn func(e *environment) {\n\t\te.instancers = i.Copy()\n\t}\n}", "func flagSet(name string, cfg *CmdConfig) *flag.FlagSet {\n\tflags := flag.NewFlagSet(name, flag.ExitOnError)\n\tflags.StringVar(\n\t\t&cfg.ConfigPath,\n\t\t\"config-path\",\n\t\tsetFromEnvStr(\"CONFIG_PATH\", \"/repo\"),\n\t\t\"Configuration root directory. Should include the '.porter' or 'environment' directory. \"+\n\t\t\t\"Kubernetes object yaml files may be in the directory or in a subdirectory named 'k8s'.\",\n\t)\n\tflags.StringVar(&cfg.ConfigType, \"config-type\", setFromEnvStr(\"CONFIG_TYPE\", \"porter\"), \"Configuration type, \"+\n\t\t\"simple or porter.\")\n\tflags.StringVar(&cfg.Environment, \"environment\", setFromEnvStr(\"ENVIRONMENT\", \"\"), \"Environment of deployment.\")\n\tflags.IntVar(&cfg.MaxConfigMaps, \"max-cm\", setFromEnvInt(\"MAX_CM\", 5), \"Maximum number of configmaps and secret \"+\n\t\t\"objects to keep per app.\")\n\tflags.StringVar(&cfg.Namespace, \"namespace\", setFromEnvStr(\"NAMESPACE\", \"default\"), \"Kubernetes namespace.\")\n\tflags.StringVar(&cfg.Regions, \"regions\", setFromEnvStr(\"REGIONS\", \"\"), \"Regions\"+\n\t\t\"of deployment. (Multiple Space delimited regions allowed)\")\n\tflags.StringVar(&cfg.SHA, \"sha\", setFromEnvStr(\"sha\", \"\"), \"Deployment sha.\")\n\tflags.StringVar(&cfg.VaultAddress, \"vault-addr\", setFromEnvStr(\"VAULT_ADDR\", \"https://vault.loc.adobe.net\"),\n\t\t\"Vault server.\")\n\tflags.StringVar(&cfg.VaultBasePath, \"vault-path\", setFromEnvStr(\"VAULT_PATH\", \"/\"), \"Path in Vault.\")\n\tflags.StringVar(&cfg.VaultToken, \"vault-token\", setFromEnvStr(\"VAULT_TOKEN\", \"\"), \"Vault token.\")\n\tflags.StringVar(&cfg.SecretPathWhiteList, \"secret-path-whitelist\", setFromEnvStr(\"SECRET_PATH_WHITELIST\", \"\"), \"\"+\n\t\t\"Multiple Space delimited secret path whitelist allowed\")\n\tflags.BoolVar(&cfg.Verbose, \"v\", setFromEnvBool(\"VERBOSE\"), \"Verbose log output.\")\n\tflags.IntVar(&cfg.Wait, \"wait\", setFromEnvInt(\"WAIT\", 180), \"Extra time to wait for deployment to complete in \"+\n\t\t\"seconds.\")\n\tflags.StringVar(&cfg.LogMode, \"log-mode\", setFromEnvStr(\"LOG_MODE\", \"inline\"), \"Pod log streaming mode. \"+\n\t\t\"One of 'inline' (print to porter2k8s log), 'file' (write to filesystem, see log-dir option), \"+\n\t\t\"'none' (disable log streaming)\")\n\tflags.StringVar(&cfg.LogDir, \"log-dir\", setFromEnvStr(\"LOG_DIR\", \"logs\"),\n\t\t\"Directory to write pod logs into. (must already exist)\")\n\n\treturn flags\n}", "func ImageListWithFilePath(imageName string, excludes []string, trimDir string, utils piperutils.FileUtils) (map[string]string, error) {\n\n\timageList := map[string]string{}\n\n\tpattern := \"**/Dockerfile*\"\n\n\tmatches, err := utils.Glob(pattern)\n\tif err != nil || len(matches) == 0 {\n\t\treturn imageList, fmt.Errorf(\"failed to retrieve Dockerfiles\")\n\t}\n\n\tfor _, dockerfilePath := range matches {\n\t\t// make sure that the path we have is relative\n\t\t// ToDo: needs rework\n\t\t//dockerfilePath = strings.ReplaceAll(dockerfilePath, cwd, \".\")\n\n\t\tif piperutils.ContainsString(excludes, dockerfilePath) {\n\t\t\tlog.Entry().Infof(\"Discard %v since it is in the exclude list %v\", dockerfilePath, excludes)\n\t\t\tcontinue\n\t\t}\n\n\t\tif dockerfilePath == \"Dockerfile\" {\n\t\t\timageList[imageName] = dockerfilePath\n\t\t} else {\n\t\t\tvar finalName string\n\t\t\tif base := filepath.Base(dockerfilePath); base == \"Dockerfile\" {\n\t\t\t\tsubName := strings.ReplaceAll(filepath.Dir(dockerfilePath), string(filepath.Separator), \"-\")\n\t\t\t\tif len(trimDir) > 0 {\n\t\t\t\t\t// allow to remove trailing sub directories\n\t\t\t\t\t// example .ci/app/Dockerfile\n\t\t\t\t\t// with trimDir = .ci/ imagename would only contain app part.\n\t\t\t\t\tsubName = strings.TrimPrefix(subName, strings.ReplaceAll(trimDir, \"/\", \"-\"))\n\t\t\t\t\t// make sure that subName does not start with a - (e.g. due not configuring trailing slash for trimDir)\n\t\t\t\t\tsubName = strings.TrimPrefix(subName, \"-\")\n\t\t\t\t}\n\t\t\t\tfinalName = fmt.Sprintf(\"%v-%v\", imageName, subName)\n\t\t\t} else {\n\t\t\t\tparts := strings.FieldsFunc(base, func(separator rune) bool {\n\t\t\t\t\treturn separator == []rune(\"-\")[0] || separator == []rune(\"_\")[0]\n\t\t\t\t})\n\t\t\t\tif len(parts) == 1 {\n\t\t\t\t\treturn imageList, fmt.Errorf(\"wrong format of Dockerfile, must be inside a sub-folder or contain a separator\")\n\t\t\t\t}\n\t\t\t\tparts[0] = imageName\n\t\t\t\tfinalName = strings.Join(parts, \"-\")\n\t\t\t}\n\n\t\t\timageList[finalName] = dockerfilePath\n\t\t}\n\t}\n\n\treturn imageList, nil\n}", "func Environ() []string", "func getNameservers(resolvConf []byte) []string {\n\tnameservers := []string{}\n\tfor _, line := range getLines(resolvConf) {\n\t\tns := nsRegexp.FindSubmatch(line)\n\t\tif len(ns) > 0 {\n\t\t\tnameservers = append(nameservers, string(ns[1]))\n\t\t}\n\t}\n\treturn nameservers\n}", "func (s Settings) SelectorsNames() []string {\n\tkeys := make([]string, 0)\n\tfor key := range s.Selectors {\n\t\tkeys = append(keys, key)\n\t}\n\treturn keys\n}", "func getUserConfigurationOptionsSchemaFilenames() map[string]string {\n\treturn map[string]string{\n\t\tUserConfigSchemaEndpoint: EndpointFileName,\n\t\tUserConfigSchemaIntegration: IntegrationFileName,\n\t\tUserConfigSchemaService: ServiceFileName,\n\t}\n}", "func extractImages(v interface{}) []string {\n\tswitch k := v.(type) {\n\tcase *appsv1.Deployment:\n\t\treturn extractImagesFromPodTemplateSpec(k.Spec.Template)\n\tcase *appsv1.StatefulSet:\n\t\treturn extractImagesFromPodTemplateSpec(k.Spec.Template)\n\tcase *appsv1.DaemonSet:\n\t\treturn extractImagesFromPodTemplateSpec(k.Spec.Template)\n\tcase *batchv1.Job:\n\t\treturn extractImagesFromPodTemplateSpec(k.Spec.Template)\n\tcase *batchv1beta1.CronJob:\n\t\treturn extractImagesFromPodTemplateSpec(k.Spec.JobTemplate.Spec.Template)\n\tcase *ocpappsv1.DeploymentConfig:\n\t\treturn extractImagesFromPodTemplateSpec(*k.Spec.Template)\n\t}\n\treturn nil\n}", "func List(c *deis.Client, app string) (api.Config, error) {\n\tu := fmt.Sprintf(\"/v2/apps/%s/config/\", app)\n\n\tres, reqErr := c.Request(\"GET\", u, nil)\n\tif reqErr != nil {\n\t\treturn api.Config{}, reqErr\n\t}\n\tdefer res.Body.Close()\n\n\tconfig := api.Config{}\n\tif err := json.NewDecoder(res.Body).Decode(&config); err != nil {\n\t\treturn api.Config{}, err\n\t}\n\n\treturn config, reqErr\n}", "func RegistryChoices() string {\n\tvar choices []string\n\tfor k := range ParserRegistry {\n\t\tchoices = append(choices, k)\n\t}\n\treturn strings.Join(choices, \"\\n\")\n}", "func (m *Config) GetNameServers() []*net.Endpoint {\n\tif m != nil {\n\t\treturn m.NameServers\n\t}\n\treturn nil\n}", "func (c *Creater) GetConfigmaps() []*components.ConfigMap {\n\n\tvar configMaps []*components.ConfigMap\n\n\thubConfig := components.NewConfigMap(horizonapi.ConfigMapConfig{Namespace: c.blackDuck.Spec.Namespace, Name: util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"config\")})\n\n\thubData := map[string]string{\n\t\t\"RUN_SECRETS_DIR\": \"/tmp/secrets\",\n\t\t\"HUB_VERSION\": c.blackDuck.Spec.Version,\n\t}\n\n\tblackduckServiceData := map[string]string{\n\t\t\"HUB_AUTHENTICATION_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"authentication\"),\n\t\t\"AUTHENTICATION_HOST\": fmt.Sprintf(\"%s:%d\", util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"authentication\"), authenticationPort),\n\t\t\"CLIENT_CERT_CN\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"binaryscanner\"),\n\t\t\"CFSSL\": fmt.Sprintf(\"%s:8888\", util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"cfssl\")),\n\t\t\"HUB_CFSSL_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"cfssl\"),\n\t\t\"BLACKDUCK_CFSSL_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"cfssl\"),\n\t\t\"BLACKDUCK_CFSSL_PORT\": \"8888\",\n\t\t\"HUB_DOC_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"documentation\"),\n\t\t\"HUB_JOBRUNNER_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"jobrunner\"),\n\t\t\"HUB_LOGSTASH_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"logstash\"),\n\t\t\"RABBIT_MQ_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"rabbitmq\"),\n\t\t\"BROKER_URL\": fmt.Sprintf(\"amqps://%s/protecodesc\", util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"rabbitmq\")),\n\t\t\"HUB_REGISTRATION_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"registration\"),\n\t\t\"HUB_SCAN_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"scan\"),\n\t\t\"BLACKDUCK_UPLOAD_CACHE_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"uploadcache\"),\n\t\t\"HUB_UPLOAD_CACHE_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"uploadcache\"),\n\t\t\"HUB_WEBAPP_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"webapp\"),\n\t\t\"HUB_WEBSERVER_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"webserver\"),\n\t\t\"HUB_ZOOKEEPER_HOST\": util.GetResourceName(c.blackDuck.Name, util.BlackDuckName, \"zookeeper\"),\n\t}\n\n\tif c.config.IsOpenshift {\n\t\tblackduckServiceData[\"BLACKDUCK_ORCHESTRATION_TYPE\"] = \"OPENSHIFT\"\n\t} else {\n\t\tblackduckServiceData[\"BLACKDUCK_ORCHESTRATION_TYPE\"] = \"KUBERNETES\"\n\t}\n\n\thubData = util.MergeEnvMaps(blackduckServiceData, hubData)\n\n\tfor _, value := range c.blackDuck.Spec.Environs {\n\t\tvalues := strings.SplitN(value, \":\", 2)\n\t\tif len(values) == 2 {\n\t\t\tmapKey := strings.TrimSpace(values[0])\n\t\t\tmapValue := strings.TrimSpace(values[1])\n\t\t\tif len(mapKey) > 0 && len(mapValue) > 0 {\n\t\t\t\thubData[mapKey] = mapValue\n\t\t\t}\n\t\t}\n\t}\n\n\t// merge default and input environs\n\tenvirons := GetHubKnobs(c.blackDuck.Spec.Version)\n\n\thubData = util.MergeEnvMaps(hubData, environs)\n\n\thubConfig.AddData(hubData)\n\thubConfig.AddLabels(c.GetVersionLabel(\"configmap\"))\n\tconfigMaps = append(configMaps, hubConfig)\n\n\treturn configMaps\n}", "func (tr *TestRunner) ConfigUEs(numUEs int) ([]*cwfprotos.UEConfig, error) {\n\tIMSIs := make([]string, 0, numUEs)\n\tfor i := 0; i < numUEs; i++ {\n\t\timsi := \"\"\n\t\tfor {\n\t\t\timsi = getRandomIMSI()\n\t\t\t_, present := tr.imsis[imsi]\n\t\t\tif !present {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tIMSIs = append(IMSIs, imsi)\n\t}\n\treturn tr.ConfigUEsPerInstance(IMSIs, MockPCRFRemote, MockOCSRemote)\n}", "func (o EciScalingConfigurationOutput) Tags() pulumi.MapOutput {\n\treturn o.ApplyT(func(v *EciScalingConfiguration) pulumi.MapOutput { return v.Tags }).(pulumi.MapOutput)\n}", "func (o *Options) readImageSet(a archive.Archiver) (map[string]string, error) {\n\n\tfilesinArchive := make(map[string]string)\n\n\tfile, err := os.Stat(o.ArchivePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif file.IsDir() {\n\n\t\t// Walk the directory and load the files from the archives\n\t\t// into the map\n\t\tlogrus.Infoln(\"Detected multiple archive files\")\n\t\terr = filepath.Walk(o.ArchivePath, func(path string, info os.FileInfo, err error) error {\n\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"traversing %s: %v\", path, err)\n\t\t\t}\n\t\t\tif info == nil {\n\t\t\t\treturn fmt.Errorf(\"no file info\")\n\t\t\t}\n\n\t\t\textension := filepath.Ext(path)\n\t\t\textension = strings.TrimPrefix(extension, \".\")\n\n\t\t\tif extension == a.String() {\n\t\t\t\tlogrus.Debugf(\"Found archive %s\", path)\n\t\t\t\treturn a.Walk(path, func(f archiver.File) error {\n\t\t\t\t\tfilesinArchive[f.Name()] = path\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\n\t} else {\n\t\t// Walk the archive and load the file names into the map\n\t\terr = a.Walk(o.ArchivePath, func(f archiver.File) error {\n\t\t\tfilesinArchive[f.Name()] = o.ArchivePath\n\t\t\treturn nil\n\t\t})\n\t}\n\n\treturn filesinArchive, err\n}", "func DriverConfigs() map[string]interface{} {\n\treturn ds.config.Driver\n}", "func getGoBuilders() Builders {\n\tdefaultBuilders := []Builder{\n\t\t{OS: \"linux\", Arch: \"amd64\"},\n\t\t{OS: \"linux\", Arch: \"386\"},\n\t\t{OS: \"windows\", Arch: \"amd64\"},\n\t\t{OS: \"windows\", Arch: \"386\"},\n\t\t{OS: \"darwin\", Arch: \"amd64\"},\n\t\t{OS: \"darwin\", Arch: \"386\"},\n\t}\n\tvar bs []*Builder\n\n\tvar clientBuildVars []string\n\tfor envkey, fqn := range map[string]string{\n\t\t\"ALKASIR_CLIENT_VERSION\": \"github.com/alkasir/alkasir/pkg/client.VERSION\",\n\t\t\"ALKASIR_CLIENT_DIFF_URL\": \"github.com/alkasir/alkasir/pkg/client.upgradeDiffsBaseURL\",\n\t\t\"ALKASIR_CLIENT_CENTRAL_URL\": \"github.com/alkasir/alkasir/pkg/client/internal/config.centralAddr\",\n\t\t\"ALKASIR_CLIENT_DEBUG_PUBKEY\": \"github.com/alkasir/alkasir/pkg/debugexport.PublicKey\",\n\t} {\n\t\tenvval := os.Getenv(envkey)\n\t\tif envval != \"\" {\n\t\t\tclientBuildVars = append(clientBuildVars, fmt.Sprintf(\"%s=%s\", fqn, envval))\n\t\t}\n\t}\n\n\tfor _, bb := range defaultBuilders {\n\t\tb := &Builder{\n\t\t\tCmd: \"alkasir-client\",\n\t\t\tOS: bb.OS,\n\t\t\tArch: bb.Arch,\n\t\t\tBrowserBuild: true,\n\t\t\tVars: clientBuildVars,\n\t\t}\n\t\tif b.ShouldBuild() {\n\t\t\tbs = append(bs, b)\n\t\t}\n\t}\n\tfor _, bb := range defaultBuilders {\n\t\tb := &Builder{\n\t\t\tCmd: \"alkasir-admin\",\n\t\t\tOS: bb.OS,\n\t\t\tArch: bb.Arch,\n\t\t}\n\t\tif b.ShouldBuild() {\n\t\t\tbs = append(bs, b)\n\t\t}\n\t}\n\n\tif xcnFlag {\n\t\tfor _, bb := range defaultBuilders {\n\t\t\tif bb.OS == \"linux\" && bb.Arch == \"386\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// ARC is used in the tray icon library which only exists for 64bit.\n\t\t\tif bb.OS == \"darwin\" && bb.Arch == \"386\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tb := &Builder{\n\t\t\t\tCmd: \"alkasir-gui\",\n\t\t\t\tOS: bb.OS,\n\t\t\t\tArch: bb.Arch,\n\t\t\t\tXCN: true,\n\t\t\t\tGUI: true,\n\t\t\t\tBinaryName: \"alkasir\",\n\t\t\t\tFlatArchive: true,\n\t\t\t\tBrowserBuild: true,\n\t\t\t\tVars: clientBuildVars,\n\t\t\t}\n\t\t\tif b.ShouldBuild() {\n\t\t\t\tbs = append(bs, b)\n\t\t\t}\n\t\t}\n\t}\n\n\tcentralBuilder := &Builder{\n\t\tCmd: \"alkasir-central\",\n\t\tOS: \"linux\",\n\t\tArch: \"amd64\",\n\t\tBinaryName: \"alkasir-central\",\n\t}\n\tif centralBuilder.ShouldBuild() {\n\t\tbs = append(bs, centralBuilder)\n\t}\n\treturn bs\n}", "func (o RegistryTaskDockerStepPtrOutput) ImageNames() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *RegistryTaskDockerStep) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ImageNames\n\t}).(pulumi.StringArrayOutput)\n}", "func (d *common) Etag() []any {\n\treturn []any{d.info.Name, d.info.Description, d.info.Ingress, d.info.Egress, d.info.Config}\n}", "func (c *CfgSvc) GetDiscoveredResources() ([]*configservice.ResourceIdentifier, error) {\n\t// List of resource types pulled from\n\t// github.com/aws/aws-sdk-go/models/apis/config/2014-11-12/api-2.json\n\tvar resourceTypes = [...]string{\n\t\t\"AWS::AppStream::DirectoryConfig\",\n\t\t\"AWS::AppStream::Application\",\n\t\t\"AWS::AppFlow::Flow\",\n\t\t\"AWS::ApiGateway::Stage\",\n\t\t\"AWS::ApiGateway::RestApi\",\n\t\t\"AWS::ApiGatewayV2::Stage\",\n\t\t\"AWS::ApiGatewayV2::Api\",\n\t\t\"AWS::Athena::WorkGroup\",\n\t\t\"AWS::Athena::DataCatalog\",\n\t\t\"AWS::CloudFront::Distribution\",\n\t\t\"AWS::CloudFront::StreamingDistribution\",\n\t\t\"AWS::CloudWatch::Alarm\",\n\t\t\"AWS::CloudWatch::MetricStream\",\n\t\t\"AWS::RUM::AppMonitor\",\n\t\t\"AWS::Evidently::Project\",\n\t\t\"AWS::CodeGuruReviewer::RepositoryAssociation\",\n\t\t\"AWS::Connect::PhoneNumber\",\n\t\t\"AWS::CustomerProfiles::Domain\",\n\t\t\"AWS::Detective::Graph\",\n\t\t\"AWS::DynamoDB::Table\",\n\t\t\"AWS::EC2::Host\",\n\t\t\"AWS::EC2::EIP\",\n\t\t\"AWS::EC2::Instance\",\n\t\t\"AWS::EC2::NetworkInterface\",\n\t\t\"AWS::EC2::SecurityGroup\",\n\t\t\"AWS::EC2::NatGateway\",\n\t\t\"AWS::EC2::EgressOnlyInternetGateway\",\n\t\t\"AWS::EC2::EC2Fleet\",\n\t\t\"AWS::EC2::SpotFleet\",\n\t\t\"AWS::EC2::PrefixList\",\n\t\t\"AWS::EC2::FlowLog\",\n\t\t\"AWS::EC2::TransitGateway\",\n\t\t\"AWS::EC2::TransitGatewayAttachment\",\n\t\t\"AWS::EC2::TransitGatewayRouteTable\",\n\t\t\"AWS::EC2::VPCEndpoint\",\n\t\t\"AWS::EC2::VPCEndpointService\",\n\t\t\"AWS::EC2::VPCPeeringConnection\",\n\t\t\"AWS::EC2::RegisteredHAInstance\",\n\t\t\"AWS::EC2::SubnetRouteTableAssociation\",\n\t\t\"AWS::EC2::LaunchTemplate\",\n\t\t\"AWS::EC2::NetworkInsightsAccessScopeAnalysis\",\n\t\t\"AWS::EC2::TrafficMirrorTarget\",\n\t\t\"AWS::EC2::TrafficMirrorSession\",\n\t\t\"AWS::EC2::DHCPOptions\",\n\t\t\"AWS::EC2::IPAM\",\n\t\t\"AWS::EC2::NetworkInsightsPath\",\n\t\t\"AWS::EC2::TrafficMirrorFilter\",\n\t\t\"AWS::EC2::Volume\",\n\t\t\"AWS::ImageBuilder::ImagePipeline\",\n\t\t\"AWS::ImageBuilder::DistributionConfiguration\",\n\t\t\"AWS::ImageBuilder::InfrastructureConfiguration\",\n\t\t\"AWS::ECR::Repository\",\n\t\t\"AWS::ECR::RegistryPolicy\",\n\t\t\"AWS::ECR::PullThroughCacheRule\",\n\t\t\"AWS::ECR::PublicRepository\",\n\t\t\"AWS::ECS::Cluster\",\n\t\t\"AWS::ECS::TaskDefinition\",\n\t\t\"AWS::ECS::Service\",\n\t\t\"AWS::ECS::TaskSet\",\n\t\t\"AWS::EFS::FileSystem\",\n\t\t\"AWS::EFS::AccessPoint\",\n\t\t\"AWS::EKS::Cluster\",\n\t\t\"AWS::EKS::FargateProfile\",\n\t\t\"AWS::EKS::IdentityProviderConfig\",\n\t\t\"AWS::EKS::Addon\",\n\t\t\"AWS::EMR::SecurityConfiguration\",\n\t\t\"AWS::Events::EventBus\",\n\t\t\"AWS::Events::ApiDestination\",\n\t\t\"AWS::Events::Archive\",\n\t\t\"AWS::Events::Endpoint\",\n\t\t\"AWS::Events::Connection\",\n\t\t\"AWS::Events::Rule\",\n\t\t\"AWS::EC2::TrafficMirrorSession\",\n\t\t\"AWS::EventSchemas::RegistryPolicy\",\n\t\t\"AWS::EventSchemas::Discoverer\",\n\t\t\"AWS::EventSchemas::Schema\",\n\t\t\"AWS::Forecast::Dataset\",\n\t\t\"AWS::FraudDetector::Label\",\n\t\t\"AWS::FraudDetector::EntityType\",\n\t\t\"AWS::FraudDetector::Variable\",\n\t\t\"AWS::FraudDetector::Outcome\",\n\t\t\"AWS::GuardDuty::Detector\",\n\t\t\"AWS::GuardDuty::ThreatIntelSet\",\n\t\t\"AWS::GuardDuty::IPSet\",\n\t\t\"AWS::GuardDuty::Filter\",\n\t\t\"AWS::HealthLake::FHIRDatastore\",\n\t\t\"AWS::Cassandra::Keyspace\",\n\t\t\"AWS::IVS::Channel\",\n\t\t\"AWS::IVS::RecordingConfiguration\",\n\t\t\"AWS::IVS::PlaybackKeyPair\",\n\t\t\"AWS::Elasticsearch::Domain\",\n\t\t\"AWS::OpenSearch::Domain\",\n\t\t\"AWS::Elasticsearch::Domain\",\n\t\t\"AWS::Pinpoint::ApplicationSettings\",\n\t\t\"AWS::Pinpoint::Segment\",\n\t\t\"AWS::Pinpoint::App\",\n\t\t\"AWS::Pinpoint::Campaign\",\n\t\t\"AWS::Pinpoint::InAppTemplate\",\n\t\t\"AWS::QLDB::Ledger\",\n\t\t\"AWS::Kinesis::Stream\",\n\t\t\"AWS::Kinesis::StreamConsumer\",\n\t\t\"AWS::KinesisAnalyticsV2::Application\",\n\t\t\"AWS::KinesisFirehose::DeliveryStream\",\n\t\t\"AWS::KinesisVideo::SignalingChannel\",\n\t\t\"AWS::Lex::BotAlias\",\n\t\t\"AWS::Lex::Bot\",\n\t\t\"AWS::Lightsail::Disk\",\n\t\t\"AWS::Lightsail::Certificate\",\n\t\t\"AWS::Lightsail::Bucket\",\n\t\t\"AWS::Lightsail::StaticIp\",\n\t\t\"AWS::LookoutMetrics::Alert\",\n\t\t\"AWS::LookoutVision::Project\",\n\t\t\"AWS::AmazonMQ::Broker\",\n\t\t\"AWS::MSK::Cluster\",\n\t\t\"AWS::Redshift::Cluster\",\n\t\t\"AWS::Redshift::ClusterParameterGroup\",\n\t\t\"AWS::Redshift::ClusterSecurityGroup\",\n\t\t\"AWS::Redshift::ScheduledAction\",\n\t\t\"AWS::Redshift::ClusterSnapshot\",\n\t\t\"AWS::Redshift::ClusterSubnetGroup\",\n\t\t\"AWS::Redshift::EventSubscription\",\n\t\t\"AWS::RDS::DBInstance\",\n\t\t\"AWS::RDS::DBSecurityGroup\",\n\t\t\"AWS::RDS::DBSnapshot\",\n\t\t\"AWS::RDS::DBSubnetGroup\",\n\t\t\"AWS::RDS::EventSubscription\",\n\t\t\"AWS::RDS::DBCluster\",\n\t\t\"AWS::RDS::DBClusterSnapshot\",\n\t\t\"AWS::RDS::GlobalCluster\",\n\t\t\"AWS::Route53::HostedZone\",\n\t\t\"AWS::Route53::HealthCheck\",\n\t\t\"AWS::Route53Resolver::ResolverEndpoint\",\n\t\t\"AWS::Route53Resolver::ResolverRule\",\n\t\t\"AWS::Route53Resolver::ResolverRuleAssociation\",\n\t\t\"AWS::Route53Resolver::FirewallDomainList\",\n\t\t\"AWS::AWS::Route53Resolver::FirewallRuleGroupAssociation\",\n\t\t\"AWS::Route53RecoveryReadiness::Cell\",\n\t\t\"AWS::Route53RecoveryReadiness::ReadinessCheck\",\n\t\t\"AWS::Route53RecoveryReadiness::RecoveryGroup\",\n\t\t\"AWS::Route53RecoveryControl::Cluster\",\n\t\t\"AWS::Route53RecoveryControl::ControlPanel\",\n\t\t\"AWS::Route53RecoveryControl::RoutingControl\",\n\t\t\"AWS::Route53RecoveryControl::SafetyRule\",\n\t\t\"AWS::Route53RecoveryReadiness::ResourceSet\",\n\t\t\"AWS::SageMaker::CodeRepository\",\n\t\t\"AWS::SageMaker::Domain\",\n\t\t\"AWS::SageMaker::AppImageConfig\",\n\t\t\"AWS::SageMaker::Image\",\n\t\t\"AWS::SageMaker::Model\",\n\t\t\"AWS::SageMaker::NotebookInstance\",\n\t\t\"AWS::SageMaker::NotebookInstanceLifecycleConfig\",\n\t\t\"AWS::SageMaker::EndpointConfig\",\n\t\t\"AWS::SageMaker::Workteam\",\n\t\t\"AWS::SES::ConfigurationSet\",\n\t\t\"AWS::SES::ContactList\",\n\t\t\"AWS::SES::Template\",\n\t\t\"AWS::SES::ReceiptFilter\",\n\t\t\"AWS::SES::ReceiptRuleSet\",\n\t\t\"AWS::SNS::Topic\",\n\t\t\"AWS::SQS::Queue\",\n\t\t\"AWS::S3::Bucket\",\n\t\t\"AWS::S3::AccountPublicAccessBlock\",\n\t\t\"AWS::S3::MultiRegionAccessPoint\",\n\t\t\"AWS::S3::StorageLens\",\n\t\t\"AWS::EC2::CustomerGateway\",\n\t\t\"AWS::EC2::InternetGateway\",\n\t\t\"AWS::EC2::NetworkAcl\",\n\t\t\"AWS::EC2::RouteTable\",\n\t\t\"AWS::EC2::Subnet\",\n\t\t\"AWS::EC2::VPC\",\n\t\t\"AWS::EC2::VPNConnection\",\n\t\t\"AWS::EC2::VPNGateway\",\n\t\t\"AWS::NetworkManager::TransitGatewayRegistration\",\n\t\t\"AWS::NetworkManager::Site\",\n\t\t\"AWS::NetworkManager::Device\",\n\t\t\"AWS::NetworkManager::Link\",\n\t\t\"AWS::NetworkManager::GlobalNetwork\",\n\t\t\"AWS::WorkSpaces::ConnectionAlias\",\n\t\t\"AWS::WorkSpaces::Workspace\",\n\t\t\"AWS::Amplify::App\",\n\t\t\"AWS::AppConfig::Application\",\n\t\t\"AWS::AppConfig::Environment\",\n\t\t\"AWS::AppConfig::ConfigurationProfile\",\n\t\t\"AWS::AppConfig::DeploymentStrategy\",\n\t\t\"AWS::AppRunner::VpcConnector\",\n\t\t\"AWS::AppMesh::VirtualNode\",\n\t\t\"AWS::AppMesh::VirtualService\",\n\t\t\"AWS::AppSync::GraphQLApi\",\n\t\t\"AWS::AuditManager::Assessment\",\n\t\t\"AWS::AutoScaling::AutoScalingGroup\",\n\t\t\"AWS::AutoScaling::LaunchConfiguration\",\n\t\t\"AWS::AutoScaling::ScalingPolicy\",\n\t\t\"AWS::AutoScaling::ScheduledAction\",\n\t\t\"AWS::AutoScaling::WarmPool\",\n\t\t\"AWS::Backup::BackupPlan\",\n\t\t\"AWS::Backup::BackupSelection\",\n\t\t\"AWS::Backup::BackupVault\",\n\t\t\"AWS::Backup::RecoveryPoint\",\n\t\t\"AWS::Backup::ReportPlan\",\n\t\t\"AWS::Backup::BackupPlan\",\n\t\t\"AWS::Backup::BackupSelection\",\n\t\t\"AWS::Backup::BackupVault\",\n\t\t\"AWS::Backup::RecoveryPoint\",\n\t\t\"AWS::Batch::JobQueue\",\n\t\t\"AWS::Batch::ComputeEnvironment\",\n\t\t\"AWS::Budgets::BudgetsAction\",\n\t\t\"AWS::ACM::Certificate\",\n\t\t\"AWS::CloudFormation::Stack\",\n\t\t\"AWS::CloudTrail::Trail\",\n\t\t\"AWS::Cloud9::EnvironmentEC2\",\n\t\t\"AWS::ServiceDiscovery::Service\",\n\t\t\"AWS::ServiceDiscovery::PublicDnsNamespace\",\n\t\t\"AWS::ServiceDiscovery::HttpNamespace\",\n\t\t\"AWS::CodeArtifact::Repository\",\n\t\t\"AWS::CodeBuild::Project\",\n\t\t\"AWS::CodeDeploy::Application\",\n\t\t\"AWS::CodeDeploy::DeploymentConfig\",\n\t\t\"AWS::CodeDeploy::DeploymentGroup\",\n\t\t\"AWS::CodePipeline::Pipeline\",\n\t\t\"AWS::Config::ResourceCompliance\",\n\t\t\"AWS::Config::ConformancePackCompliance\",\n\t\t\"AWS::Config::ConfigurationRecorder\",\n\t\t\"AWS::Config::ResourceCompliance\",\n\t\t\"AWS::Config::ConfigurationRecorder\",\n\t\t\"AWS::Config::ConformancePackCompliance\",\n\t\t\"AWS::Config::ConfigurationRecorder\",\n\t\t\"AWS::DMS::EventSubscription\",\n\t\t\"AWS::DMS::ReplicationSubnetGroup\",\n\t\t\"AWS::DMS::ReplicationInstance\",\n\t\t\"AWS::DMS::ReplicationTask\",\n\t\t\"AWS::DMS::Certificate\",\n\t\t\"AWS::DataSync::LocationSMB\",\n\t\t\"AWS::DataSync::LocationFSxLustre\",\n\t\t\"AWS::DataSync::LocationFSxWindows\",\n\t\t\"AWS::DataSync::LocationS3\",\n\t\t\"AWS::DataSync::LocationEFS\",\n\t\t\"AWS::DataSync::LocationNFS\",\n\t\t\"AWS::DataSync::LocationHDFS\",\n\t\t\"AWS::DataSync::LocationObjectStorage\",\n\t\t\"AWS::DataSync::Task\",\n\t\t\"AWS::DeviceFarm::TestGridProject\",\n\t\t\"AWS::DeviceFarm::InstanceProfile\",\n\t\t\"AWS::DeviceFarm::Project\",\n\t\t\"AWS::ElasticBeanstalk::Application\",\n\t\t\"AWS::ElasticBeanstalk::ApplicationVersion\",\n\t\t\"AWS::ElasticBeanstalk::Environment\",\n\t\t\"AWS::FIS::ExperimentTemplate\",\n\t\t\"AWS::GlobalAccelerator::Listener\",\n\t\t\"AWS::GlobalAccelerator::EndpointGroup\",\n\t\t\"AWS::GlobalAccelerator::Accelerator\",\n\t\t\"AWS::Glue::Job\",\n\t\t\"AWS::Glue::Classifier\",\n\t\t\"AWS::Glue::MLTransform\",\n\t\t\"AWS::GroundStation::Config\",\n\t\t\"AWS::IAM::User\",\n\t\t\"AWS::IAM::SAMLProvider\",\n\t\t\"AWS::IAM::ServerCertificate\",\n\t\t\"AWS::IAM::Group\",\n\t\t\"AWS::IAM::Role\",\n\t\t\"AWS::IAM::Policy\",\n\t\t\"AWS::AccessAnalyzer::Analyzer\",\n\t\t\"AWS::IoT::Authorizer\",\n\t\t\"AWS::IoT::SecurityProfile\",\n\t\t\"AWS::IoT::RoleAlias\",\n\t\t\"AWS::IoT::Dimension\",\n\t\t\"AWS::IoT::Policy\",\n\t\t\"AWS::IoT::MitigationAction\",\n\t\t\"AWS::IoT::ScheduledAudit\",\n\t\t\"AWS::IoT::AccountAuditConfiguration\",\n\t\t\"AWS::IoTSiteWise::Gateway\",\n\t\t\"AWS::IoT::CustomMetric\",\n\t\t\"AWS::IoTWireless::ServiceProfile\",\n\t\t\"AWS::IoT::FleetMetric\",\n\t\t\"AWS::IoTAnalytics::Datastore\",\n\t\t\"AWS::IoTAnalytics::Dataset\",\n\t\t\"AWS::IoTAnalytics::Pipeline\",\n\t\t\"AWS::IoTAnalytics::Channel\",\n\t\t\"AWS::IoTEvents::Input\",\n\t\t\"AWS::IoTEvents::DetectorModel\",\n\t\t\"AWS::IoTEvents::AlarmModel\",\n\t\t\"AWS::IoTTwinMaker::Workspace\",\n\t\t\"AWS::IoTTwinMaker::Entity\",\n\t\t\"AWS::IoTTwinMaker::Scene\",\n\t\t\"AWS::IoTSiteWise::Dashboard\",\n\t\t\"AWS::IoTSiteWise::Project\",\n\t\t\"AWS::IoTSiteWise::Portal\",\n\t\t\"AWS::IoTSiteWise::AssetModel\",\n\t\t\"AWS::KMS::Key\",\n\t\t\"AWS::KMS::Alias\",\n\t\t\"AWS::Lambda::Function\",\n\t\t\"AWS::Lambda::Alias\",\n\t\t\"AWS::NetworkFirewall::Firewall\",\n\t\t\"AWS::NetworkFirewall::FirewallPolicy\",\n\t\t\"AWS::NetworkFirewall::RuleGroup\",\n\t\t\"AWS::NetworkFirewall::TLSInspectionConfiguration\",\n\t\t\"AWS:Panorama::Package\",\n\t\t\"AWS::ResilienceHub::ResiliencyPolicy\",\n\t\t\"AWS::RoboMaker::RobotApplicationVersion\",\n\t\t\"AWS::RoboMaker::RobotApplication\",\n\t\t\"AWS::RoboMaker::SimulationApplication\",\n\t\t\"AWS::Signer::SigningProfile\",\n\t\t\"AWS::SecretsManager::Secret\",\n\t\t\"AWS::ServiceCatalog::CloudFormationProduct\",\n\t\t\"AWS::ServiceCatalog::CloudFormationProvisionedProduct\",\n\t\t\"AWS::ServiceCatalog::Portfolio\",\n\t\t\"AWS::Shield::Protection\",\n\t\t\"AWS::ShieldRegional::Protection\",\n\t\t\"AWS::StepFunctions::Activity\",\n\t\t\"AWS::StepFunctions::StateMachine\",\n\t\t\"AWS::SSM::ManagedInstanceInventory\",\n\t\t\"AWS::SSM::PatchCompliance\",\n\t\t\"AWS::SSM::AssociationCompliance\",\n\t\t\"AWS::SSM::FileData\",\n\t\t\"AWS::Transfer::Agreement\",\n\t\t\"AWS::Transfer::Connector\",\n\t\t\"AWS::Transfer::Workflow\",\n\t\t\"AWS::WAF::RateBasedRule\",\n\t\t\"AWS::WAF::Rule\",\n\t\t\"AWS::WAF::WebACL\",\n\t\t\"AWS::WAF::RuleGroup\",\n\t\t\"AWS::WAFRegional::RateBasedRule\",\n\t\t\"AWS::WAFRegional::Rule\",\n\t\t\"AWS::WAFRegional::WebACL\",\n\t\t\"AWS::WAFRegional::RuleGroup\",\n\t\t\"AWS::WAFv2::WebACL\",\n\t\t\"AWS::WAFv2::RuleGroup\",\n\t\t\"AWS::WAFv2::ManagedRuleSet\",\n\t\t\"AWS::WAFv2::IPSet\",\n\t\t\"AWS::WAFv2::RegexPatternSet\",\n\t\t\"AWS::XRay::EncryptionConfig\",\n\t\t\"AWS::ElasticLoadBalancingV2::LoadBalancer\",\n\t\t\"AWS::ElasticLoadBalancingV2::Listener\",\n\t\t\"AWS::ElasticLoadBalancing::LoadBalancer\",\n\t\t\"AWS::ElasticLoadBalancingV2::LoadBalancer\",\n\t\t\"AWS::MediaPackage::PackagingGroup\",\n\t\t\"AWS::MediaPackage::PackagingConfiguration\",\n\t}\n\t// nolint: prealloc\n\tvar res []*configservice.ResourceIdentifier\n\n\tfor _, t := range &resourceTypes {\n\t\tt := t\n\t\tinput := &configservice.ListDiscoveredResourcesInput{\n\t\t\tResourceType: aws.String(t),\n\t\t}\n\n\t\tresult, err := c.Client.ListDiscoveredResources(input)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error ListDiscoveredResources (ResourceType: %s): %v\\n\", t, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tres = append(res, result.ResourceIdentifiers...)\n\n\t\tfor aws.StringValue(result.NextToken) != \"\" {\n\t\t\tinput.NextToken = result.NextToken\n\n\t\t\tresult, err = c.Client.ListDiscoveredResources(input)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Error ListDiscoveredResources (Input: %v): %v\\n\", input, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tres = append(res, result.ResourceIdentifiers...)\n\t\t}\n\t}\n\n\treturn res, nil\n}", "func configureFlags(api *operations.JiliAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func (services *ECSServices) ResourceIdentifiers() []string {\n\treturn services.Services\n}", "func getAugs(c *cli.Context) *iniparamsContainer {\r\n\tj := &jsonControl{}\r\n\tj.Command = c.Command.Names()[0]\r\n\tif j.Command == \"json\" {\r\n\t\terr := json.Unmarshal([]byte(c.String(\"json\")), &j)\r\n\t\tif err != nil {\r\n\t\t\tfmt.Fprintf(os.Stderr, \"Error: JSON Format error. Please confirm inputted JSON again.\\n\")\r\n\t\t\tos.Exit(1)\r\n\t\t}\r\n\t} else {\r\n\t\tobj := map[string]interface{}{}\r\n\t\tfor _, e := range c.FlagNames() {\r\n\t\t\tswitch reflect.TypeOf(c.Generic(e)).String() {\r\n\t\t\tcase \"*flag.stringValue\":\r\n\t\t\t\tobj[e] = c.String(e)\r\n\t\t\tcase \"*flag.intValue\":\r\n\t\t\t\tobj[e] = c.Int(e)\r\n\t\t\tcase \"*flag.boolValue\":\r\n\t\t\t\tobj[e] = c.Bool(e)\r\n\t\t\t}\r\n\t\t}\r\n\t\tj.Options = obj\r\n\t}\r\n\ti := &iniparamsContainer{\r\n\t\t&authParams{},\r\n\t\t&jsonControl{},\r\n\t}\r\n\ti.jsonControl = j\r\n\r\n\tworkdir, err := filepath.Abs(\".\")\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\ti.WorkDir = workdir\r\n\tvar cfgdir string\r\n\tcfgdir = os.Getenv(cfgpathenv)\r\n\tif st, _ := i.jsonControl.Options[\"cfgdirectory\"].(string); len(st) > 0 {\r\n\t\tcfgdir = st\r\n\t}\r\n\tif cfgdir == \"\" {\r\n\t\tcfgdir = workdir\r\n\t}\r\n\ti.CfgDir = cfgdir\r\n\treturn i\r\n}", "func (g *Generator) ConfigVolumes() map[string]struct{} {\n\t// We have to make a copy to preserve the privacy of g.image.Config.\n\tcopy := map[string]struct{}{}\n\tfor k, v := range g.image.Config.Volumes {\n\t\tcopy[k] = v\n\t}\n\treturn copy\n}", "func main() {\n\n\tc := new(bluemix.Config)\n\n\tvar imageTag string\n\t// should same form of registry.ng.bluemix.net/<namespace>/<imagename>\n\tflag.StringVar(&imageTag, \"t\", \"registry.ng.bluemix.net/ibmcloud-go/build\", \"tag\")\n\n\tvar dockerFile string\n\tflag.StringVar(&dockerFile, \"f\", \"Dockerfile\", \"Dockerfile\")\n\n\tvar region string\n\tflag.StringVar(&region, \"region\", \"us-south\", \"region\")\n\n\tflag.Parse()\n\n\tc.Region = region\n\tdirectory := flag.Args()\n\n\tfmt.Println(directory)\n\ttrace.Logger = trace.NewLogger(\"true\")\n\tif len(directory) < 1 || directory[0] == \"\" {\n\n\t\tflag.Usage()\n\t\tfmt.Println(\"Example: ./build -f Dockerfile -t registry.ng.bluemix.net/ibmcloud-go/imagtest .\")\n\t\tos.Exit(1)\n\t}\n\n\tsession, _ := session.New(c)\n\n\tiamAPI, err := iamv1.New(session)\n\tidentityAPI := iamAPI.Identity()\n\tuserInfo, err := identityAPI.UserInfo()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tregistryClient, err := registryv1.New(session)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tnamespaceHeaderStruct := registryv1.NamespaceTargetHeader{\n\t\tAccountID: userInfo.Account.Bss,\n\t}\n\n\tnamespace := strings.Split(imageTag, \"/\")\n\tif len(namespace) != 3 {\n\t\tlog.Fatal(\"Image Tag not correct format\")\n\t}\n\n\tnamespaces, err := registryClient.Namespaces().GetNamespaces(namespaceHeaderStruct)\n\tfound := false\n\tfor _, a := range namespaces {\n\t\tif a == namespace[1] {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\t_, err := registryClient.Namespaces().AddNamespace(namespace[1], namespaceHeaderStruct)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t}\n\n\theaderStruct := registryv1.BuildTargetHeader{\n\t\tAccountID: userInfo.Account.Bss,\n\t}\n\n\trequestStruct := registryv1.DefaultImageBuildRequest()\n\trequestStruct.T = imageTag\n\trequestStruct.Dockerfile = dockerFile\n\n\ttarName, err := tarGzContext(directory[0])\n\tif err != nil {\n\n\t}\n\ttarFile, err := os.Open(tarName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttarReader := bufio.NewReader(tarFile)\n\t//Too much binary output\n\ttrace.Logger = trace.NewLogger(\"false\")\n\n\tfmt.Println(\"Building...\")\n\terr = registryClient.Builds().ImageBuild(*requestStruct, tarReader, headerStruct, os.Stdout)\n\n\timageHeaderStruct := registryv1.ImageTargetHeader{\n\t\tAccountID: userInfo.Account.Bss,\n\t}\n\n\tfmt.Println(\"\\nInspecting Built Image...\")\n\timage, err := registryClient.Images().InspectImage(imageTag, imageHeaderStruct)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tjsonBytes, err := json.MarshalIndent(image, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(string(jsonBytes))\n\n\tfmt.Println(\"\\nScanning Built Image...\")\n\timageVulnerabiliyRequst := registryv1.DefaultImageVulnerabilitiesRequest()\n\timageReport, err := registryClient.Images().ImageVulnerabilities(imageTag, *imageVulnerabiliyRequst, imageHeaderStruct)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tjsonBytes, err = json.MarshalIndent(imageReport, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(string(jsonBytes))\n}", "func ProviderNames(verbose bool) []string {\n\tnames := []string{}\n\n\tfor key, p := range Providers {\n\t\tif enableWhitelist {\n\t\t\t_, ok := whitelist[key]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif enableBlacklist {\n\t\t\t_, ok := blacklist[key]\n\t\t\tif ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif verbose {\n\t\t\ttags := p.Tags()\n\n\t\t\tif len(tags) > 0 {\n\t\t\t\tsort.Strings(tags)\n\t\t\t\tnames = append(names, fmt.Sprintf(\"%s (%s)\", key, strings.Join(tags, \", \")))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tnames = append(names, key)\n\t}\n\n\tsort.Strings(names)\n\treturn names\n}", "func (o GetInfrastructureConfigurationsResultOutput) Arns() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetInfrastructureConfigurationsResult) []string { return v.Arns }).(pulumi.StringArrayOutput)\n}", "func All() []string {\n\treturn superheroes\n}", "func (c ContainerSet) GetAll() []string{\n\tkeys := make([]string, 0, len(c.containerMap))\n\tfor k := range c.containerMap {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}", "func ImageRepositoryToSelectableFields(ir *api.ImageRepository) labels.Set {\n\treturn labels.Set{\n\t\t\"name\": ir.Name,\n\t\t\"dockerImageRepository\": ir.DockerImageRepository,\n\t\t\"status.dockerImageRepository\": ir.Status.DockerImageRepository,\n\t}\n}", "func DockerComposeServicesExcluding(excluded []string) []string {\n\tservices := getDockerComposeMap(\"docker-compose.yml\")\n\tif file := os.Getenv(\"LC_BASE_COMPOSE_FILE\"); len(file) > 0 {\n\t\tfor k, v := range getDockerComposeMap(file) {\n\t\t\tif _, ok := services[k]; !ok {\n\t\t\t\tservices[k] = v\n\t\t\t}\n\t\t}\n\t}\n\tvar filtered []string\n\tfor service, image := range services {\n\t\tvar exclude bool\n\t\tfor _, i := range excluded {\n\t\t\tif image.Image == i {\n\t\t\t\texclude = true\n\t\t\t}\n\t\t}\n\t\tif !exclude {\n\t\t\tfiltered = append(filtered, service)\n\t\t}\n\t}\n\treturn filtered\n}", "func readVsphereConfCredentialsInMultiVcSetup(cfg string) (e2eTestConfig, error) {\n\tvar config e2eTestConfig\n\n\tvirtualCenters := make([]string, 0)\n\tuserList := make([]string, 0)\n\tpasswordList := make([]string, 0)\n\tportList := make([]string, 0)\n\tdataCenterList := make([]string, 0)\n\n\tkey, value := \"\", \"\"\n\tlines := strings.Split(cfg, \"\\n\")\n\tfor index, line := range lines {\n\t\tif index == 0 {\n\t\t\t// Skip [Global].\n\t\t\tcontinue\n\t\t}\n\t\twords := strings.Split(line, \" = \")\n\t\tif strings.Contains(words[0], \"topology-categories=\") {\n\t\t\twords = strings.Split(line, \"=\")\n\t\t}\n\n\t\tif len(words) == 1 {\n\t\t\tif strings.Contains(words[0], \"Snapshot\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.Contains(words[0], \"Labels\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twords = strings.Split(line, \" \")\n\t\t\tif strings.Contains(words[0], \"VirtualCenter\") {\n\t\t\t\tvalue = words[1]\n\t\t\t\tvalue = strings.TrimSuffix(value, \"]\")\n\t\t\t\tvalue = trimQuotes(value)\n\t\t\t\tconfig.Global.VCenterHostname = value\n\t\t\t\tvirtualCenters = append(virtualCenters, value)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tkey = words[0]\n\t\tvalue = trimQuotes(words[1])\n\t\tvar strconvErr error\n\t\tswitch key {\n\t\tcase \"insecure-flag\":\n\t\t\tif strings.Contains(value, \"true\") {\n\t\t\t\tconfig.Global.InsecureFlag = true\n\t\t\t} else {\n\t\t\t\tconfig.Global.InsecureFlag = false\n\t\t\t}\n\t\tcase \"cluster-id\":\n\t\t\tconfig.Global.ClusterID = value\n\t\tcase \"cluster-distribution\":\n\t\t\tconfig.Global.ClusterDistribution = value\n\t\tcase \"user\":\n\t\t\tconfig.Global.User = value\n\t\t\tuserList = append(userList, value)\n\t\tcase \"password\":\n\t\t\tconfig.Global.Password = value\n\t\t\tpasswordList = append(passwordList, value)\n\t\tcase \"datacenters\":\n\t\t\tconfig.Global.Datacenters = value\n\t\t\tdataCenterList = append(dataCenterList, value)\n\t\tcase \"port\":\n\t\t\tconfig.Global.VCenterPort = value\n\t\t\tportList = append(portList, value)\n\t\tcase \"cnsregistervolumes-cleanup-intervalinmin\":\n\t\t\tconfig.Global.CnsRegisterVolumesCleanupIntervalInMin, strconvErr = strconv.Atoi(value)\n\t\t\tif strconvErr != nil {\n\t\t\t\treturn config, fmt.Errorf(\"invalid value for cnsregistervolumes-cleanup-intervalinmin: %s\", value)\n\t\t\t}\n\t\tcase \"topology-categories\":\n\t\t\tconfig.Labels.TopologyCategories = value\n\t\tcase \"global-max-snapshots-per-block-volume\":\n\t\t\tconfig.Snapshot.GlobalMaxSnapshotsPerBlockVolume, strconvErr = strconv.Atoi(value)\n\t\t\tif strconvErr != nil {\n\t\t\t\treturn config, fmt.Errorf(\"invalid value for global-max-snapshots-per-block-volume: %s\", value)\n\t\t\t}\n\t\tcase \"csi-fetch-preferred-datastores-intervalinmin\":\n\t\t\tconfig.Global.CSIFetchPreferredDatastoresIntervalInMin, strconvErr = strconv.Atoi(value)\n\t\t\tif strconvErr != nil {\n\t\t\t\treturn config, fmt.Errorf(\"invalid value for csi-fetch-preferred-datastores-intervalinmin: %s\", value)\n\t\t\t}\n\t\tcase \"targetvSANFileShareDatastoreURLs\":\n\t\t\tconfig.Global.TargetvSANFileShareDatastoreURLs = value\n\t\tcase \"query-limit\":\n\t\t\tconfig.Global.QueryLimit, strconvErr = strconv.Atoi(value)\n\t\t\tif strconvErr != nil {\n\t\t\t\treturn config, fmt.Errorf(\"invalid value for query-limit: %s\", value)\n\t\t\t}\n\t\tcase \"list-volume-threshold\":\n\t\t\tconfig.Global.ListVolumeThreshold, strconvErr = strconv.Atoi(value)\n\t\t\tif strconvErr != nil {\n\t\t\t\treturn config, fmt.Errorf(\"invalid value for list-volume-threshold: %s\", value)\n\t\t\t}\n\t\tdefault:\n\t\t\treturn config, fmt.Errorf(\"unknown key %s in the input string\", key)\n\t\t}\n\t}\n\n\tconfig.Global.VCenterHostname = strings.Join(virtualCenters, \",\")\n\tconfig.Global.User = strings.Join(userList, \",\")\n\tconfig.Global.Password = strings.Join(passwordList, \",\")\n\tconfig.Global.VCenterPort = strings.Join(portList, \",\")\n\tconfig.Global.Datacenters = strings.Join(dataCenterList, \",\")\n\n\treturn config, nil\n}", "func (o LookupExperienceResultOutput) Configurations() GetExperienceConfigurationArrayOutput {\n\treturn o.ApplyT(func(v LookupExperienceResult) []GetExperienceConfiguration { return v.Configurations }).(GetExperienceConfigurationArrayOutput)\n}", "func ScrubConfig(target interface{}, values ...string) string {\n\tconf := fmt.Sprintf(\"Config: %+v\", target)\n\tfor _, value := range values {\n\t\tconf = strings.Replace(conf, value, \"<Filtered>\", -1)\n\t}\n\treturn conf\n}", "func (sc *SampleConfig) IntegrationNames() []string {\n\tnames := []string{}\n\tfor _, integration := range sc.Integrations {\n\t\tnames = append(names, integration.Name)\n\t}\n\n\treturn names\n}" ]
[ "0.51636654", "0.50098467", "0.5007201", "0.4983479", "0.49117845", "0.48418006", "0.47519144", "0.47423694", "0.46875143", "0.4671297", "0.46617126", "0.4644778", "0.46275565", "0.45914572", "0.45488852", "0.4517872", "0.45048082", "0.4491206", "0.44843468", "0.44672272", "0.4466367", "0.44543934", "0.4453371", "0.44500366", "0.44494563", "0.4448642", "0.4444354", "0.44411477", "0.44404435", "0.4437712", "0.4435838", "0.44318444", "0.4423228", "0.44064787", "0.43691698", "0.4366322", "0.43599692", "0.43573377", "0.4348002", "0.43449453", "0.43374616", "0.43338516", "0.4313214", "0.4300586", "0.42940593", "0.42933083", "0.42925754", "0.42886275", "0.42847148", "0.42843032", "0.42810908", "0.42761716", "0.42706686", "0.4266193", "0.4265467", "0.4261017", "0.42604792", "0.4256683", "0.42535907", "0.42527384", "0.42503682", "0.42495584", "0.4247623", "0.4244414", "0.42395365", "0.42377967", "0.42296618", "0.42267728", "0.42206252", "0.42206198", "0.42196047", "0.4218336", "0.42138004", "0.42120305", "0.4210488", "0.420692", "0.41929063", "0.41882414", "0.41793415", "0.41734692", "0.41654816", "0.416478", "0.41576523", "0.41501626", "0.41496068", "0.41492227", "0.4146549", "0.4144931", "0.4143902", "0.41430357", "0.4142319", "0.41421142", "0.41414058", "0.41397408", "0.41388342", "0.41352907", "0.41352522", "0.41349855", "0.4131987", "0.41295934" ]
0.5689205
0
wsMessage handles browser requests to /msg/
func wsMessage(w http.ResponseWriter, r *http.Request) { // Get session, continue only if authenticated sok, vok := checkLogin(r, cfgMap["session name"], "user") if !sok || !vok { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } cc := make(chan bool) // upgrade to websocket c, err := upgrader.Upgrade(w, r, nil) defer c.Close() if err != nil { log.Println("upgrade:", err) return } // handle websocket incoming browser messages go func(c *websocket.Conn) { for { _, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) cc <- true return } log.Printf("recv: %s", message) } }(c) // send websocket message to browser for { select { case <-cc: return default: response := []byte(<-wsChan) // mesage type = 1 err = c.WriteMessage(1, response) if err != nil { log.Println("ws write err:", err) break } time.Sleep(time.Second) } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (w *BaseWebsocketClient) OnWsMessage(payload []byte, isBinary bool) {}", "func handleMessage(msg *game.InMessage, ws *websocket.Conn, board *game.Board) {\n\tfmt.Println(\"Message Got: \", msg)\n\n}", "func (ctx *Context) MessageHandler(w http.ResponseWriter, r *http.Request) {\n\t//get the current user\n\tss := &SessionState{}\n\t_, err := sessions.GetState(r, ctx.SessionKey, ctx.SessionStore, ss)\n\tif err != nil {\n\t\thttp.Error(w, \"error getting current session : \"+err.Error(), http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tif r.Method == \"POST\" {\n\n\t\td := json.NewDecoder(r.Body)\n\t\tnm := &messages.NewMessage{}\n\t\tif err := d.Decode(nm); err != nil {\n\t\t\thttp.Error(w, \"invalid JSON\", http.StatusBadRequest)\n\t\t}\n\n\t\t//Validate the models.NewMessage\n\t\terr := nm.Validate()\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"invalid message: \"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tm, err := ctx.MessageStore.InsertMessage(ss.User.ID, nm)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error inserting message: \"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\t//Notify client of new message through websocket\n\t\tn, err := m.ToNewMessageEvent()\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error creating message event: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tctx.Notifier.Notify(n)\n\n\t\tw.Header().Add(headerContentType, contentTypeJSONUTF8)\n\t\tencoder := json.NewEncoder(w)\n\t\tencoder.Encode(m)\n\n\t}\n}", "func message(w http.ResponseWriter, r *http.Request) {\n\tvar rBody request\n\n\tif err := json.NewDecoder(r.Body).Decode(&rBody); err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to decode message\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tc, err := models.GetConnectionWithRecipients(rBody.ConnectionID)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to get connection\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdbMsg := &models.Message{\n\t\tConnectionID: rBody.ConnectionID,\n\t\tMessage: rBody.Text,\n\t\tSourceUser: *c.SourceUser,\n\t\tSourceUserID: c.SourceUserID,\n\t\tDestinationUserID: c.DestinationUserID,\n\t\tChannel: rBody.Channel,\n\t}\n\n\tif err := dbMsg.Save(); err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to save message. \", err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tcMsg := models.ChannelMessage{\n\t\tID: int(dbMsg.ID),\n\t\tCreatedAt: dbMsg.CreatedAt,\n\t\tMessage: dbMsg.Message,\n\t\tReadBy: dbMsg.ReadBy,\n\t\tUser: rBody.User,\n\t}\n\n\tpayload := pubMessage{\n\t\t// populate embedded struct (promoted fields)\n\t\tdefaultProperties: defaultProperties{\n\t\t\tChannel: rBody.Channel,\n\t\t\tType: rBody.Type,\n\t\t\tSubType: rBody.SubType,\n\t\t},\n\t\tChannelMessage: cMsg,\n\t}\n\n\t// prep for ws\n\tbytes, err := json.Marshal(payload)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to marshal chat message\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpubMessage := hub.PublishMessage{\n\t\tTopic: rBody.Channel,\n\t\tPayload: bytes,\n\t}\n\n\tbroker.Hub.Publish(pubMessage)\n\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func processMessage(ws *Conn, msg []byte) {\n\n\tr := ws.r\n\n\t// Parse request\n\tvar req *reqres.Req\n\tvar err error\n\tif req, err = ParseReq(msg); err != nil {\n\t\tres := NewResponse_Err(req,\n\t\t\terrors.New_AppErr(err, \"Cannot unmarshal request\"))\n\t\tws.chanOut <- res\n\t\treturn\n\t}\n\n\t/* NOTE: Relax this requirement\n\t // Validate request\n\t if req.Id == 0 {\n\t err = fmt.Errorf(\"Request ID is missing\")\n\t res := NewResponse_Err(req,\n\t errors.New_AppErr(err, \"Request must have _reqId\"))\n\t ws.chanOut <- res\n\t return\n\t }\n\t*/\n\n\t// HTTP request\n\treq.HttpReq = r\n\n\t// Catch panic\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tstack := util.Stack()\n\t\t\tres := NewResponse_Err(req,\n\t\t\t\terrors.New_AppErr(fmt.Errorf(\"%v\", err),\n\t\t\t\t\t\"Application error, support notified\"))\n\t\t\tws.chanOut <- res\n\n\t\t\t// Report panic: err, url, params, stack\n\t\t\t_onPanic(\n\t\t\t\tfmt.Sprintf(\"Error processing WS request: %v\", err),\n\t\t\t\tfmt.Sprintf(\"%v : %v : %v\", r.Host, ws.router.URL, req.Op),\n\t\t\t\t\"Params\", fmt.Sprint(req.Params),\n\t\t\t\t\"Session\", fmt.Sprint(req.GetSessionValues()),\n\t\t\t\t\"Stack\", stack)\n\t\t}\n\t}()\n\n\t// Find proc for given op\n\tvar proc func(*reqres.Req) (interface{}, error)\n\tvar ok bool\n\n\t// First look in core procs in this package\n\t// Then look in app supplied procs\n\tif proc, ok = _coreProcs[req.Op]; !ok {\n\t\tif proc, ok = ws.router.Procs[req.Op]; !ok {\n\t\t\tres := NewResponse_Err(req,\n\t\t\t\terrors.New_NotFound(req.Op, \"No matching op processor found\"))\n\t\t\tws.chanOut <- res\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Call proc\n\tvar data interface{}\n\tdata, err = proc(req)\n\n\t// Respond\n\tvar res []byte\n\tif err == nil {\n\t\tres = NewResponse(req, data)\n\t} else {\n\t\t// Error can be either:\n\t\t// Request error: prepended with \"ERR:\" to be shown to user\n\t\t// Application error: all programming logic error\n\t\tres = NewResponse_Err(req, errors.New(err))\n\t}\n\tws.chanOut <- res\n}", "func (tv *TV) MessageHandler() (err error) {\n\tdefer func() {\n\t\ttv.resMutex.Lock()\n\t\tfor _, ch := range tv.res {\n\t\t\tclose(ch)\n\t\t}\n\t\ttv.res = nil\n\t\ttv.resMutex.Unlock()\n\t}()\n\n\tfor {\n\t\tmt, p, err := tv.ws.ReadMessage()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif mt != websocket.TextMessage {\n\t\t\tcontinue\n\t\t}\n\n\t\tmsg := Message{}\n\n\t\terr = json.Unmarshal(p, &msg)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\ttv.resMutex.Lock()\n\t\tch := tv.res[msg.ID]\n\t\ttv.resMutex.Unlock()\n\n\t\tch <- msg\n\t}\n}", "func (h *Handler) handleMessage(c websocket.Connection, requestId string, req request.CreateMessage) {\n\t// Validate the request\n\tif err := h.Validator.Struct(req); err != nil {\n\t\tc.Emit(\"error\", WsResponse{\n\t\t\tRequestId: requestId,\n\t\t\tBody: h.Validator.FormatError(err),\n\t\t})\n\t\treturn\n\t}\n\n\t// Create the message\n\tres := h.CreateMessageInteractor.Call(req)\n\n\tvar successResponse response.CreateMessage\n\t// If the response code is not the correct one return the error\n\tif res.GetCode() != successResponse.GetCode() {\n\t\tc.Emit(\"error\", WsResponse{\n\t\t\tRequestId: requestId,\n\t\t\tBody: res,\n\t\t})\n\t}\n\n\t// Send a message to confirm that the message has been sent\n\tc.Emit(\"sent\", WsResponse{\n\t\tRequestId: requestId,\n\t\tBody: res,\n\t})\n}", "func (s *Server) OnMessage(msg *Message, sess *Session) {\n\tmsg.SetHeader(proto.Sender, sess.ID)\n\tmsg.SetHeader(proto.Host, s.ServerAddress.Address)\n\tif msg.Id() == \"\" {\n\t\tmsg.SetId(uuid())\n\t}\n\tif msg.Cmd() != proto.Heartbeat {\n\t\t//log.Printf(msg.String())\n\t}\n\n\thandleUrlMessage(msg)\n\n\tcmd := msg.Cmd()\n\thandler, ok := s.handlerTable[cmd]\n\tif ok {\n\t\thandler(s, msg, sess)\n\t\treturn\n\t}\n\tres := NewMessageStatus(400, \"Bad format: command(%s) not support\", cmd)\n\tsess.WriteMessage(res)\n}", "func (s *API) ReceiveMessage(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"ReceiveMessage\")\n\tw.WriteHeader(http.StatusNotImplemented)\n}", "func (wc *WebClient) SendMessage(message string) {\n\twc.logger.Debug(\"WebClient.SendMessage() - %s\", message)\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\terr := wc.conn.Write(ctx, ws.MessageText, []byte(message))\n\tif err != nil {\n\t\twc.logger.Error(\"Error encountered writing to webclient: %v\", err)\n\t}\n}", "func ws_SendMsg(ws *websocket.Conn, send_channel SendChannel) {\n\tfor {\n\t\tselect {\n\t\tcase send_msg := <-send_channel.containers:\n\t\t\tlog.Printf(\"[%s] containers sendMessage= \", __FILE__, send_msg)\n\t\t\twebsocket.JSON.Send(ws, send_msg)\n\t\tcase send_msg := <-send_channel.updateinfo:\n\t\t\tlog.Printf(\"[%s] update sendMessage=\", __FILE__, send_msg)\n\t\t}\n\t}\n}", "func (s *Serve) HandleMessage(msg *nsq.Message) (err error) {\n\tif string(msg.Body) == \"TOBEFAILED\" {\n\t\treturn errors.New(\"fail this message\")\n\t}\n\n\tvar m url.Values\n\terr = json.Unmarshal(msg.Body, &m)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tresC <- m\n\treturn\n}", "func (api *WebSocketAPI) DispatchMessageEvent(data []byte) error {\n\tif err := api.Battle.DispatchMessageEvent(data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (bot *Hitbot) MessageHandler() {\n\tfor {\n\t\t_, p, err := bot.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t//log.Printf(\"Message: %v\", string(p)) //debug info\n\t\tif string(p[:3]) == \"2::\" {\n\t\t\tbot.conn.WriteMessage(websocket.TextMessage, []byte(\"2::\"))\n\t\t\t//log.Print(\"Ping!\")\n\t\t\tcontinue\n\t\t} else if string(p[:3]) == \"1::\" {\n\t\t\tlog.Print(\"Connection successful!\")\n\t\t\tfor _, channel := range bot.channels {\n\t\t\t\tbot.joinChannel(channel)\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if string(p[:4]) == \"5:::\" {\n\t\t\tbot.parseMessage(p[4:])\n\t\t}\n\t}\n}", "func (q *Q) WebNewMessage(response http.ResponseWriter, request *http.Request) {\n\tvars := mux.Vars(request)\n\tmsg := q.Message(vars[\"topic\"])\n\tif msg != nil {\n\t\t// woot woot! message found\n\t\tresponse.WriteHeader(http.StatusOK)\n\t\tfmt.Fprintf(response, msg.String())\n\t} else {\n\t\t// boo, couldn't find a message\n\t\tresponse.WriteHeader(http.StatusNotFound)\n\t\tfmt.Fprintf(response, \"{}\")\n\t}\n}", "func (srv *Server) handleMessage(msg *Message) error {\n\tswitch msg.msgType {\n\tcase MsgSignalBinary:\n\t\tfallthrough\n\tcase MsgSignalUtf8:\n\t\tfallthrough\n\tcase MsgSignalUtf16:\n\t\tsrv.handleSignal(msg)\n\n\tcase MsgRequestBinary:\n\t\tfallthrough\n\tcase MsgRequestUtf8:\n\t\tfallthrough\n\tcase MsgRequestUtf16:\n\t\tsrv.handleRequest(msg)\n\n\tcase MsgRestoreSession:\n\t\treturn srv.handleSessionRestore(msg)\n\tcase MsgCloseSession:\n\t\treturn srv.handleSessionClosure(msg)\n\t}\n\treturn nil\n}", "func (srv *Server) handleMessage(msg *Message) error {\n\tswitch msg.msgType {\n\tcase MsgSignalBinary:\n\t\tfallthrough\n\tcase MsgSignalUtf8:\n\t\tfallthrough\n\tcase MsgSignalUtf16:\n\t\tsrv.handleSignal(msg)\n\n\tcase MsgRequestBinary:\n\t\tfallthrough\n\tcase MsgRequestUtf8:\n\t\tfallthrough\n\tcase MsgRequestUtf16:\n\t\tsrv.handleRequest(msg)\n\n\tcase MsgRestoreSession:\n\t\treturn srv.handleSessionRestore(msg)\n\tcase MsgCloseSession:\n\t\treturn srv.handleSessionClosure(msg)\n\t}\n\treturn nil\n}", "func GetMessageWS(c *gin.Context) {\n\thandler := websocket.Handler(func(conn *websocket.Conn) {\n\n\t\tfor _, row := range database.LocalDB {\n\t\t\tconn.Write([]byte(row))\n\t\t}\n\n\t\tio.Copy(conn, conn)\n\n\t})\n\n\thandler.ServeHTTP(c.Writer, c.Request)\n}", "func wsHandler(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tchannel := params[\"channel\"]\n\tclientServer := params[\"clientServer\"]\n\n\tvar fromServer bool\n\n\tswitch clientServer {\n\tcase \"client\":\n\t\tfromServer = false\n\tcase \"server\":\n\t\tfromServer = true\n\tdefault:\n\t\thttp.Error(w, \"bad path not /x/client or /x/server\", http.StatusNotFound)\n\t\treturn\n\n\t}\n\n\tupgraderMutex.Lock()\n\tc, err := upgrader.Upgrade(w, r, nil)\n\tupgraderMutex.Unlock()\n\tcheck(err)\n\tdefer func() {\n\t\tcheck(c.Close())\n\t}()\n\n\tconnections[key{channel, fromServer}] = connection{myconn: c, paired: nil}\n\n\tglog.Warningln(\"connection from \", c.RemoteAddr())\n\n\tfor {\n\t\tmtype, msg, err := c.ReadMessage()\n\t\tif websocket.IsCloseError(err) {\n\t\t\tglog.Warningln(\"remote conn closed, dropping off\")\n\t\t\treturn\n\t\t}\n\t\tcheck(err)\n\n\t\tmessages <- message{channel, mtype, msg, fromServer, c}\n\t}\n}", "func WebsocketMessengerHandler(w http.ResponseWriter, r *http.Request) {\n\tpagestate := r.FormValue(\"id\")\n\n\tif !page.HasPage(pagestate) {\n\t\t// The page manager has no record of the pagestate, so either it is expired or never existed\n\t\treturn // TODO: return error?\n\t}\n\n\t// Inject the pagestate as the client ID so the next handler down can read it\n\tctx := context.WithValue(r.Context(), goradd.WebSocketContext, pagestate)\n\tmessageServer.Messenger.(*ws.WsMessenger).WebSocketHandler().ServeHTTP(w, r.WithContext(ctx))\n}", "func (em *EventManager) handleMessage(i interface{}) error {\n\tvar err error = nil\n\n\tm := i.(Message)\n\n\tlog.Printf(\"Processing message\")\n\n\t// TODO: process incoming message\n\tres, err := em.wc.HandleMessage(m.Text())\n\tif err != nil {\n\t\tlog.Printf(\"Error processing message\")\n\t\treturn err\n\t}\n\n\t// TODO: act on message\n\tswitch res.Intent {\n\tcase analysis.IntentCreateEvent:\n \n\n\tcase analysis.IntentCancelEvent:\n // Check owner, when and where match\n\n // Delete event\n\n\tcase analysis.IntentFindEvents:\n // Find events based on when / where filters\n\n\tcase analysis.IntentAttending:\n // Set attending flag for a given event\n\n\tcase analysis.IntentNotAttending:\n // Set not attending flag for a given event\n\n case analysis.IntentArrived:\n // Set arrived flag for a given event\n\n\t}\n\n\tif res.Response != \"\" {\n\t\tlog.Printf(\"Sending reply\")\n\n\t\t// Generate reply\n\t\treply := m.Reply(res.Response)\n\n\t\t// Locate matching client\n\t\tc, ok := em.clients[m.Connector()]\n\t\tif !ok {\n\t\t\tlog.Printf(\"Invalid connector %s for response\", m.Connector())\n\t\t\treturn err\n\t\t}\n\n\t\t// Send reply\n\t\tc.Send(reply)\n\t}\n\n\treturn err\n}", "func HandleMessage(mType int, msg []byte, conn *websocket.Conn, isFirst bool) {\n\tvar workSpace *Command\n\tvar err error\n\tif isFirst {\n\t\tpwd := GetPwd(\"test\")\n\t\tvar env []string\n\t\tentrypoint := make([]string, 1) // Set `/go` as default entrypoint\n\t\tentrypoint[0] = \"/go\"\n\t\tusername := \"test\"\n\t\tworkSpace = &Command{\n\t\t\tCommand: string(msg),\n\t\t\tEntrypoint: entrypoint,\n\t\t\tPWD: pwd,\n\t\t\tENV: env,\n\t\t\tUserName: username,\n\t\t}\n\t}\n\n\t// Send message\n\tif isFirst {\n\t\terr = conn.WriteJSON(*workSpace)\n\t} else {\n\t\terr = conn.WriteMessage(mType, msg)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Can not write message to connection\")\n\t\treturn\n\t}\n}", "func handleMessages() {\n\tvar msg node.Message\n\tvar jsonMessage Message\n\tfor {\n\t\tmsg = <-uiChannel\n\t\tjsonMessage.Message = msg.Content\n\t\tjsonMessage.Peer = msg.Peer\n\t\tfor client := range clients {\n\t\t\t// Send message to web application\n\t\t\terr := client.WriteJSON(jsonMessage)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t\tclient.Close()\n\t\t\t\tdelete(clients, client)\n\t\t\t}\n\t\t}\n\t}\n}", "func (nc *NetClient) handleMessage(m *arbor.ProtocolMessage) {\n\tswitch m.Type {\n\tcase arbor.NewMessageType:\n\t\tif !nc.Archive.Has(m.UUID) {\n\t\t\tif nc.receiveHandler != nil {\n\t\t\t\tnc.receiveHandler(m.ChatMessage)\n\t\t\t\t// ask Notifier to handle the message\n\t\t\t\tnc.Notifier.Handle(nc, m.ChatMessage)\n\t\t\t}\n\t\t\tif m.Parent != \"\" && !nc.Archive.Has(m.Parent) {\n\t\t\t\tnc.Query(m.Parent)\n\t\t\t}\n\t\t}\n\tcase arbor.WelcomeType:\n\t\tif !nc.Has(m.Root) {\n\t\t\tnc.Query(m.Root)\n\t\t}\n\t\tfor _, recent := range m.Recent {\n\t\t\tif !nc.Has(recent) {\n\t\t\t\tnc.Query(recent)\n\t\t\t}\n\t\t}\n\tcase arbor.MetaType:\n\t\tnc.HandleMeta(m.Meta)\n\t}\n}", "func HandleMessage(w http.ResponseWriter, r *http.Request) {\n\tif token == \"\" {\n\t\tlog.Printf(\"no bot token available\")\n\t\treturn\n\t}\n\n\tbot, err := tgbotapi.NewBotAPI(token)\n\tif err != nil {\n\t\tlog.Printf(\"could not create telegram bot: %v\\n\", err)\n\t\treturn\n\t}\n\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Printf(\"could not read request: %v\\n\", err)\n\t\treturn\n\t}\n\n\tvar update tgbotapi.Update\n\n\tif err := json.Unmarshal(data, &update); err != nil {\n\t\tlog.Printf(\"could not parse request: %v\\n\", err)\n\t\treturn\n\t}\n\n\tcid := update.Message.Chat.ID\n\n\tswitch {\n\tcase update.Message.Voice != nil:\n\t\thandleVoiceMessage(bot, cid, update.Message.Voice)\n\tcase update.Message.Text != \"\":\n\t\thandleTextMessage(bot, cid, update.Message.Text)\n\t}\n}", "func handleWebsocketEndpoint(w http.ResponseWriter, r *http.Request) {\n\tconn, _ := upgrader.Upgrade(w, r, nil) // error ignored for sake of simplicity\n\tfor {\n\t\t// Read message from client\n\t\tmsgType, msg, err := conn.ReadMessage()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Print the message to the console\n\t\tfmt.Printf(\"%s sent: %s\\n\", conn.RemoteAddr(), string(msg))\n\n\t\t// Write message back to client\n\t\tif err = conn.WriteMessage(msgType, msg); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n}", "func wsReceive(server_url string, ws *websocket.Conn, messages chan string) (err error) {\n\n\tvar read_buf string\n\n\tfor {\n\t\terr = websocket.Message.Receive(ws, &read_buf)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[%s] wsReceive : %s\", __FILE__, err)\n\t\t\tmessages <- `{\"cmd\" : \"err\"}`\n\t\t\tbreak\n\t\t}\n\t\tlog.Printf(\"[%s] received: %s\", __FILE__, read_buf)\n\t\tmessages <- read_buf\n\t}\n\n\treturn err\n}", "func (h *messageHandler) HandleMessage(m *nsq.Message) error {\n\t//Process the Message\n\tvar request Message\n\tif err := json.Unmarshal(m.Body, &request); err != nil {\n\t\tlog.Println(\"Error when Unmarshaling the message body, Err : \", err)\n\t\t// Returning a non-nil error will automatically send a REQ command to NSQ to re-queue the message.\n\t\treturn err\n\t}\n\t//Print the Message\n\tlog.Println(\"Message\")\n\tfmt.Println(request)\n\tlog.Println(\"--------------------\")\n\tlog.Println(\"Name : \", request.Name)\n\tlog.Println(\"Content : \", request.Content)\n\tlog.Println(\"Timestamp : \", request.Timestamp)\n\tlog.Println(\"--------------------\")\n\tlog.Println(\"\")\n\t// Will automatically set the message as finish\n\treturn nil\n}", "func sendMessage(w http.ResponseWriter, r *http.Request) {\n\t// Store the message\n\tvar message Message\n\t_ = json.NewDecoder(r.Body).Decode(&message)\n\tmessage.Username = getRandUsername()\n\tstoreMessage(message)\n\n\t// Broadcast the message\n\tbroadcast <- message\n\n\tvar msgs []Message\n\tmsgs = append(msgs, message)\n\tgetMessageResponse(w, msgs, nil)\n}", "func (s *server) wsHandler(w http.ResponseWriter, r *http.Request) {\n\t// Upgrade the HTTP connection.\n\tc, err := s.upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\ts.log.Error(\"error upgrading connection\")\n\t\treturn\n\t}\n\tdefer c.Close()\n\n\t// Client has connected, save its connection in clients struct.\n\t// Remove the connection once the client is disconected.\n\ts.clients.add(c)\n\tdefer s.clients.remove(c)\n\n\ts.log.Info(\"client connected\", zap.Any(\"address\", c.RemoteAddr()))\n\n\t// Wait for messages\n\tfor {\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\ts.log.Info(\"closing context\")\n\t\t\treturn\n\t\tdefault:\n\t\t\t_, msg, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\ts.log.Error(\"error reading message\", zap.Error(err))\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ts.log.Info(\"message received\", zap.String(\"msg\", string(msg)))\n\n\t\t\t// Publish the message to redis\n\t\t\terr = s.redis.Publish(s.ctx, s.channel, msg).Err()\n\t\t\tif err != nil {\n\t\t\t\ts.log.Error(\"error publishing message to redis\", zap.Error(err))\n\t\t\t}\n\n\t\t\ts.log.Info(\"message published\")\n\t\t}\n\t}\n}", "func handleWebsocket(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, \"Niedozwolona metoda\", 405)\n\t\treturn\n\t}\n\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.WithField(\"err\", err).Println(\"Przejście do Websocket\")\n\t\thttp.Error(w, \"Error Upgrading to websockets\", 400)\n\t\treturn\n\t}\n\n\tid := rr.register(ws)\n\n\tfor {\n\t\tmt, data, err := ws.ReadMessage()\n\t\tctx := log.Fields{\"mt\": mt, \"data\": data, \"err\": err}\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tlog.WithFields(ctx).Info(\"Połączenie websocket zamknięte\")\n\t\t\t} else {\n\t\t\t\tlog.WithFields(ctx).Error(\"Błąd odczytu wiadomości websocket\")\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tswitch mt {\n\t\tcase websocket.TextMessage:\n\t\t\tmsg, err := validateMessage(data)\n\t\t\tif err != nil {\n\t\t\t\tctx[\"msg\"] = msg\n\t\t\t\tctx[\"err\"] = err\n\t\t\t\tlog.WithFields(ctx).Error(\"Niepoprawna wiadomość\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\trw.publish(data)\n\t\tdefault:\n\t\t\tlog.WithFields(ctx).Warning(\"Nieznana wiadomość\")\n\t\t}\n\t}\n\n\trr.deRegister(id)\n\n\tws.WriteMessage(websocket.CloseMessage, []byte{})\n}", "func websocketEchoHandler(w http.ResponseWriter, r *http.Request) {\n\tc, err := webSocketUpgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\terrorf(w, http.StatusInternalServerError, \"websocket upgrade failed: %v\", err)\n\t\treturn\n\t}\n\tdefer c.Close()\n\tfor {\n\t\tmt, message, err := c.ReadMessage()\n\t\tif err != nil {\n\t\t\terrorf(w, http.StatusInternalServerError, \"websocket read failed: %v\", err)\n\t\t\tbreak\n\t\t}\n\t\tlog.Printf(\"recv: %s\", message)\n\t\terr = c.WriteMessage(mt, message)\n\t\tif err != nil {\n\t\t\terrorf(w, http.StatusInternalServerError, \"websocket write failed: %v\", err)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (xio *SimpleXIO) Message(timestamp, from, to, channel string, msg []byte, isEncrypted bool, doBell bool) {\n\tChatCmds <- cmdRecvMessage{timestamp, from, to, channel, string(msg)}\n}", "func wsHandler(w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tclient := &models.Client{Conn: conn}\n\tclients[conn] = client\n\tgo receiveMessages(conn)\n\n\toutboundResponses <- &models.Message{Body: \"Welcome to the chat room!\", Client: &models.Client{Handle: \"Server\", Conn: client.GetConn()}}\n\n\tfmt.Println(\"Client connected\")\n}", "func websocketRead(wsConn *websocket.Conn, integraClient *integra.Client) {\n\tfor {\n\t\t_, m, err := wsConn.ReadMessage()\n\t\tif err != nil {\n\t\t\t// Log errors, except for logging websocket\n\t\t\t// going away errors (they happen every time a\n\t\t\t// browser tab is closed).\n\t\t\tif !websocket.IsCloseError(err, websocket.CloseGoingAway) {\n\t\t\t\tlog.Println(\"ReadMessage failed:\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tvar message integra.Message\n\t\terr = json.Unmarshal(m, &message)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Unmarshall failed:\", err)\n\t\t}\n\n\t\terr = integraClient.Send(&message)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Send failed:\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func routeMsg(ws *websocket.Conn, ctx context.Context) {\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase msg := <-postFromClientChan:\n\t\t\tpostFromClient(msg)\n\t\tcase msg := <-initFromClientChan:\n\t\t\tinitFromClient(msg)\n\t\t}\n\t}\n\n}", "func ProcessMessage(message WSMessage) (err error) {\n\tif message.Type == \"MESSAGE\" {\n\t\tlog.Infof(\"received message for topic %v\", message.Data.Topic)\n\t\terr = json.Unmarshal([]byte(message.Data.MessageString),\n\t\t\t&message.Data.Message)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\ttopic := strings.Split(message.Data.Topic, \".\")[0]\n\t\tswitch {\n\t\tcase topic == \"channel-bits-events-v2\":\n\t\t\terr = ProcessBitsEvent(message)\n\t\tcase topic == \"channel-subscribe-events-v1\":\n\t\t\terr = ProcessSubscribeEvent(message)\n\t\tcase topic == \"channel-points-channel-v1\":\n\t\t\terr = ProcessPointsEvent(message)\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Debugf(\"%v\", message)\n\treturn\n}", "func ws_MessageLoop(messages chan string, receive_channel ReceiveChannel) {\n\n\tfor {\n\t\tmsg := <-messages\n\t\tlog.Printf(\"[%s] MESSAGE !!! \", __FILE__)\n\t\trcv := Command{}\n\t\tjson.Unmarshal([]byte(msg), &rcv)\n\t\tlog.Printf(rcv.Cmd)\n\n\t\tswitch rcv.Cmd {\n\t\tcase \"connected\":\n\t\t\tlog.Printf(\"[%s] connected succefully~~\", __FILE__)\n\t\tcase \"GetContainersInfo\":\n\t\t\treceive_channel.containers <- true\n\t\tcase \"UpdateImage\":\n\t\t\tlog.Printf(\"[%s] command <UpdateImage>\", __FILE__)\n\t\t\tupdate_msg, r := parseUpdateParam(msg)\n\t\t\tif r == nil {\n\t\t\t\treceive_channel.updateinfo <- update_msg\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"[%s] UpdateImage message null !!!\")\n\t\t\t}\n\t\tcase \"err\":\n\t\t\tlog.Printf(\"[%s] Error Case in connection need to recovery\", __FILE__)\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[%s] add command of {%s}\", __FILE__, rcv.Cmd)\n\t\t}\n\n\t}\n}", "func (l DefaultBlazeListener) OnMessage(ctx context.Context, msg MessageView, userId string) error {\n\tlog.Println(\"I got a message: \", msg)\n\tdata, err := base64.StdEncoding.DecodeString(msg.Data)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif msg.Category == \"SYSTEM_ACCOUNT_SNAPSHOT\" {\n\t\tvar transfer TransferView\n\t\tif err := json.Unmarshal(data, &transfer); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"I got a snapshot: \", transfer)\n\t\treturn nil\n\t} else {\n\t\tlog.Printf(\"I got a message, it said: %s\", string(data))\n\t\treturn nil\n\t}\n}", "func (e *orderEndpoint) ws(input interface{}, c *ws.Client) {\n\tmsg := &types.WebsocketEvent{}\n\n\tbytes, _ := json.Marshal(input)\n\tif err := json.Unmarshal(bytes, &msg); err != nil {\n\t\tlogger.Error(err)\n\t\tc.SendMessage(ws.OrderChannel, \"ERROR\", err.Error())\n\t}\n\n\tswitch msg.Type {\n\tcase \"NEW_ORDER\":\n\t\te.handleNewOrder(msg, c)\n\tcase \"CANCEL_ORDER\":\n\t\te.handleCancelOrder(msg, c)\n\tdefault:\n\t\tlog.Print(\"Response with error\")\n\t}\n}", "func (ctx *Context) SpecificMessageHandler(w http.ResponseWriter, r *http.Request) {\n\t//get the messageID form the request's URL path\n\t_, id := path.Split(r.URL.String())\n\n\t//Get current state\n\tss := &SessionState{}\n\t_, err := sessions.GetState(r, ctx.SessionKey, ctx.SessionStore, ss)\n\tif err != nil {\n\t\thttp.Error(w, \"error getting current session : \"+err.Error(), http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t//Get message from store\n\tm, err := ctx.MessageStore.GetMessageByID(messages.MessageID(id))\n\tif err != nil {\n\t\thttp.Error(w, \"error getting message: \"+err.Error(), http.StatusNotFound)\n\t\treturn\n\t}\n\n\t//if the user is not owner throw error\n\tif ss.User.ID != m.CreatorID {\n\t\thttp.Error(w, \"error updating message: you aren't the owner\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tswitch r.Method {\n\t//updates the specified message if the current user is the is owner.\n\t//writes back the updated message\n\tcase \"PATCH\":\n\t\td := json.NewDecoder(r.Body)\n\t\tmu := &messages.MessageUpdates{}\n\t\tif err := d.Decode(mu); err != nil {\n\t\t\thttp.Error(w, \"error decoding JSON\"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tum, err := ctx.MessageStore.UpdateMessage(mu, m)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error updating message: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t//Notify client of updated message through websocket\n\t\tn, err := um.ToUpdatedMessageEvent()\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error creating message event: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tctx.Notifier.Notify(n)\n\n\t\tw.Header().Add(headerContentType, contentTypeJSONUTF8)\n\t\tencoder := json.NewEncoder(w)\n\t\tencoder.Encode(um)\n\t//deletes the message if the current user is the owner.\n\tcase \"DELETE\":\n\t\tif err := ctx.MessageStore.DeleteMessage(messages.MessageID(id)); err != nil {\n\t\t\thttp.Error(w, \"error deleting message: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t//Notify client of updated message through websocket\n\t\tn, err := m.ToDeletedMessageEvent()\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"error creating message event: \"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tctx.Notifier.Notify(n)\n\n\t\tw.Header().Add(headerContentType, contentTypeText)\n\t\tw.Write([]byte(\"message succesfully deleted\"))\n\t}\n}", "func (h *Handler) GetMessage(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\tvar id int\n\n\tidStr := mux.Vars(r)[\"id\"]\n\tif id, err = strconv.Atoi(idStr); err != nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/text; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, \"id must be an integer\")\n\n\t\treturn\n\t}\n\n\tmessage, err := h.db.GetMessage(id)\n\tif err != nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/text; charset=UTF-8\")\n\t\tif err.Error() == dal.NotFound {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\tfmt.Fprintf(w, \"Could not find record with id %d\", id)\n\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"Could not get message with id %d: %s\", id, err)\n\n\t\treturn\n\t}\n\n\tmessage.IsPalindrome = isPalindrome(message.Body)\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\tif err = json.NewEncoder(w).Encode(message); err != nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/text; charset=UTF-8\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"Encountered an error encoding JSON response\")\n\n\t\treturn\n\t}\n}", "func (c *Conn) WriteMessage(msg interface{}) error {\n\tdata, err := xml.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcolor.Printf(\"@{|}<!-- REQUEST -->\\n%s\\n\\n\", string(data))\n\treturn c.WriteDataUnit(data)\n}", "func SendMessage(w http.ResponseWriter, r *http.Request) {\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, \"unsupport body type\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif hub == nil {\n\t\thttp.Error(w, \"unknown error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thub.sendMessage(string(b))\n}", "func (s *Switch) processMessage(ctx context.Context, ime net.IncomingMessageEvent) {\n\t// Extract request context and add to log\n\tif ime.RequestID != \"\" {\n\t\tctx = log.WithRequestID(ctx, ime.RequestID)\n\t} else {\n\t\tctx = log.WithNewRequestID(ctx)\n\t\ts.logger.WithContext(ctx).Warning(\"got incoming message event with no requestID, setting new id\")\n\t}\n\n\tif s.config.MsgSizeLimit != config.UnlimitedMsgSize && len(ime.Message) > s.config.MsgSizeLimit {\n\t\ts.logger.WithContext(ctx).With().Error(\"message is too big to process\",\n\t\t\tlog.Int(\"limit\", s.config.MsgSizeLimit),\n\t\t\tlog.Int(\"actual\", len(ime.Message)))\n\t\treturn\n\t}\n\n\tif err := s.onRemoteClientMessage(ctx, ime); err != nil {\n\t\t// TODO: differentiate action on errors\n\t\ts.logger.WithContext(ctx).With().Error(\"err reading incoming message, closing connection\",\n\t\t\tlog.FieldNamed(\"sender_id\", ime.Conn.RemotePublicKey()),\n\t\t\tlog.Err(err))\n\t\tif err := ime.Conn.Close(); err == nil {\n\t\t\ts.cPool.CloseConnection(ime.Conn.RemotePublicKey())\n\t\t\ts.Disconnect(ime.Conn.RemotePublicKey())\n\t\t}\n\t}\n}", "func webSocketHandler(w http.ResponseWriter, r *http.Request) {\n\n\t// 建立连接\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlogrus.Error(\"连接失败\", err.Error())\n\t\treturn\n\t}\n\n\t// 断开连接自动清除连接信息\n\tconn.SetCloseHandler(func(code int, text string) error {\n\t\tconn.Close()\n\t\treturn nil\n\t})\n\n\t// 用户认证\n\ttoken := r.URL.Query().Get(\"token\")\n\n\t// token校验\n\tif token != config.GetServerConfig().Token {\n\t\tlogrus.Error(\"用户校验失败!!!\")\n\t\tconn.CloseHandler()(0, \"认证失败\")\n\t\treturn\n\t}\n\tconnLock := &sync.Mutex{}\n\t// 开始接收消息\n\tfor {\n\t\t_, data, err := conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tconn.CloseHandler()(0, err.Error())\n\t\t\tbreak\n\t\t}\n\t\t// 解析消息\n\t\trpcMsg := &message.RPCMsg{}\n\t\terr = proto.Unmarshal(data, rpcMsg)\n\n\t\trpcCtx := context.GenRespCtx(conn, rpcMsg, connLock)\n\n\t\tif err != nil {\n\t\t\tlogrus.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif rpcMsg.Type == message.RemoterTypeEnum.HANDLER {\n\t\t\tok := clienthandler.Manager.Exec(rpcCtx)\n\t\t\tif !ok {\n\t\t\t\tif rpcCtx.GetRequestID() == 0 {\n\t\t\t\t\tlogrus.Warn(fmt.Sprintf(\"NotifyHandler(%v)不存在\", rpcCtx.GetHandler()))\n\t\t\t\t} else {\n\t\t\t\t\tlogrus.Warn(fmt.Sprintf(\"Handler(%v)不存在\", rpcCtx.GetHandler()))\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if rpcMsg.Type == message.RemoterTypeEnum.REMOTER {\n\t\t\tok := serverhandler.Manager.Exec(rpcCtx)\n\t\t\tif !ok {\n\t\t\t\tif rpcCtx.GetRequestID() == 0 {\n\t\t\t\t\tlogrus.Warn(fmt.Sprintf(\"NotifyRemoter(%v)不存在\", rpcCtx.GetHandler()))\n\t\t\t\t} else {\n\t\t\t\t\tlogrus.Warn(fmt.Sprintf(\"Remoter(%v)不存在\", rpcCtx.GetHandler()))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlogrus.Panic(\"无效的消息类型\")\n\t\t}\n\t}\n}", "func MsgServer(ws *websocket.Conn) {\r\n\tvar message string\r\n\t// all.(ws)\r\n\talive := true\r\n\tallconnections = append(allconnections, ws)\r\n\tfor {\r\n\t\twebsocket.Message.Receive(ws, &message)\r\n\t\tfor i, aWs := range allconnections {\r\n\r\n\t\t\tif _, err := aWs.Write([]byte(message)); err != nil {\r\n\t\t\t\tlog.Println(\"Error!!: \", err)\r\n\t\t\t\taWs.Close()\r\n\t\t\t\tallconnections = remove(allconnections, i)\r\n\t\t\t\talive = false\r\n\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t\tlog.Println(\"I hope I didn't crash: \")\r\n\t\tif !alive {\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n}", "func (api *APIv1) MessagesHandler(w http.ResponseWriter, r *http.Request) {\n\twr := &HTTPResponder{w, r, \"\"}\n\n\tconn, err := api.upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\twr.Error(HTTPErr, err)\n\t\treturn\n\t}\n\tid, messages := api.messages.Subscribe()\n\n\tfor {\n\t\tm, ok := <-messages // Blocks until we have a message.\n\t\tif !ok {\n\t\t\t// Channel is now closed.\n\t\t\tbreak\n\t\t}\n\t\tam, _ := json.Marshal(&APIv1Message{m.(*Message).typ, m.(*Message).text})\n\n\t\terr = conn.WriteMessage(websocket.TextMessage, am)\n\t\tif err != nil {\n\t\t\t// Silently unsubscribe, the client has gone away.\n\t\t\tbreak\n\t\t}\n\t}\n\tapi.messages.Unsubscribe(id)\n\tconn.Close()\n}", "func (c *Conn) OnMessage(messageType int, p []byte) {\n\tfor _, str := range strings.Split(string(p), \"\\r\\n\") {\n\t\tif str != \"\" {\n\t\t\tdata, _ := utils.GbkToUtf8([]byte(str))\n\t\t\tdoc := xml.NewDecoder(bytes.NewReader(data))\n\t\t\tnode := c.respParseAttr(doc)\n\t\t\tnode.Raw = string(data)\n\t\t\tswitch node.getAttr(\"id\") {\n\t\t\tcase \"1\":\n\t\t\t\tstatus := node.getElem(\"result\").getAttr(\"status\")\n\t\t\t\tif status == \"ok\" {\n\t\t\t\t\tc.key1 = node.getElem(\"key\").getAttr(\"key1\")\n\t\t\t\t\t// 初始化心跳\n\t\t\t\t\tc.loginChatServerSuccess()\n\t\t\t\t} else {\n\t\t\t\t\tEventChan <- EventMessage{Type: \"error\", Msg: fmt.Sprintf(\"%v\", \"进入直播间失败\")}\n\t\t\t\t}\n\t\t\tcase \"2\":\n\t\t\tcase \"3\":\n\t\t\tdefault:\n\t\t\t\tc.socketData(node)\n\t\t\t}\n\t\t\tc.pushNode(node)\n\t\t}\n\t}\n}", "func ServeWs(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif err := r.ParseForm(); err != nil {\n\t\tlog.Errorln(\"error parsing form on websocket serve, err:\", err)\n\t}\n\n\tcookie := model.CookieDetail{CookieName: values.UserCookieName, Collection: values.UsersCollectionName}\n\n\tif err := cookie.CheckCookie(r); err != nil {\n\t\tws, err := model.Upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tlog.Errorln(\"error upgrading websocket while sending error message, err: \", err)\n\t\t\treturn\n\t\t}\n\n\t\tif err := ws.WriteJSON(struct {\n\t\t\tMessageType string `json:\"msgType\"`\n\t\t}{\n\t\t\tvalues.UnauthorizedAcces,\n\t\t}); err != nil {\n\t\t\tlog.Errorln(\"could not send unauthorized message to user, err:\", err)\n\t\t}\n\n\t\tif err := ws.Close(); err != nil {\n\t\t\tlog.Errorln(\"error closing websocket on unauthorized access, err:\", err)\n\t\t}\n\n\t\treturn\n\t}\n\n\tws, err := model.Upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Errorln(\"error upgrading websocket, err:\", err)\n\t\treturn\n\t}\n\tmodel.HubConstruct.RegisterWS(ws, cookie.Email)\n}", "func messageDelete(w http.ResponseWriter, r *http.Request) {\n\tvar rBody request\n\n\tif err := json.NewDecoder(r.Body).Decode(&rBody); err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to decode message\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tid, err := strconv.Atoi(mux.Vars(r)[\"id\"])\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to convert ID to int. Error: %v\", err), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr = models.DeleteMessage(id)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to delete message. Error: %v\", err), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\ttype deleteMessage struct {\n\t\tdefaultProperties\n\t\tID int `json:\"id\"`\n\t}\n\n\tpayload := deleteMessage{\n\t\tdefaultProperties: defaultProperties{\n\t\t\tChannel: rBody.Channel,\n\t\t\tType: \"message\",\n\t\t\tSubType: \"message_deleted\",\n\t\t},\n\t\tID: id,\n\t}\n\n\t// prep for ws\n\tbytes, err := json.Marshal(payload)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to marshal chat message\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpubMessage := hub.PublishMessage{\n\t\tTopic: rBody.Channel,\n\t\tPayload: bytes,\n\t}\n\n\tbroker.Hub.Publish(pubMessage)\n\n\tw.WriteHeader(http.StatusOK)\n\treturn\n\n}", "func (c *app) ReceiveMessage(msg message) {\n\tc.in <- msg\n}", "func GetMessage(ctx *context.Context, session *context.Session, w http.ResponseWriter, r *http.Request, vars map[string]string) {\n\tmessage, err := ctx.MessageService.GetMessage(vars[\"id\"])\n\n\tif err != nil {\n\t\thandleError(w, err)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(message)\n}", "func (s *Server) handleMessageRequest(pubKey credentials.StaticSizedPublicKey, r *message.Request) {\n\tmethodName := r.GetMethod()\n\tif md, ok := s.service.methods[methodName]; ok {\n\t\t// Create a decoder function to unmarshal the message\n\t\tdec := func(v interface{}) error {\n\t\t\terr := UnmarshalProtoMessage(r.GetPayload(), v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\t// Inject the peer's public keey into the context so the handler's can use it\n\t\tctx := peer.NewContext(context.Background(), &peer.Peer{PublicKey: pubKey})\n\t\tv, herr := md.Handler(s.service.serviceImpl, ctx, dec)\n\n\t\tmsg, err := message.NewResponse(r.GetCallId(), v, herr)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\treplyMsg, err := MarshalProtoMessage(msg)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\ts.sendMsg(pubKey, replyMsg)\n\t}\n}", "func SendMessage(message string) {\n\tif message == \"\" {\n\t\tfmt.Println(\"Message cannot be empty\")\n\t\tos.Exit(1)\n\t}\n\n\ttype Status struct {\n\t\tSuccess bool\n\t\tMessage interface{}\n\t}\n\n\ttype Result struct {\n\t\tNewMessageID string `json:\"new_message_id\"`\n\t}\n\ttype Response struct {\n\t\tStatus Status `json:\"status\"`\n\t\tResult interface{}\n\t}\n\n\tbaseURL, err := url.Parse(apiURL)\n\n\tif err != nil {\n\t\tfmt.Println(\"Malformed URL: \", err.Error())\n\t\treturn\n\t}\n\n\troomID := viper.GetString(\"roomID\")\n\tparams := url.Values{}\n\tparams.Add(\"room_id\", roomID)\n\n\tbaseURL.RawQuery = params.Encode()\n\n\tvar replacedString = strings.ReplaceAll(message, \"\\\\n\", \"\\n\")\n\t// re := regexp.MustCompile(`\\r?\\n`)\n\t// replacedString := re.ReplaceAllString(message, `\\n`)\n\t// fmt.Printf(\"fd;fhkhfkhf %v\", replacedString)\n\tjsonValues, err := json.Marshal(map[string]string{\n\t\t\"text\": replacedString,\n\t\t\"_t\": viper.GetString(\"token\"),\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tformData := url.Values{\n\t\t\"pdata\": {string(jsonValues)},\n\t}\n\n\treq, err := http.NewRequest(\n\t\thttp.MethodPost,\n\t\tbaseURL.String(),\n\t\tstrings.NewReader(formData.Encode()),\n\t)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded;charset=UTF-8\")\n\treq.Header.Add(\"cookie\", fmt.Sprintf(\"%v=%v\", cookieName, viper.GetString(\"cookie\")))\n\n\tresponse, err := http.DefaultClient.Do(req)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error making send-message request, %v\\n\", err)\n\t}\n\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error parsing response %v\\n\", err)\n\t\treturn\n\t}\n\n\tvar parsedBody Response\n\terr = json.Unmarshal(body, &parsedBody)\n\tif err != nil {\n\t\tlog.Fatalln(\"Error parsing response\", err)\n\t}\n\n\tif parsedBody.Status.Success != true {\n\t\tvar errMsg string\n\t\tswitch v := parsedBody.Status.Message.(type) {\n\t\tcase string:\n\t\t\terrMsg = v\n\t\tcase []interface{}:\n\t\t\t// for _, val := range v {\n\t\t\t// \tfmt.Println(val)\n\t\t\t// }\n\t\t\terrMsg = v[0].(string)\n\t\t}\n\t\tfmt.Printf(\"❌ Send report failed: %v\\n\", errMsg)\n\n\t} else {\n\t\tfmt.Println(\"✅ Send report successfully\")\n\t}\n\t// fmt.Printf(\"%s\\n\", string(body))\n\n}", "func messageHandler(w http.ResponseWriter, r *http.Request) {\n\tu := r.PostFormValue(\"username\")\n\tm := r.PostFormValue(\"message\")\n\tlog.Printf(\"Howdy mam, username is: %q, message is: %q\\n\", u, m)\n\tfmt.Fprintf(w, \"I am not ready yet, mam\\n\")\n\t// TODO: need to check for post, username and message.\n\t// TODO: need to send the request to slack.\n}", "func (wc *WSConnection) ReadMsg(ctx context.Context) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlogger.Errorf(\"ws soeckt Read Routine panic \", string(debug.Stack()))\n\t\t\t// wc.wsConn.Close()\n\t\t}\n\t}()\n\twc.wsConn.SetReadLimit(maxMessageSize)\n\twc.wsConn.SetReadDeadline(time.Now().Add(pongWait))\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t\tmsgType, message, err := wc.wsConn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tlogger.Errorf(\"ws soeckt Read err- \", err)\n\t\t\t}\n\t\t\tlogger.Errorf(\"ws soeckt Read err- %v\", err)\n\t\t\tbreak\n\t\t}\n\t\tif msgType == websocket.TextMessage {\n\t\t\tmessage = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))\n\t\t}\n\t\tif wc.WChan != nil {\n\t\t\twc.WChan <- &ChanMsgPack{\n\t\t\t\tcid: wc.cid,\n\t\t\t\tbody: message,\n\t\t\t\tlogicBindID: wc.GetBindId(),\n\t\t\t}\n\t\t}\n\t\tlogger.Infof(\"ws soeckt receive id: %d msg %s \", wc.bindId, string(message))\n\t}\n}", "func (c app) ReceiveMessage(msg message) {\n\tc.in <- msg\n}", "func MessagesHandler(w http.ResponseWriter, r *http.Request, ctx *Context) error {\n\tclient, err := ctx.GetClient()\n\tif err != nil { return err }\n\n\tvar mailbox *imap.Box\n\tboxName := r.URL.Query().Get(\"box\")\n\tlog.Println(r.URL)\n\tif boxName == \"\" {\n\t\tmailbox = client.Inbox()\n\t} else {\n\t\tmailbox = client.Box(boxName)\n\t}\n\tif mailbox == nil {\n\t\tw.WriteHeader(404)\n\t\treturn nil\n\t}\n\n\tmailbox.Check()\n\tmsgs := mailbox.Msgs()\n\n\tn := len(msgs)\n\tvar headers []*Message\n\tif n > 0 {\n\t\tmn := max(1, (minusf(uint32(n), 50)))\n\t\theaders = make([]*Message, uint32(n) - mn)\n\t\tfor i, msg := range msgs[mn:] {\n\t\t\theaders[i] = &Message{\n\t\t\t\tfmt.Sprintf(\"%v\",msg.UID),\n\t\t\t\tmsg.Hdr,\n\t\t\t\t(msg.Flags & imap.FlagSeen) == imap.FlagSeen,\n\t\t\t\tmsg.Box.Name,\n\t\t\t}\n\t\t}\n\t} else {\n\t\theaders = make([]*Message, 0)\n\t}\n\n\tb, err := json.Marshal(headers)\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.WriteHeader(200)\n\tw.Write(b)\n\treturn nil\n}", "func MessageHandler(w http.ResponseWriter, r *http.Request) {\n\n\tvars := mux.Vars(r)\n\tkey := vars[\"key\"]\n\tdb, err := bolt.Open(\"messages.db\", 0777, nil)\n\n\tswitch r.Method {\n\tcase \"GET\":\n\t\treceiver := strings.Split(key, \"-\")[1]\n\t\tkey = strings.Split(key, \"-\")[0]\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t} else {\n\t\t\tdb.Update(func(tx *bolt.Tx) error {\n\t\t\t\tif receiver == \"\" {\n\t\t\t\t\tio.WriteString(w, \"[]\")\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\t//messagesBucket := tx.Bucket([]byte(key))\n\t\t\t\tmessagesBucket, _ := tx.CreateBucketIfNotExists([]byte(key))\n\t\t\t\tjsonStr := \"[\"\n\t\t\t\tmessagesBucket.ForEach(func(k, v []byte) error {\n\t\t\t\t\tvar messageItem message\n\t\t\t\t\tjson.Unmarshal(v, &messageItem)\n\t\t\t\t\tif (messageItem.Name == receiver && messageItem.From == key) || (messageItem.Name == key && messageItem.From == receiver) {\n\t\t\t\t\t\tjsonStr += string(v)\n\t\t\t\t\t\tjsonStr += \",\"\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t\tjsonStr = strings.TrimSuffix(jsonStr, \",\")\n\t\t\t\tjsonStr += \"]\"\n\t\t\t\tio.WriteString(w, jsonStr)\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\tcase \"POST\":\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t} else {\n\t\t\tdb.Update(func(tx *bolt.Tx) error {\n\t\t\t\tdecoder := json.NewDecoder(r.Body)\n\t\t\t\tvar m message\n\t\t\t\terrdec := decoder.Decode(&m)\n\t\t\t\tif errdec != nil {\n\t\t\t\t\tpanic(errdec)\n\t\t\t\t}\n\n\t\t\t\tif key == \"\" {\n\t\t\t\t\tio.WriteString(w, \"Please provide the recipients name\")\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tb, _ := json.Marshal(m)\n\t\t\t\tdata := string(b[:])\n\n\t\t\t\tmessagesBucket, _ := tx.CreateBucketIfNotExists([]byte(key))\n\t\t\t\tmessagesBucket.Put([]byte(m.Time), []byte(data))\n\n\t\t\t\tmessagesBucketOwn, _ := tx.CreateBucketIfNotExists([]byte(m.From))\n\t\t\t\tmessagesBucketOwn.Put([]byte(m.Time), []byte(data))\n\n\t\t\t\tio.WriteString(w, \"Success\")\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\t}\n\tdb.Close()\n}", "func (o *WlDisplay) ServeMessage(msg *wire.Message) error {\n\tswitch msg.Opcode {\n\tcase 0:\n\t\tif o.errorHandler == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tr := wire.NewReader(msg.Payload)\n\n\t\tobjectIdId, err := r.ReadID()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tobjectId, ok := o.Base.Conn.GetObject(objectIdId)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"cannot find an object: id(%d)\", objectIdId)\n\t\t}\n\t\tcode, err := r.ReadUint()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmessage, err := r.ReadString()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn o.errorHandler(objectId, code, message)\n\n\tcase 1:\n\t\tif o.deleteIdHandler == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tr := wire.NewReader(msg.Payload)\n\n\t\tid, err := r.ReadUint()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn o.deleteIdHandler(id)\n\n\tdefault:\n\t\treturn fmt.Errorf(\"WlDisplay: unhandled message(%v)\", msg)\n\t}\n}", "func (conn SplunkConnection) SendMessage(message *Message) (string, error) {\n\tdata := make(url.Values)\n\tdata.Add(\"name\", message.Name)\n\tdata.Add(\"value\", message.Content.Message)\n\tdata.Add(\"severity\", string(message.Content.Severity))\n\tresponse, err := conn.HTTPPost(fmt.Sprintf(\"%s/services/messages\", conn.BaseURL), &data)\n\treturn response, err\n}", "func (c *Client) messageReceived(data []byte) {\n\tfor _, v := range c.onDebugListeners {\n\t\tv(data)\n\t}\n\tif bytes.HasPrefix(data, c.config.EvtMessagePrefix) {\n\t\t//it's a custom ws message\n\t\treceivedEvt := c.messageSerializer.getWebsocketCustomEvent(data)\n\t\tvalue, ok := c.onEventListeners.Load(string(receivedEvt))\n\t\tif !ok || value == nil {\n\t\t\treturn\n\t\t}\n\n\t\tlisteners, ok := value.([]MessageFunc)\n\t\tif !ok || len(listeners) == 0 {\n\t\t\treturn // if not listeners for this event exit from here\n\t\t}\n\n\t\tcustomMessage, err := c.messageSerializer.deserialize(receivedEvt, data)\n\t\tif customMessage == nil || err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tfor i := range listeners {\n\t\t\tif fn, ok := listeners[i].(func()); ok { // its a simple func(){} callback\n\t\t\t\tfn()\n\t\t\t} else if fnString, ok := listeners[i].(func(string)); ok {\n\n\t\t\t\tif msgString, is := customMessage.(string); is {\n\t\t\t\t\tfnString(msgString)\n\t\t\t\t} else if msgInt, is := customMessage.(int); is {\n\t\t\t\t\t// here if server side waiting for string but client side sent an int, just convert this int to a string\n\t\t\t\t\tfnString(strconv.Itoa(msgInt))\n\t\t\t\t}\n\n\t\t\t} else if fnInt, ok := listeners[i].(func(int)); ok {\n\t\t\t\tfnInt(customMessage.(int))\n\t\t\t} else if fnBool, ok := listeners[i].(func(bool)); ok {\n\t\t\t\tfnBool(customMessage.(bool))\n\t\t\t} else if fnBytes, ok := listeners[i].(func([]byte)); ok {\n\t\t\t\tfnBytes(customMessage.([]byte))\n\t\t\t} else {\n\t\t\t\tlisteners[i].(func(interface{}))(customMessage)\n\t\t\t}\n\n\t\t}\n\t} else {\n\t\t// it's native websocket message\n\t\tfor i := range c.onNativeMessageListeners {\n\t\t\tc.onNativeMessageListeners[i](data)\n\t\t}\n\t}\n\n}", "func (client *wsClient) writeMessages() {\n\tdefer client.conn.Close()\n\tdefer log.Println(\"writeMessages exiting\")\n\tfor {\n\t\t// Read a message from the outbound channel\n\t\tmsg := <-client.outboundMsgs\n\t\t// Send message to the browser\n\t\terr := client.conn.WriteMessage(websocket.TextMessage, msg)\n\t\tif err != nil {\n\t\t\tlog.Println(\"writeMessages: \", err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func MessagesHandler(w http.ResponseWriter, r *http.Request) {\n\tclient := context.Get(r, \"redis.Client\").(*redis.Client)\n\tu := url.Values{}\n\n\tu.Set(\"a\", \"sf-muni\")\n\n\trouteTags := r.URL.Query().Get(\"route_tags\")\n\tif routeTags != \"\" {\n\t\troutes := strings.Split(routeTags, \",\")\n\t\tfor n := range routes {\n\t\t\tu.Add(\"r\", routes[n])\n\t\t}\n\t}\n\n\tbody, err := getFromCache(client, r.URL.String())\n\tif err == nil {\n\t\tfmt.Fprintf(w, \"%s\", body)\n\t\treturn\n\t}\n\n\tbody, err = fetch(\"messages\", u)\n\tif err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\twriteToCache(client, r.URL.String(), body)\n\n\tfmt.Fprintf(w, \"%s\", body)\n}", "func (s Service) UpdateMessage(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tbodyReq, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tidS, ok := mux.Vars(r)[\"id\"] // Gets params\n\tif !ok {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tid, err := strconv.Atoi(idS)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tmes, err := s.strg.Update(bodyReq, uint(id))\n\tif err == errors.New(\"Deleted message1\") {\n\t\thttp.Error(w, err.Error(), http.StatusGone)\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tjsonResponse, err := json.Marshal(mes)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tfmt.Fprint(w, string(jsonResponse))\n\n\t// params := mux.Vars(r)\n\t// for index, mas := range Messages {\n\t// \tif mas.ID == params[\"id\"] {\n\t// \t\tMessages = append(Messages[:index], Messages[index+1:]...)\n\t// \t\tvar mas Message\n\t// \t\t_ = json.NewDecoder(r.Body).Decode(&mas)\n\t// \t\tmas.ID = params[\"id\"]\n\t// \t\tMessages = append(Messages, mas)\n\t// \t\tjson.NewEncoder(w).Encode(mas)\n\t// \t\treturn\n\t// \t}\n\t// }\n}", "func AddMessage(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tfmt.Printf(\"Parse form error\\n%v\", err)\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\tmessage := r.Form.Get(\"message\")\n\tif message == \"\" {\n\t\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\t\treturn\n\t}\n\n\tCookie, err := GetCookieValue(r)\n\tif err != nil {\n\t\thttp.Error(w, \"Cookieの解析に失敗しました。\", http.StatusBadRequest)\n\t\tlog.Printf(\"Cookieの解析に失敗しました。\\n%v\\n\", err)\n\t\treturn\n\t}\n\n\tAccounts, err := ReadAccounts()\n\tif err != nil {\n\t\thttp.Error(w, \"アカウントデータの読み込みに失敗しました。\", http.StatusBadRequest)\n\t\tlog.Printf(\"アカウントデータの読み込みに失敗しました。\\n%v\\n\", err)\n\t\treturn\n\t}\n\n\tname := Accounts[Cookie[\"id\"]].Name\n\n\tvar newMessage Message = Message{\n\t\tText: message,\n\t\tName: name,\n\t\tTime: time.Now(),\n\t}\n\n\tMessages = append(Messages, newMessage)\n\n\tdata, err := json.MarshalIndent(Messages, \"\", \"\t \")\n\tif err != nil {\n\t\tfmt.Printf(\"Json marshal error\\n%v\", err)\n\t\thttp.Error(w, \"500 Internal server error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tExportFile(MessageFilePath, data)\n\thttp.Redirect(w, r, \"/\", http.StatusTemporaryRedirect)\n\treturn\n}", "func (c *client) SendMessage(m *Message) {\n\tselect {\n\tcase c.messages <- m:\n\tdefault:\n\t\tc.Close()\n\t}\n}", "func (m *MajsoulChannel) recvMsg(stop chan struct{}) {\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, os.Interrupt)\n\tfor {\n\t\tselect {\n\t\tcase <-interrupt:\n\t\t\treturn\n\t\tcase <-stop:\n\t\t\treturn\n\t\tdefault:\n\t\t\tmsgType, msg, err := m.Connection.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tm.Close(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif msgType == websocket.BinaryMessage {\n\t\t\t\tm.processMsg(msg)\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) Message(channelID discord.ChannelID, messageID discord.MessageID) (*discord.Message, error) {\n\tvar msg *discord.Message\n\treturn msg, c.RequestJSON(&msg, \"GET\",\n\t\tEndpointChannels+channelID.String()+\"/messages/\"+messageID.String())\n}", "func (c *Connection) SendMessage(r *dto.Response) {\n\n\tbody, err := json.Marshal(r)\n\tif err != nil {\n\n\t}\n\n\tc.Inner.WriteMessage(websocket.TextMessage, body)\n}", "func (s Service) DeleteMessage(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tidS, ok := mux.Vars(r)[\"id\"] // Gets params\n\tif !ok {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tid, err := strconv.Atoi(idS)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tmes, err := s.strg.DeleteByID(uint(id))\n\tif err == errors.New(\"Deleted message\") {\n\t\thttp.Error(w, err.Error(), http.StatusGone)\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tjsonResponse, err := json.Marshal(mes)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tfmt.Fprint(w, string(jsonResponse))\n\t// params := mux.Vars(r)\n\t// for index, mas := range Messages {\n\t// \tif mas.ID == params[\"id\"] {\n\t// \t\tMessages = append(Messages[:index], Messages[index+1:]...)\n\t// \t\tbreak\n\t// \t}\n\t// }\n\t// json.NewEncoder(w).Encode(Messages)\n}", "func (m *messageHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\n // writes a string (m.message) to a writer (w)\n fmt.Fprintf(w, m.message)\n}", "func msgHandler(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close()\n\tbody, _ := ioutil.ReadAll(r.Body)\n\tgo writer(string(body))\n}", "func readMsg(ws *websocket.Conn, cancel context.CancelFunc, client *firestore.Client) {\n\n\tvar payload models.MsgPayload = models.MsgPayload{\n\t\tConn: ws,\n\t\tClient: client,\n\t}\n\n\tdefer cancel()\n\n\tfor {\n\t\terr := ws.ReadJSON(&payload)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbreak\n\t\t}\n\t\tswitch payload.Type {\n\t\tcase \"postFromClient\":\n\t\t\tpostFromClientChan <- payload\n\t\tcase \"initFromClient\":\n\t\t\tinitFromClientChan <- payload\n\t\t}\n\t}\n}", "func (object *MQMessageHandler) OnMQMessage(raw []byte, offset int64) {\n}", "func socketHandler(ws *websocket.Conn) {\n\tvar err error\n\tfor {\n\t\tvar reply string\n\n\t\tif err = websocket.Message.Receive(ws, &reply); err != nil {\n\t\t\tfmt.Println(\"Can't receive\")\n\t\t\tbreak\n\t\t}\n\n\t\tif debug {\n\t\t\tfmt.Println(\"Received from client: \" + reply)\n\t\t}\n\n\t\t// Json decode\n\t\tvar req = AOWRequest{}\n\t\tif err := json.Unmarshal([]byte(reply), &req); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// Get client from pool\n\t\tpclient := clientPool.Get().(*http.Client)\n\n\t\t// Prepare request\n\t\tpreq, perr := http.NewRequest(req.Method, fmt.Sprintf(\"%s\", req.URI), nil)\n\t\tfor k, v := range req.Headers {\n\t\t\tpreq.Header.Add(k, v)\n\t\t}\n\t\tpresp, perr := pclient.Do(preq)\n\t\tif perr != nil {\n\t\t\tlog.Printf(\"%s\\n\", perr)\n\n\t\t\t// Return client to pool\n\t\t\tclientPool.Put(pclient)\n\t\t\treturn\n\t\t}\n\t\tdefer presp.Body.Close()\n\t\tbody, readErr := ioutil.ReadAll(presp.Body)\n\t\tif readErr != nil {\n\t\t\tlog.Printf(\"%s\\n\", readErr)\n\t\t}\n\n\t\t// Response wrapper\n\t\tvar resp = AOWResponse{}\n\t\tresp.Id = req.Id\n\t\tresp.Text = string(body)\n\t\tresp.Status = presp.StatusCode\n\t\tresp.Headers = presp.Header\n\t\trespBytes, jErr := json.Marshal(resp)\n\t\tif jErr != nil {\n\t\t\tpanic(jErr)\n\t\t}\n\n\t\t// Return client to pool\n\t\tclientPool.Put(pclient)\n\n\t\t// Msg\n\t\tmsg := string(respBytes)\n\n\t\t// Send to client\n\t\tif debug {\n\t\t\tfmt.Println(\"Sending to client: \" + msg)\n\t\t}\n\t\tif err = websocket.Message.Send(ws, msg); err != nil {\n\t\t\tfmt.Println(\"Can't send\")\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (c Client) OnMessage(message []byte) error {\n\tvar (\n\t\tv ws.SubscriptionResponse\n\t)\n\n\terr := json.Unmarshal(message, &v)\n\tif err != nil {\n\t\t// in case an error happens just assume the message is due to a subscription and try to process it\n\t\treturn c.ProcessMessage(message)\n\t}\n\n\tsplit := strings.Split(v.Request.Args[0], \".\")\n\tchannel := split[0]\n\tmarket := split[1]\n\n\tswitch v.Request.Op {\n\tcase Subscribed:\n\t\tc.subscriptions[channel] = append(c.subscriptions[channel], market)\n\t\tc.logger.Infof(\"Successfully %v to channel {%v} for market {%v}\", v.Request.Op, channel, market)\n\t\tbreak\n\tcase Unsubscribed:\n\t\tvar subs []string\n\t\tfor _, sub := range c.subscriptions[channel] {\n\t\t\tif sub == market {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsubs = append(subs, sub)\n\t\t}\n\t\tc.subscriptions[channel] = subs\n\t\tc.logger.Infof(\"Successfully %v to channel {%v} for market {%v}\", v.Request.Op, channel, market)\n\t\tbreak\n\t}\n\n\treturn nil\n}", "func (i *IncomingSocket) OnMessage(belowNexus nexusHelper.Nexus, moneysocketMessage base2.MoneysocketMessage) {\n\tlog.Info(\"websocket nexus got message\")\n\ti.onMessage(belowNexus, moneysocketMessage)\n}", "func (tv *TV) request(msg *Message) (Message, error) {\n\tch := tv.setupResponseChannel(msg.ID)\n\tdefer tv.teardownResponseChannel(msg.ID)\n\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn Message{}, fmt.Errorf(\"could not marshall request: %v\", err)\n\t}\n\n\ttv.wsMutex.Lock()\n\terr = tv.ws.WriteMessage(websocket.TextMessage, b)\n\ttv.wsMutex.Unlock()\n\n\tif err != nil {\n\t\treturn Message{}, fmt.Errorf(\"could not write to socket: %v\", err)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase res, ok := <-ch:\n\t\t\tif !ok {\n\t\t\t\treturn Message{}, errors.New(\"no response\")\n\t\t\t}\n\n\t\t\tif res.Type == ResponseMessageType && msg.Type == RegisterMessageType {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn res, res.Validate()\n\t\tcase <-time.After(time.Second * 15):\n\t\t\treturn Message{}, errors.New(\"timeout\")\n\t\t}\n\t}\n}", "func (c *Common) HandleReceivedMessage(message messages.Messager) {\n\n switch message.(type) {\n case *messages.LocationMessage:\n c.rp.HandleLocationMessage(message.(*messages.LocationMessage))\n case *messages.MotorSpeedMessage:\n c.rp.HandleMotorSpeedMessage(message.(*messages.MotorSpeedMessage))\n }\n\n}", "func sendToWs(msg network.Message, update bool, s *session, messagesDb *MsgDb) {\n\tmsgNum := msg.Seqnum\n\twsMsg := wsMessage{Src: msg.Src, Dst: msg.Dst,\n\t\tMsgNumber: strconv.FormatUint(msgNum, 10), Payload: string(msg.Payload)}\n\ts.logger.Debug(\"sending json message to WS\", zap.Any(\"msg\", wsMsg))\n\tif update {\n\t\t(*messagesDb)[msgNum] = msg\n\t}\n\n\tif err := s.conn.WriteJSON(wsMsg); err != nil {\n\t\ts.logger.Error(\"failed to send json message\", zap.Error(err))\n\t\treturn\n\t}\n}", "func SendMessageToRoute(msg interface{}, exchangeName string, routeKey string) {\n sendMessage(msg, DirectExchange, exchangeName, \"\", routeKey, true)\n}", "func OnMSG(c diam.Conn, m *diam.Message) {\n\tlog.Printf(\"Receiving message from %s\", c.RemoteAddr().String())\n\t//log.Println(m)\n}", "func (s *ClientState) send(msg MsgBody) error {\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\tlogError(\"could not marshal message: %s\", err)\n\t\treturn err\n\t}\n\tlogDebug(\"sending message\")\n\ts.ws.SetWriteDeadline(time.Now().Add(WEBSOCKET_WRITE_TIMEOUT))\n\terr = s.ws.WriteMessage(websocket.TextMessage, b)\n\tif err != nil {\n\t\tlogError(\"could not send message: %s\", err)\n\t\treturn err\n\t}\n\tlogDebug(\"sent: %s\", string(b))\n\treturn nil\n}", "func HandlePostMessage(w http.ResponseWriter, r *http.Request) {\n\tvar res []byte\n\tb, _ := readRequestParams(r.Body)\n\tm, _ := initChannels(b, channels...)\n\terr := sendMessages(m)\n\tif err != nil {\n\t\terr := err.Error()\n\t\tres, _ = json.Marshal(MsgResBody{Sent: false, Error: &err})\n\t} else {\n\t\tres, _ = json.Marshal(MsgResBody{Sent: true, Error: nil})\n\t}\n\n\tw.Write(res)\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\n fmt.Println(r.Host)\n\n // upgrade this connection to a WebSocket\n // connection\n ws, err := upgrader.Upgrade(w, r, nil)\n if err != nil {\n log.Println(err)\n }\n // listen indefinitely for new messages coming\n // through on our WebSocket connection\n reader(ws)\n}", "func WebsocketHandler(writer http.ResponseWriter, request *http.Request) {\n\tws, err := websocket.Upgrade(writer, request, nil, 1024, 1024)\n\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\thttp.Error(writer, \"Invalid handshake\", 400)\n\t\treturn\n\t} else if err != nil {\n\t\treturn\n\t}\n\n\t/*\n\t * Create a new websocket connection struct and add it's pointer\n\t * address to our web socket tracking map.\n\t */\n\tconnection := &WebsocketConnection{WS: ws, SendChannel: make(chan MailItemStruct, 256)}\n\tWebsocketConnections[connection] = true\n\tdefer destroyConnection(connection)\n\n\tfor {\n\t\tfor message := range connection.SendChannel {\n\t\t\ttransformedMessage := model.JSONMailItem{\n\t\t\t\tId: message.Id,\n\t\t\t\tDateSent: message.DateSent,\n\t\t\t\tFromAddress: message.FromAddress,\n\t\t\t\tToAddresses: message.ToAddresses,\n\t\t\t\tSubject: message.Subject,\n\t\t\t\tXMailer: message.XMailer,\n\t\t\t\tBody: \"\",\n\t\t\t\tContentType: \"\",\n\t\t\t\tAttachmentCount: len(message.Attachments),\n\t\t\t}\n\n\t\t\terr := connection.WS.WriteJSON(transformedMessage)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tconnection.WS.Close()\n}", "func (sub *Subscriber) RequestMessage() {\n\t// get message from channel\n\tfor {\n\t\tmessage := <-sub.Request\n\n\t\t//log.Println(\"Going to send message on socket %s\", message.TargetConnId)\n\n\t\t// send message to targetConn\n\t\twriter := bufio.NewWriter(sub.Conn)\n\t\twriter.Write(append(message.Payload, '\\n'))\n\t\twriter.Flush()\n\t}\n}", "func (f *fakeDiskUpdateWatchServer) SendMsg(m interface{}) error { return nil }", "func onMessage(cm gcm.CcsMessage) error {\n\ttoylog.Infoln(\"Message, from:\", cm.From, \"with:\", cm.Data)\n\t// Echo the message with a tag.\n\tcm.Data[\"echoed\"] = true\n\tm := gcm.HttpMessage{To: cm.From, Data: cm.Data}\n\tr, err := gcm.SendHttp(*serverKey, m)\n\tif err != nil {\n\t\ttoylog.Errorln(\"Error sending message.\", err)\n\t\treturn err\n\t}\n\ttoylog.Infof(\"Sent message. %+v -> %+v\", m, r)\n\treturn nil\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\t// upgrade to a websocket\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Printf(\"upgrade error: %v\\n\", err.Error())\n\t\tw.WriteHeader(500)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tfor {\n\t\t// read the raw (encoded) message from the connection\n\t\tmsgtype, encodedmsg, err := conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error reading ws message: %v\\n\", err.Error())\n\t\t\tjsonb, _ := json.Marshal(OutgoingMessage{Type: \"error\", Message: \"Error reading request \" + err.Error(), Success: false})\n\t\t\tconn.WriteMessage(msgtype, jsonb)\n\t\t\tbreak\n\t\t}\n\n\t\t// Log what we got for later debugging and unmarshal it to our struct\n\t\tvar msg IncomingMessage\n\t\terr = json.Unmarshal(encodedmsg, &msg)\n\t\tlog.Printf(\"ws recv: %v\\n\", msg)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error decoding ws message: %v\\n\", err.Error())\n\t\t\tjsonb, _ := json.Marshal(OutgoingMessage{Type: \"error\", Message: \"Did not understand request \" + err.Error(), Success: false})\n\t\t\tconn.WriteMessage(msgtype, jsonb)\n\t\t\tbreak\n\t\t}\n\n\t\tswitch msg.Action {\n\t\tcase \"make_drink\":\n\t\t\tlocked := hw.LockPumps()\n\t\t\tif !locked {\n\t\t\t\t// don't want to queue up users with a normal lock, so tell them to come back later\n\t\t\t\tjsonb, _ := json.Marshal(OutgoingMessage{Type: \"error\", Message: \"System currently in use, please wait and try again later.\", Success: false})\n\t\t\t\tconn.WriteMessage(msgtype, jsonb)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// make sure our stop flag is false, user can hit stop from here on out\n\t\t\tstopRunning = false\n\t\t\tmakeDrink(conn, msgtype, msg)\n\t\t\t// free up the lock for the next person\n\t\t\thw.UnlockPumps()\n\t\tcase \"run_pump\":\n\t\t\tlocked := hw.LockPumps()\n\t\t\tif !locked {\n\t\t\t\t// don't want to queue up users with a normal lock, so tell them to come back later\n\t\t\t\tjsonb, _ := json.Marshal(OutgoingMessage{Type: \"error\", Message: \"System currently in use, please wait and try again later.\", Success: false})\n\t\t\t\tconn.WriteMessage(msgtype, jsonb)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\trunPump(conn, msgtype, msg)\n\t\t\t// free up the lock for the next person\n\t\t\thw.UnlockPumps()\n\t\tcase \"stop\":\n\t\t\t// just set the stop flag to true, the current running loop should stop within a second\n\t\t\tstopRunning = true\n\t\tdefault:\n\t\t\tjsonb, _ := json.Marshal(OutgoingMessage{Type: \"error\", Message: \"Request not understood\", Success: false})\n\t\t\tconn.WriteMessage(msgtype, jsonb)\n\t\t}\n\t}\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\treturn\n\t}\n\n\tchatroomId := r.FormValue(\"chatroomId\")\n\n\tvar upgrader = websocket.Upgrader{\n\t\tReadBufferSize: 4096,\n\t\tWriteBufferSize: 4096,\t\n\t\tCheckOrigin: func(r *http.Request) bool { return true },\n\t}\n\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\th := chatIdToHub[chatroomId]\n\tif h == nil{\n\t\tfmt.Println(\"Couldn't find hub.\")\n\t}\n\n\tc := &connection{chatroomId: chatroomId, nicknameId: \"sadf\", hub: h, send: make(chan []byte, 256), ws: ws}\n\tc.hub.register <- c\n\tgo c.writePump()\n\tc.readPump()\n}", "func (c *Client) SendMessage(msg Message) error {\n\t// convert Message to JSON bytes\n\tmsgJSON, err := makeJSONMassage(msg)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"fail to make json bytes\")\n\t}\n\n\t// create new Request with given params\n\treq, err := http.NewRequest(\"POST\", c.WebhookURL.String(), bytes.NewBuffer(msgJSON))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"fail to create new request\")\n\t}\n\n\t// add necessary headers\n\tfor k, v := range c.Header {\n\t\treq.Header.Add(k, v)\n\t}\n\n\tlog.Printf(\"send request\")\n\t// send http request\n\tres, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\tlog.Printf(\"error after send request\")\n\t\treturn errors.Wrap(err, \"fail to send request\")\n\t}\n\tdefer res.Body.Close()\n\n\tlog.Printf(\"check status code\")\n\t// check status code\n\tif res.StatusCode != 200 {\n\t\tt, _ := ioutil.ReadAll(res.Body)\n\t\treturn fmt.Errorf(\"http request failed: status: %s: url=%s, body=%s\", res.Status, c.WebhookURL.String(), string(t))\n\t}\n\treturn nil\n}", "func Message(level string, msg string) {\n\tonce.Do(initChannel)\n\n\tbody := buildBody(level, msg)\n\tdata := body[\"data\"].(map[string]interface{})\n\tdata[\"body\"] = messageBody(msg)\n\n\tpush(body)\n}", "func MessagesHandler(w http.ResponseWriter, r *http.Request) {\n\t//fmt.Fprintln(w, \"no message to show\")\n\t// specify to the client that the request should be respect the JSON format\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\t// Encode the messages to send back some JSON to the client\n\tif err := json.NewEncoder(w).Encode(listMessages); err != nil {\n\t\tpanic(err)\n\t}\n}", "func Echo(ws *websocket.Conn) {\n\tvar errreceive error\n\tvar errsend error\n\n\tfmt.Println(\"Start of Echo func.\")\n\n\tfor {\n\t\tvar reply string\n\n\t\terrreceive = websocket.Message.Receive(ws, &reply)\n\n\t\tif errreceive != nil {\n\t\t\tfmt.Println(\"Can't receive\")\n\t\t\tbreak\n\t\t}\n\n\t\t// if reply is not empty, message has been received\n\t\tfmt.Println(\"Received back from client: \" + reply)\n\n\t\tmsg := reply\n\t\tfmt.Println(\"Sending to client: \" + msg)\n\n\t\terrsend = websocket.Message.Send(ws, msg)\n\n\t\tif errsend != nil {\n\t\t\tfmt.Println(\"Can't send\")\n\t\t\tbreak\n\t\t}\n\t}\n}", "func messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) {\n\n\t// If the message author is the bot, do nothing\n\tif m.Author.ID == BotID {\n\t\treturn\n\t}\n\n\tif m.Content == \"ping\" {\n\t\t_, _ = s.ChannelMessageSend(m.ChannelID, \"pong\")\n\t}\n\n}", "func (m *msgHandler) Message(_ []byte, hdr wire.Header, payload []byte) error {\n\tmsg := Message{\n\t\tMsgType: pb.MessageType(hdr.MessageType),\n\t\tMsg: make([]byte, len(payload)),\n\t}\n\tcopy(msg.Msg, payload)\n\n\tm.owner.cond.L.Lock()\n\tdefer m.owner.cond.L.Unlock()\n\tm.owner.points = append(m.owner.points, msg)\n\tm.owner.cond.Broadcast()\n\treturn nil\n}", "func (c *client) SendJSONMessage(msg interface{}) error {\n\treturn c.ws.WriteJSON(msg)\n}" ]
[ "0.71633077", "0.7148145", "0.6686693", "0.6623083", "0.6605026", "0.64997613", "0.6431778", "0.6405488", "0.63879466", "0.6301808", "0.62788296", "0.62768406", "0.62759316", "0.6266679", "0.6266447", "0.6254338", "0.6254338", "0.62163866", "0.6205541", "0.6175806", "0.61744785", "0.61640334", "0.6156608", "0.61533135", "0.6136362", "0.6135973", "0.61187065", "0.6105243", "0.60936046", "0.6091013", "0.60728484", "0.605527", "0.6051788", "0.6049223", "0.602823", "0.60230744", "0.6018642", "0.6014932", "0.60117733", "0.60103816", "0.60051185", "0.6003434", "0.60007626", "0.5981935", "0.5966379", "0.59582734", "0.59444463", "0.5937484", "0.5932081", "0.5930671", "0.5928066", "0.59111094", "0.59096014", "0.58903", "0.5881966", "0.5873534", "0.58724755", "0.5872331", "0.5871342", "0.5870792", "0.5867714", "0.5865695", "0.5860151", "0.5858342", "0.5851374", "0.5847103", "0.5842568", "0.5842088", "0.5837785", "0.5831403", "0.58267146", "0.58238596", "0.5820995", "0.5815991", "0.5798016", "0.579594", "0.57905513", "0.5790021", "0.5786354", "0.5786036", "0.57742804", "0.5773029", "0.57604384", "0.57603353", "0.57587254", "0.57496333", "0.57462937", "0.57454497", "0.57409745", "0.5736808", "0.5736738", "0.57360035", "0.5730942", "0.5726829", "0.57239276", "0.5722275", "0.5719954", "0.5717434", "0.57117677", "0.57071" ]
0.8022294
0
wsChanSend build and send messages to connected browsers, the channel is shared between connections
func wsChanSend() { log.Println("wschan running...") i := 1 for { // send stuff to clients // TODO: solve multiple clients connecting wsChan <- "test: " + strconv.Itoa(i) i++ } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ws_SendMsg(ws *websocket.Conn, send_channel SendChannel) {\n\tfor {\n\t\tselect {\n\t\tcase send_msg := <-send_channel.containers:\n\t\t\tlog.Printf(\"[%s] containers sendMessage= \", __FILE__, send_msg)\n\t\t\twebsocket.JSON.Send(ws, send_msg)\n\t\tcase send_msg := <-send_channel.updateinfo:\n\t\t\tlog.Printf(\"[%s] update sendMessage=\", __FILE__, send_msg)\n\t\t}\n\t}\n}", "func WsSend(channel, message string) (err error) {\n\tfor cs, _ := range ActiveClients[channel] {\n\t\terr = websocket.Message.Send(cs.websocket, message)\n\t\tif err != nil {\n\t\t\tlog.Println(channel, \"Could not send message to \", cs.clientIP, err.Error())\n\t\t}\n\t}\n\treturn\n}", "func wsMessage(w http.ResponseWriter, r *http.Request) {\n\n\t// Get session, continue only if authenticated\n\tsok, vok := checkLogin(r, cfgMap[\"session name\"], \"user\")\n\tif !sok || !vok {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError),\n\t\t\thttp.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tcc := make(chan bool)\n\t// upgrade to websocket\n\tc, err := upgrader.Upgrade(w, r, nil)\n\tdefer c.Close()\n\tif err != nil {\n\t\tlog.Println(\"upgrade:\", err)\n\t\treturn\n\t}\n\n\t// handle websocket incoming browser messages\n\tgo func(c *websocket.Conn) {\n\t\tfor {\n\t\t\t_, message, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"read:\", err)\n\t\t\t\tcc <- true\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Printf(\"recv: %s\", message)\n\t\t}\n\t}(c)\n\n\t// send websocket message to browser\n\tfor {\n\t\tselect {\n\t\tcase <-cc:\n\t\t\treturn\n\t\tdefault:\n\t\t\tresponse := []byte(<-wsChan)\n\t\t\t// mesage type = 1\n\t\t\terr = c.WriteMessage(1, response)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"ws write err:\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t}\n}", "func (h *hub) update() {\n\t//send each channel its client state\n\tfor c := range h.connections {\n\t\tmsg := c.client.GetMessage()\n\t\tc.ws.WriteMessage(websocket.BinaryMessage, msg)\n\t}\n}", "func sendLoop() {\n\tif currentWebsocket == nil {\n\t\tcolorLog(\"[INFO] BW: No connection, wait for it.\\n\")\n\t\tcmd := <-connectChannel\n\t\tif \"QUIT\" == cmd.Action {\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor {\n\t\tnext, ok := <-toBrowserChannel\n\t\tif !ok {\n\t\t\tcolorLog(\"[WARN] BW: Send channel was closed.\\n\")\n\t\t\tbreak\n\t\t}\n\n\t\tif \"QUIT\" == next.Action {\n\t\t\tbreak\n\t\t}\n\n\t\tif currentWebsocket == nil {\n\t\t\tcolorLog(\"[INFO] BW: No connection, wait for it.\\n\")\n\t\t\tcmd := <-connectChannel\n\t\t\tif \"QUIT\" == cmd.Action {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\twebsocket.JSON.Send(currentWebsocket, &next)\n\t\tcolorLog(\"[SUCC] BW: Sent %v.\\n\", next)\n\t}\n\n\tcolorLog(\"[WARN] BW: Exit send loop.\\n\")\n}", "func (w *websocketPeer) sendHandler() {\n\tdefer close(w.writerDone)\n\tfor msg := range w.wr {\n\t\tif msg == nil {\n\t\t\treturn\n\t\t}\n\t\tb, err := w.serializer.Serialize(msg.(wamp.Message))\n\t\tif err != nil {\n\t\t\tw.log.Print(err)\n\t\t}\n\n\t\tif err = w.conn.WriteMessage(w.payloadType, b); err != nil {\n\t\t\tif !wamp.IsGoodbyeAck(msg) {\n\t\t\t\tw.log.Print(err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *ClientState) send(msg MsgBody) error {\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\tlogError(\"could not marshal message: %s\", err)\n\t\treturn err\n\t}\n\tlogDebug(\"sending message\")\n\ts.ws.SetWriteDeadline(time.Now().Add(WEBSOCKET_WRITE_TIMEOUT))\n\terr = s.ws.WriteMessage(websocket.TextMessage, b)\n\tif err != nil {\n\t\tlogError(\"could not send message: %s\", err)\n\t\treturn err\n\t}\n\tlogDebug(\"sent: %s\", string(b))\n\treturn nil\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\treturn\n\t}\n\n\tchatroomId := r.FormValue(\"chatroomId\")\n\n\tvar upgrader = websocket.Upgrader{\n\t\tReadBufferSize: 4096,\n\t\tWriteBufferSize: 4096,\t\n\t\tCheckOrigin: func(r *http.Request) bool { return true },\n\t}\n\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\th := chatIdToHub[chatroomId]\n\tif h == nil{\n\t\tfmt.Println(\"Couldn't find hub.\")\n\t}\n\n\tc := &connection{chatroomId: chatroomId, nicknameId: \"sadf\", hub: h, send: make(chan []byte, 256), ws: ws}\n\tc.hub.register <- c\n\tgo c.writePump()\n\tc.readPump()\n}", "func (h *Hub) Send(conn *websocket.Conn, data []byte, mt int) {\n\th.ch <- channelMessage{\n\t\tdata: data,\n\t\tconn: conn,\n\t\tmt: mt,\n\t}\n}", "func (c *Client) send(ctx context.Context, message map[string]interface{}) error {\n\tc.Lock()\n\tmessage[\"id\"] = c.nextID\n\tc.nextID++\n\tc.Unlock()\n\terr := make(chan error, 1)\n\tgo func() { err <- websocket.JSON.Send(c.webSock, message) }()\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase err := <-err:\n\t\treturn err\n\t}\n}", "func (h *Hub) run() {\n\tfor {\n\t\tselect {\n\t\t// register a new client to a specific ws connection\n\t\tcase client := <-h.register:\n\t\t\th.clients[client] = true\n\t\t\tclient.send <- &Message{\n\t\t\t\tbroadcast: []byte(fmt.Sprintf(`{\"id\": \"%s\"}`, client.key)),\n\t\t\t}\n\t\t// de-register existing client\n\t\tcase client := <-h.unregister:\n\t\t\tif _, ok := h.clients[client]; ok {\n\t\t\t\tdelete(h.clients, client)\n\t\t\t\tclose(client.send)\n\t\t\t}\n\t\t// send message to each client\n\t\tcase message := <-h.broadcast:\n\t\t\tfor client := range h.clients {\n\t\t\t\t// don't send to creator of the broadcast\n\t\t\t\tif client.key == message.senderKey {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tselect {\n\t\t\t\tcase client.send <- message:\n\t\t\t\tdefault:\n\t\t\t\t\tclose(client.send)\n\t\t\t\t\tdelete(h.clients, client)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *hub) run() {\n for {\n select{\n case s := <- h.register:\n // fmt.Println(\"wild client has appeared in the brush!\")\n clients := h.channels[s.channel]\n if clients == nil {\n clients = make(map[*client]bool)\n h.channels[s.channel] = clients\n }\n h.channels[s.channel][s.client] = true\n //send the latest data for room (empty string if new room)\n //s.client.send <- []byte(contents[s.channel])\n case s := <- h.unregister:\n clients := h.channels[s.channel]\n if clients != nil {\n if _, ok := clients[s.client]; ok{\n delete(clients, s.client)\n close(s.client.send)\n if len(clients) == 0 {\n delete(h.channels, s.channel)\n if len(contents[s.channel]) != 0 {\n //delete contents for channel if no more clients using it.\n delete(contents, s.channel)\n }\n }\n }\n }\n case m := <- h.broadcast:\n clients := h.channels[m.channel]\n // fmt.Println(\"broadcasting message to \", clients, \"data is: \", string(m.data))\n for c := range clients {\n fmt.Println(\"broadcasting message to \", c, \"data is: \", string(m.data))\n select {\n case c.send <- m.data:\n contents[m.channel] = string(m.data)\n default:\n close(c.send)\n delete(clients, c)\n if len(clients) == 0 {\n delete(h.channels, m.channel)\n if len(contents[m.channel]) != 0 {\n //delete contents for channel if no more clients using it.\n delete(contents, m.channel)\n }\n }\n }\n }\n }\n }\n}", "func ListenToWsChannel() {\n\tresp := &WsJsonResponse{\n\t\tAction: \"\",\n\t\tMessage: \"\",\n\t\tMessageType: \"\",\n\t}\n\tfor {\n\t\te := <-WsChan\n\n\t\tswitch e.Action {\n\t\tcase \"usernames\":\n\t\t\tusers := getAllClients()\n\t\t\tresp.Action = \"UsersList\"\n\t\t\tresp.MessageType = \"JSON\"\n\t\t\tresp.Message = \"Get all usernames\"\n\t\t\tresp.UsersList = users\n\t\t\tgo broadCastToAll(resp)\n\t\tcase \"left\":\n\t\t\tdelete(Clients, e.UserConn)\n\t\t\tusers := getAllClients()\n\t\t\tresp.Action = \"LeftUser\"\n\t\t\tresp.MessageType = \"JSON\"\n\t\t\tresp.Message = e.Username + \" Left !\"\n\t\t\tresp.UsersList = users\n\t\t\tclose(e.UserConn.CloseChan)\n\t\t\tgo broadCastToAll(resp)\n\t\tcase \"broadcast\":\n\t\t\tresp.Action = \"BroadCast\"\n\t\t\tresp.MessageType = \"JSON\"\n\t\t\tresp.Message = e.Username + \" : \" + e.Message\n\t\t\tgo broadCastToAll(resp)\n\t\tcase \"private\":\n\t\t\tresp.Action = \"Private\"\n\t\t\tresp.Message = \"JSON\"\n\t\t\tresp.Message = e.Username + \" : \" + e.Message\n\t\t\tgo sendPrivateMsg(resp, e.Target)\n\t\tdefault:\n\t\t\tresp.Action = e.Action + \"; Action\"\n\t\t\tresp.Message = fmt.Sprintf(\"Some message you sent : %v\", e.Username)\n\t\t\tresp.MessageType = \"JSON\"\n\t\t\terr := e.UserConn.MyConn.WriteJSON(resp)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (client *wsClient) writeMessages() {\n\tdefer client.conn.Close()\n\tdefer log.Println(\"writeMessages exiting\")\n\tfor {\n\t\t// Read a message from the outbound channel\n\t\tmsg := <-client.outboundMsgs\n\t\t// Send message to the browser\n\t\terr := client.conn.WriteMessage(websocket.TextMessage, msg)\n\t\tif err != nil {\n\t\t\tlog.Println(\"writeMessages: \", err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.ws.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\t// spew.Dump(c.clientID)\n\t\t\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.ws.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.ws.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.ws.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (conn *PeerConnection) send(payload string) {\n\tconn.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\tconn.ws.WriteMessage(websocket.TextMessage, []byte(payload))\n}", "func (w *BaseWebsocketClient) Send(msg base.MoneysocketMessage) error {\n\tif w.getConnection() == nil {\n\t\treturn errors.New(\"not currently connected\")\n\t}\n\tres, err := message.WireEncode(msg, w.SharedSeed())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn w.SendBin(res)\n}", "func SendWorker(ch chan RemoteCommandMessage, broadlink broadlinkrm.Broadlink, wg *sync.WaitGroup) {\n\tfor msg := range ch {\n\t\tfor _, cmd := range msg.commands {\n\t\t\tswitch cmd.commandType {\n\t\t\tcase SendCommand:\n\t\t\t\terr := broadlink.Execute(cmd.target, cmd.data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error executing command: %v\", err)\n\t\t\t\t}\n\t\t\tcase Pause:\n\t\t\t\tinterval, err := strconv.Atoi(cmd.data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error processing pause interval (%v): %v\", cmd.data, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ttime.Sleep(time.Duration(interval) * time.Millisecond)\n\t\t\tcase shutdown:\n\t\t\t\twg.Done()\n\t\t\t\tlog.Print(\"SendWorker terminated\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func ChMessageSend(textChannelID, message string) {\n\tfor i := 0; i < 10; i++ {\n\t\t_, err := dg.ChannelMessageSend(textChannelID, message)\n\t\tif err != nil {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\r\n\t// fmt.Println(\"socket start!\")\r\n\tconn, err := upgrader.Upgrade(w, r, nil)\r\n\tif err != nil {\r\n\t\tlogger.Error(err.Error())\r\n\t\treturn\r\n\t}\r\n\tclient := &Client{conn: conn, send: make(chan []byte, 256), UID: 0}\r\n\t// client.hub.register <- client\r\n\r\n\t// Allow collection of memory referenced by the caller by doing all work in\r\n\t// new goroutines.\r\n\tgo client.writePump()\r\n\tgo client.readPump()\r\n}", "func (fr *frame) chanSend(ch *govalue, elem *govalue) {\n\telemtyp := ch.Type().Underlying().(*types.Chan).Elem()\n\telem = fr.convert(elem, elemtyp)\n\telemptr := fr.allocaBuilder.CreateAlloca(elem.value.Type(), \"\")\n\tfr.builder.CreateStore(elem.value, elemptr)\n\telemptr = fr.builder.CreateBitCast(elemptr, llvm.PointerType(llvm.Int8Type(), 0), \"\")\n\tchantyp := fr.types.ToRuntime(ch.Type())\n\tfr.runtime.sendBig.call(fr, chantyp, ch.value, elemptr)\n}", "func broadcastWebSocket(outChannel chan string, ws *websocket.Conn) {\n\n for {\n select {\n case data := <-outChannel:\n ws.WriteMessage(websocket.TextMessage, []byte(data))\n break\n }\n }\n}", "func (h *wsHub) send(message []byte) {\n\th.broadcast <- message\n}", "func send(enc json.Encoder){\n\tif testing {log.Println(\"send\")}\n\tmsg:=new(Message)\n\tfor {\n\t\tmessage:= <-output\n\t\twhatever:=strings.Split(message,\"*\")\n\t\tmsg.Username=myName\n\t\tif message==\"disconnect\"{\n\t\t\tmsg.Kind=\"DISCONNECT\"\n\t\t\tenc.Encode(msg)\n\t\t\tbreak\n\t\t} else if len(whatever)>1 {\n\t\t\tmsg.Kind=\"PRIVATE\"\n\t\t\tmsg.Receiver=whatever[1]\n\t\t\tmsg.MSG=whatever[0]\n\t\t} else {\n\t\t\tmsg.Kind=\"PUBLIC\"\n\t\t\tmsg.MSG=whatever[0]\n\t\t}\n\t\tenc.Encode(msg)\n\t}\n\tos.Exit(1)\n}", "func (m *MajsoulChannel) sendMsg(stop chan struct{}) {\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, os.Interrupt)\n\n\tfor {\n\t\tselect {\n\t\tcase <-interrupt:\n\t\t\treturn\n\t\tcase <-stop:\n\t\t\treturn\n\t\tcase out := <-m.outgoing:\n\t\t\terr := m.Connection.WriteMessage(out.MsgType, out.Msg)\n\t\t\tif err != nil {\n\t\t\t\tm.Close(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tswitch out.MsgType {\n\t\t\tcase websocket.PingMessage:\n\t\t\t\tm.timeLastPingSent = time.Now()\n\t\t\t\tlog.Println(\"Ping sent\")\n\t\t\tcase websocket.PongMessage:\n\t\t\t\tlog.Println(\"Pong sent\")\n\t\t\tcase websocket.CloseMessage:\n\t\t\t\tlog.Println(\"Close sent\")\n\t\t\tdefault:\n\t\t\t\tlog.Println(\"Message sent: \", out.Msg)\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *client) write() {\n\tfor {\n\t\ttoWrite := <-c.send\n\t\t_ = c.conn.WriteMessage(websocket.BinaryMessage, toWrite)\n\t}\n}", "func (c *UserClientWS) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\t/*n := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}*/\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) listenWrite() {\n for {\n select {\n\n // send message to the client\n case msg := <-c.ch:\n websocket.JSON.Send(c.ws, msg)\n\n // receive done request\n case <-c.doneCh:\n c.grid.Del(c)\n c.doneCh <- true // for listenRead method\n return\n }\n }\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tfmt.Println(\"Closing writePump\")\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tif !c.isAlive {\n\t\t\t\tfmt.Printf(\"Channel closed\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t//// Add queued chat messages to the current websocket message.\n\t\t\t//n := len(c.send)\n\t\t\t//for i := 0; i < n; i++ {\n\t\t\t//\tw.Write(newline)\n\t\t\t//\tw.Write(<-c.send)\n\t\t\t//}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func send(username string, text string, ws *websocket.Conn) {\n\tm := Message{\n\t\tUsername: username,\n\t\tText: text,\n\t}\n\terr := websocket.JSON.Send(ws, m)\n\tif err != nil {\n\t\tfmt.Println(\"Could not send message: \", err.Error())\n\t}\n}", "func sendToWs(msg network.Message, update bool, s *session, messagesDb *MsgDb) {\n\tmsgNum := msg.Seqnum\n\twsMsg := wsMessage{Src: msg.Src, Dst: msg.Dst,\n\t\tMsgNumber: strconv.FormatUint(msgNum, 10), Payload: string(msg.Payload)}\n\ts.logger.Debug(\"sending json message to WS\", zap.Any(\"msg\", wsMsg))\n\tif update {\n\t\t(*messagesDb)[msgNum] = msg\n\t}\n\n\tif err := s.conn.WriteJSON(wsMsg); err != nil {\n\t\ts.logger.Error(\"failed to send json message\", zap.Error(err))\n\t\treturn\n\t}\n}", "func (c *MsgConnection) sendSock(m []byte) error {\n\tif err := c.deadliner.SetWriteDeadline(time.Now().Add(c.deadline)); err != nil {\n\t\treturn err\n\t}\n\n\t// the underlying net.Conn object performs its own write locking and is goroutine safe, so no need for a\n\t// mutex here. see https://github.com/spacemeshos/go-spacemesh/pull/2435#issuecomment-851039112.\n\tif _, err := c.w.Write(m); err != nil {\n\t\tif err := c.Close(); err != ErrAlreadyClosed {\n\t\t\tc.networker.publishClosingConnection(ConnectionWithErr{c, err}) // todo: reconsider\n\t\t}\n\t\treturn err\n\t}\n\tmetrics.PeerRecv.With(metrics.PeerIDLabel, c.remotePub.String()).Add(float64(len(m)))\n\treturn nil\n}", "func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tclient := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}\n\tclient.hub.register <- client\n\n\t// Allow collection of memory referenced by the caller by doing all work in\n\t// new goroutines.\n\tgo client.writePump()\n\tgo client.readPump()\n}", "func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn\n\t}\n\tclient := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}\n\tclient.hub.register <- client\n\tgo client.writePump()\n\tclient.readPump()\n}", "func sendToChannel(ch chan string, url string) {\n\tch <- url\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\treturn\n\t}\n\tif r.Header.Get(\"Origin\") != \"http://\"+r.Host {\n\t\thttp.Error(w, \"Origin not allowed\", 403)\n\t\treturn\n\t}\n\tws, err := websocket.Upgrade(w, r.Header, nil, 1024, 1024)\n\tif _, ok := err.(websocket.HandshakeError); ok {\n\t\thttp.Error(w, \"Not a websocket handshake\", 400)\n\t\treturn\n\t} else if err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tc := &connection{send: make(chan []byte, 256), ws: ws}\n\th.register <- c\n\tgo c.writePump()\n\tc.readPump()\n}", "func (c *Client) Send(ch <-chan *Message) error {\n\tfor msg := range ch {\n\t\t_, err := io.WriteString(c.conn, msg.Content)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func sendMessageToChannels(msg chat.Message, msgChannels []chan chat.Message) {\n\tfor _, msgChan := range msgChannels {\n\t\tmsgChan <- msg\n\t}\n}", "func serveWs(hub *Hub, c echo.Context) error {\n\n\tuser := c.Get(\"user\").(*jwt.Token)\n\tclaims := user.Claims.(*auth.JWTUserClaims)\n\tname := claims.Name\n\n\n\tconn, err := upgrader.Upgrade(c.Response(), c.Request(), nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tclient := &Client{name: name, hub: hub, conn: conn, send: make(chan Command)}\n\tclient.hub.register <- client\n\tgo client.writePump()\n\ttime.AfterFunc(1*time.Second, func() {\n\t\tclient.hub.broadcast <- enterRoomCommand(client.name)\n\t})\n\tclient.readPump()\n\ttime.AfterFunc(1*time.Second, func() {\n\t\tclient.hub.broadcast <- leaveRoomCommand(client.name)\n\t})\n\treturn nil\n}", "func (c Channel) Send(cmd wit.Command, clientIDs ...string) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tfor _, clientID := range clientIDs {\n\t\tif cmap, ok := c.clients[clientID]; ok {\n\t\t\tfor _, op := range cmap {\n\t\t\t\tselect {\n\t\t\t\tcase <-op.Done():\n\t\t\t\tcase op.CmdCh() <- cmd:\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func newWebSocketChan(ctx context.Context, addr string, conn *websocket.Conn) wormhole.DataChannel {\n\treturn &webSocketChan{\n\t\tctx: ctx,\n\t\taddr: addr,\n\t\tconn: conn,\n\t\twfh: wormhole_msgp.Handler,\n\t}\n}", "func web(srvChan chan string, channel, nick, hostname string, args []string) {\n\tmessage := \"NOTICE \" + channel + \" :https://anex.us/\"\n\tlog.Println(message)\n\tsrvChan <- message\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *client) serveWs(s *server, w http.ResponseWriter, r *http.Request) {\n\tconn,err := upgrader.Upgrade(w,r,nil)\n\tif err != nil {\n\t\tlog.Println(\"error upgrading to websocket:\",err.Error())\n\t\treturn\n\t}\n\tc.Server = s\n\tc.conn = conn\n\tc.send = make(chan[]byte, 256)\n\n\tc.Server.register <- c\n\n\tgo c.writePump()\n\tgo c.readPump()\n}", "func ServeWs(hub *Hubx, w http.ResponseWriter, r *http.Request, upgrader websocket.Upgrader, clientProps map[string]interface{}) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tlog := NewLogger(hub.options.Logger, \"github.com/RocksonZeta/hubx.Client\", hub.options.LoggerLevel)\n\n\tclient := &Client{hub: hub, conn: conn, send: make(chan []byte, hub.options.ChannelSize), log: log}\n\tif client.hub.register != nil {\n\t\tfor k, v := range clientProps {\n\t\t\tclient.Props.Store(k, v)\n\t\t}\n\t\tclient.hub.register <- client\n\t} else {\n\t\tlog.Error(\"ServeWs hubx is nil\")\n\t\treturn\n\t}\n\n\t// Allow collection of memory referenced by the caller by doing all work in\n\t// new goroutines.\n\tGo(client.writePump)\n\tGo(client.readPump)\n\t// go client.writePump()\n\t// go client.readPump()\n}", "func ServeWs(hub *Hub, w http.ResponseWriter, r *http.Request, appKey, client, version, protocolStr string) {\n\tprotocol, _ := Str2Int(protocolStr)\n\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\n\tif appKey != viper.GetString(\"APP_KEY\") {\n\t\tlog.Error(\"Error app key\", appKey)\n\t\t_ = conn.SetWriteDeadline(time.Now().Add(time.Second))\n\t\t_ = conn.WriteMessage(websocket.TextMessage, ErrPack(4001))\n\t\t_ = conn.Close()\n\t\treturn\n\t}\n\n\tif !funk.Contains(SupportedProtocolVersions, protocol) {\n\t\tlog.Error(\"Unsupported protocol version\", protocol)\n\t\t_ = conn.SetWriteDeadline(time.Now().Add(time.Second))\n\t\t_ = conn.WriteMessage(websocket.TextMessage, ErrPack(4007))\n\t\t_ = conn.Close()\n\t\treturn\n\t}\n\n\tsocketID := GenerateSocketID()\n\tsession := &Session{hub: hub, conn: conn, client: client, version: version, protocol: protocol, send: make(chan []byte, maxMessageSize), subscriptions: make(map[string]bool), pubSub: new(redis.PubSub), socketID: socketID, closed: false}\n\tsession.hub.register <- session\n\n\tsession.pubSub = db.Redis().Subscribe()\n\tgo session.subscribePump()\n\tgo session.writePump()\n\tgo session.readPump()\n\n\tsession.send <- EstablishPack(socketID)\n}", "func serveWs(h func(*Client), upgrader *websocket.Upgrader, w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tclient := &Client{\n\t\tconn: conn,\n\t\tonConnectedHandler: h,\n\t\tsend: make(chan []byte, 256),\n\t\treceive: make(chan []byte, 256),\n\t\tconnQuit: make(chan struct{}, 1),\n\t\tchanQuit: make(chan struct{}, 1),\n\t}\n\tclient.Run()\n}", "func (g *Gateway) sendMessagesToServer(mchan <-chan string) {\n\tgo func() {\n\t\tconn, err := net.Dial(\"tcp\", g.MessageAddress)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"error opening message server connection: %s\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\t//status, err := bufio.NewReader(conn).ReadBytes('\\r')\n\n\t\tfor p := range mchan {\n\t\t\tm, err := ioutil.ReadFile(p)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"Gateway: Error reading file: \", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"path\": p,\n\t\t\t\t\"contents\": string(m),\n\t\t\t}).Info(\"Gateway sending message to central server\")\n\t\t\tfmt.Fprintf(conn, \"%s\\r\\n\", m) // NOTE could change to \\n?\n\t\t\t// TODO remove file\n\t\t}\n\n\t}()\n}", "func (p *player) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tp.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-p.disconnect:\n\t\t\t// Finish this goroutine to not to send messages anymore\n\t\t\treturn\n\t\tcase move, ok := <-p.sendMove: // Opponent moved a piece\n\t\t\tp.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tpayload := websocket.FormatCloseMessage(1001, \"\")\n\t\t\t\tp.conn.WriteMessage(websocket.CloseMessage, payload)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := p.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(move)\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase msg, ok := <-p.sendChat: // Chat msg\n\t\t\tp.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tp.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif (msg.userId == p.userId) && (msg.Username == DEFAULT_USERNAME) {\n\t\t\t\tmsg.Username = \"you\"\n\t\t\t}\n\n\t\t\tmsgB, err := json.Marshal(msg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Could not marshal data:\", err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tw, err := p.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Could not make next writer:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(msgB)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(p.sendChat)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tmsg = <-p.sendChat\n\t\t\t\tif (msg.userId == p.userId) && (msg.Username == DEFAULT_USERNAME) {\n\t\t\t\t\tmsg.Username = \"you\"\n\t\t\t\t}\n\t\t\t\tmsgB, err := json.Marshal(msg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"Could not marshal data:\", err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tw.Write([]byte(newline))\n\t\t\t\tw.Write(msgB)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\tlog.Println(\"Could not close writer:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C: // ping\n\t\t\tp.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := p.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\tlog.Println(\"Could not ping:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.clock.C: // Player ran out ouf time\n\t\t\t// Inform the opponent about this\n\t\t\tp.room.broadcastNoTime<- p.color\n\n\t\t\tdata := map[string]string{\n\t\t\t\t\"OOT\": \"MY_CLOCK\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppRanOut: // Opponent ran out ouf time\n\t\t\tdata := map[string]string{\n\t\t\t\t\"OOT\": \"OPP_CLOCK\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.drawOffer: // Opponent offered draw\n\t\t\tdata := map[string]string{\n\t\t\t\t\"drawOffer\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppAcceptedDraw: // opponent accepted draw\n\t\t\tdata := map[string]string{\n\t\t\t\t\"oppAcceptedDraw\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppResigned: // opponent resigned\n\t\t\tdata := map[string]string{\n\t\t\t\t\"oppResigned\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.rematchOffer: // Opponent offered rematch\n\t\t\tdata := map[string]string{\n\t\t\t\t\"rematchOffer\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppAcceptedRematch: // opponent accepted rematch\n\t\t\tdata := map[string]string{\n\t\t\t\t\"oppAcceptedRematch\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppReady: // opponent ready\n\t\t\tdata := map[string]string{\n\t\t\t\t\"oppReady\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppDisconnected: // opponent disconnected\n\t\t\tdata := map[string]string{\n\t\t\t\t\"waitingOpp\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppReconnected: // opponent reconnected\n\t\t\tdata := map[string]string{\n\t\t\t\t\"oppReady\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-p.oppGone: // opponent is gone\n\t\t\tdata := map[string]string{\n\t\t\t\t\"oppGone\": \"true\",\n\t\t\t}\n\t\t\tif err := sendTextMsg(data, p.conn); err != nil {\n\t\t\t\tlog.Println(\"Could not send text msg:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func SendMsg(msgChan chan MessageTask) {\n\tfor {\n\t\tmsgData := <-msgChan\n\t\ttarget, exist := connect.Pool.GetPlayer(msgData.Target)\n\t\tif !exist {\n\t\t\tlog.Println(\"Cannot find player connection: \", msgData.Target)\n\t\t\treturn\n\t\t}\n\t\tnetMsg := message.NetMessage{}\n\t\tmsg, err := json.Marshal(msgData.Msg)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Json encode message failed: \", err)\n\t\t\treturn\n\t\t}\n\t\tnetMsg.MsgName = msgData.Msg.MsgName()\n\t\tnetMsg.Data = string(msg)\n\t\tdata, err := json.Marshal(netMsg)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Encode net message error: \", err)\n\t\t\treturn\n\t\t}\n\t\t_, err = (*target.Conn).Write(data)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Send message failed: \", err)\n\t\t}\n\t}\n}", "func (c *Client) Write(ctx context.Context, chain *Chain) {\n\tticker := time.NewTicker(c.pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(c.writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\t//w.Write(newline)\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(c.writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (gs *Service) writeToSocket(client Client) {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\t_ = client.Conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-client.Send:\n\t\t\t_ = client.Conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\t_ = client.Conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := client.Conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlogger.Info(\"writing message..\")\n\t\t\t_, _ = w.Write(message)\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\t_ = client.Conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := client.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func ws_mainLoop() (err error) {\n\n\tgo func() {\n\t\t<-chSignal\n\t\treturn\n\t}()\n\n\tvar server_url = set.GetServerURL()\n\tif server_url == \"\" {\n\t\tlog.Printf(\"[%s] Server URL Error !! \", __FILE__)\n\t\treturn\n\t}\n\n\tws, err := ws_Server_Connect(server_url)\n\tif err == nil {\n\t\tlog.Printf(\"[%s] ws_Server_Connecet success\", __FILE__)\n\t\tmessages := make(chan string)\n\t\tgo wsReceive(server_url, ws, messages)\n\n\t\tvar send_channel SendChannel\n\t\tsend_channel.containers = make(chan ws_ContainerList_info, 5)\n\t\tsend_channel.updateinfo = make(chan ws_ContainerUpdateReturn, 5)\n\n\t\tgo ws_SendMsg(ws, send_channel)\n\n\t\tvar container_ch Containers_Channel\n\t\tcontainer_ch.receive = make(chan bool)\n\t\tcontainer_ch.send = send_channel.containers\n\n\t\tvar update_ch Update_Channel\n\t\tupdate_ch.receive = make(chan dockzen_h.ContainerUpdateInfo)\n\t\tupdate_ch.send = send_channel.updateinfo\n\n\t\tfor i := 0; i < 3; i++ {\n\t\t\tgo ws_GetContainerLists(container_ch)\n\t\t\tgo ws_UpdateImage(update_ch)\n\t\t}\n\n\t\tvar receive_channel ReceiveChannel\n\t\treceive_channel.containers = container_ch.receive\n\t\treceive_channel.updateinfo = update_ch.receive\n\t\t//go ws_UpdateImage(update_msg, send_channel.updateinfo)\n\n\t\tdefer ws.Close()\n\t\tws_MessageLoop(messages, receive_channel)\n\t}\n\n\tlog.Printf(\"End of ws_mainLoop\")\n\treturn err\n}", "func (c *Connection) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.send)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(<-c.send)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) writePump(g ghess.Board) {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tvar feedback string // For sending info to client\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.write(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// read json from message\n\t\t\tmsg := inCome{}\n\t\t\tjson.Unmarshal([]byte(message), &msg)\n\t\t\tswitch msg.Type {\n\t\t\tcase \"move\":\n\t\t\t\tmv := &outGo{}\n\t\t\t\terr = g.ParseStand(msg.Origin,\n\t\t\t\t\tmsg.Destination)\n\t\t\t\tfen := g.Position()\n\t\t\t\tinfo := g.Stats()\n\t\t\t\tcheck, _ := strconv.ParseBool(info[\"check\"])\n\t\t\t\tcheckmate, _ := strconv.ParseBool(\n\t\t\t\t\tinfo[\"checkmate\"])\n\t\t\t\tif check {\n\t\t\t\t\tfeedback = \"Check!\"\n\t\t\t\t} else if checkmate {\n\t\t\t\t\tfeedback = \"Checkmate!\"\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\tmv = &outGo{\n\t\t\t\t\t\tType: \"move\",\n\t\t\t\t\t\tPosition: fen,\n\t\t\t\t\t\tError: err.Error(),\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tmv = &outGo{\n\t\t\t\t\t\tType: \"move\",\n\t\t\t\t\t\tPosition: fen,\n\t\t\t\t\t\tError: feedback,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfeedback = \"\"\n\t\t\t\t// Marshal into json response\n\t\t\t\tj, _ := json.Marshal(mv)\n\t\t\t\t// Update the DB\n\t\t\t\terr := db.Update(func(tx *bolt.Tx) error {\n\t\t\t\t\tbucket := tx.Bucket([]byte(\"challenges\"))\n\t\t\t\t\terr = bucket.Put([]byte(msg.Id), []byte(fen))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t}\n\t\t\t\t// Write Message to Clien\n\t\t\t\tw.Write([]byte(j))\n\t\t\tcase \"message\":\n\t\t\t\tchat := &outGo{\n\t\t\t\t\tType: \"message\",\n\t\t\t\t\tMessage: msg.Message,\n\t\t\t\t}\n\t\t\t\tj, _ := json.Marshal(chat)\n\t\t\t\tw.Write([]byte(j))\n\t\t\tcase \"connection\":\n\t\t\t\t// Should this be put elsewhere?\n\t\t\t\tchat := &outGo{\n\t\t\t\t\tType: \"connection\",\n\t\t\t\t\tMessage: msg.Message,\n\t\t\t\t}\n\t\t\t\tj, _ := json.Marshal(chat)\n\t\t\t\tw.Write([]byte(j))\n\t\t\t}\n\n\t\t\t// Close the writer\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tif err := c.write(websocket.PingMessage,\n\t\t\t\t[]byte{}); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func ProtoSend(ws *websocket.Conn, msg proto.Message) error {\n\tif ws == nil {\n\t\treturn fmt.Errorf(\"Empty websocket connection\")\n\t}\n\n\tw, err := ws.NextWriter(websocket.BinaryMessage)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() { _ = w.Close() }()\n\n\tdata, err := proto.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = shared.WriteAll(w, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn w.Close()\n}", "func serveWebSocket(w http.ResponseWriter, r *http.Request){\n if r.Method != \"GET\" {\n http.Error(w, \"Method not allowed\", 405)\n return\n }\n ws, err := upgrader.Upgrade(w, r, nil)\n if err != nil {\n log.Println(err)\n return\n }\n c := &Connection{send: make(chan []byte, 256), ws: ws}\n h.register <- c\n go c.writePump()\n c.readPump()\n}", "func (bili *BiliClient) sendJoinChannel(channelID int) error {\n\tbili.uid = rand.Intn(2000000000) + 1000000000\n\tbody := fmt.Sprintf(\"{\\\"roomid\\\":%d,\\\"uid\\\":%d}\", channelID, bili.uid)\n\treturn bili.sendSocketData(0, 16, bili.protocolVersion, 7, 1, body)\n}", "func ClienteWrite(conn net.Conn, ch <-chan string) {\n\tfor msg := range ch {\n\t\tmsgByte := []byte(msg)\n\t\tmsgByteNew := CombinarBytes(IntABytes(len(msgByte)), msgByte)\n\t\tconn.Write(msgByteNew)\n\t}\n}", "func (m *MajsoulChannel) Send(msg []byte) []byte {\n\tm.mutexMsgIndex.Lock()\n\tindex := m.msgIndex\n\tm.msgIndex += 1\n\tm.mutexMsgIndex.Unlock()\n\n\tm.responses[index] = make(chan []byte, 1)\n\n\th1 := make([]byte, 1)\n\th2 := make([]byte, 2)\n\n\th1[0] = byte(MSG_TYPE_REQUEST)\n\tbinary.LittleEndian.PutUint16(h2, index)\n\n\tvar msgBuffer bytes.Buffer\n\tmsgBuffer.Write(h1)\n\tmsgBuffer.Write(h2)\n\tmsgBuffer.Write(msg)\n\n\tm.writeMsg(websocket.BinaryMessage, msgBuffer.Bytes())\n\n\t//Wait for the response to come through the channel\n\tres := <-m.responses[index]\n\treturn res\n}", "func (s *senderQueue) send(incoming []byte) {\n\tdefer s.wg.Done()\n\tdefer s.workers.Release()\n\n\tlogging.Debug(s.logger).Log(logging.MessageKey(), \"Sending message...\")\n\n\terr := s.connection.WriteMessage(websocket.BinaryMessage, incoming)\n\tif err != nil {\n\t\tlogging.Error(s.logger, emperror.Context(err)...).\n\t\t\tLog(logging.MessageKey(), \"Failed to send message\",\n\t\t\t\tlogging.ErrorKey(), err.Error(),\n\t\t\t\t\"msg\", string(incoming))\n\t\treturn\n\t}\n\n\tlogging.Debug(s.logger).Log(logging.MessageKey(), \"Message Sent\")\n}", "func websocketEventLoop(s *state.State) {\n\tfor {\n\t\tdata := <-s.Data\n\t\tfor client := range clients {\n\t\t\t// send data in separate go routine\n\t\t\tgo func(s *state.State, clients map[*websocket.Conn]bool, client *websocket.Conn, data []byte) {\n\t\t\t\terr := client.WriteMessage(websocket.TextMessage, data)\n\t\t\t\tif err != nil {\n\t\t\t\t\ts.Log.Warnln(\"[websocket] error sending message to client\", err)\n\t\t\t\t\tdelete(clients, client)\n\t\t\t\t}\n\t\t\t}(s, clients, client, data)\n\t\t}\n\t}\n}", "func WebsocketChl(hub *Hub, w http.ResponseWriter, r *http.Request) {\n\tclientIP := utils.IPAddress(r)\n\n\tconn, err := Upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tklog.Error(err)\n\t\treturn\n\t}\n\tclient := &Client{Hub: hub, Conn: conn, Send: make(chan []byte, 256), IPAddress: clientIP, Accounts: []string{}}\n\tclient.Hub.Register <- client\n\n\t// Allow collection of memory referenced by the caller by doing all work in\n\t// new goroutines.\n\tgo client.writePump()\n\tgo client.readPump()\n}", "func BroadcastMessageToWebsockets(message MailItemStruct) {\n\tfor connection := range WebsocketConnections {\n\t\tconnection.SendChannel <- message\n\t}\n}", "func (c *Channel) sendToChannel(msg Message) {\n\tfor _, user := range c.users {\n\t\tuser.ChannelOut() <- fmt.Sprintf(\"%s: %s\", msg.client.Nickname()+msg.msg)\n\t}\n}", "func (c *Client) writePump() {\n\tfor {\n\t\tmessage, ok := <-c.send\n\t\tfmt.Println(\"new messsage incoming\")\n\n\t\tif !ok {\n\t\t\t// The hub closed the channel.\n\t\t\tfmt.Println(\"error in message\")\n\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\treturn\n\t\t}\n\n\t\tc.conn.WriteMessage(websocket.TextMessage, message)\n\t\tfmt.Println(\"sent message!\")\n\t}\n}", "func (c *Conn) send(msg *pivo.Message) error {\n\tswitch msg.Type {\n\tcase pivo.IsBinaryMessage:\n\t\treturn c.write(websocket.BinaryMessage, msg.Data)\n\tcase pivo.IsTextMessage:\n\t\t// Default is to send text message\n\t}\n\treturn c.write(websocket.TextMessage, msg.Data)\n}", "func (wc *WSConnection) WriteMsg(ctx context.Context) {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tticker.Stop()\n\t\t\twc.wsConn.Close()\n\t\t\tlogger.Errorf(\"ws soeckt write Routine panic \", string(debug.Stack()))\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-wc.RChan:\n\t\t\tlogger.Infof(\"ws write msg %v \", string(message))\n\t\t\twc.wsConn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// if !ok {\n\t\t\t\t// The input closed the channel.\n\t\t\t\twc.wsConn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := wc.wsConn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(wc.RChan)\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tw.Write(newline)\n\t\t\t\tw.Write(<-wc.RChan)\n\t\t\t}\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\tlogger.Errorf(\"ws write msg close err %v \", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\twc.wsConn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := wc.wsConn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\tlogger.Errorf(\"ws write msg timeout \")\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func handleMessages() {\n\tvar msg node.Message\n\tvar jsonMessage Message\n\tfor {\n\t\tmsg = <-uiChannel\n\t\tjsonMessage.Message = msg.Content\n\t\tjsonMessage.Peer = msg.Peer\n\t\tfor client := range clients {\n\t\t\t// Send message to web application\n\t\t\terr := client.WriteJSON(jsonMessage)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t\tclient.Close()\n\t\t\t\tdelete(clients, client)\n\t\t\t}\n\t\t}\n\t}\n}", "func (b *Board) SendToWebSocket(conn *websocket.Conn) {\n\tfor {\n\t\tif len(b.refereeData) > 0 {\n\t\t\tif err := conn.WriteMessage(websocket.BinaryMessage, b.refereeData); err != nil {\n\t\t\t\tlog.Println(\"Could not write to referee websocket: \", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(b.cfg.SendingInterval)\n\t}\n}", "func (c *HubController) handleServeWs(w http.ResponseWriter, r *http.Request, u *db.User) (int, error) {\n\thubID := chi.URLParam(r, \"id\")\n\n\t// find hub\n\th, err := db.FindHub(c.Conn, hubID)\n\tif err != nil {\n\t\treturn http.StatusBadRequest, terror.New(err, \"\")\n\t}\n\n\tms, err := h.Messages(\n\t\tqm.Load(\n\t\t\tdb.MessageRels.Sender,\n\t\t),\n\t\tqm.Load(\n\t\t\tqm.Rels(\n\t\t\t\tdb.MessageRels.MessageReactions,\n\t\t\t\tdb.MessageReactionRels.Poster,\n\t\t\t),\n\t\t),\n\t).All(c.Conn)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, terror.New(err, \"\")\n\t}\n\n\t// check the hub is in the active hub list\n\tif _, ok := c.HubConns[h.ID]; !ok {\n\t\t// create new hub connection\n\t\tc.HubConns[h.ID] = newHub()\n\t\tgo c.HubConns[h.ID].run()\n\t}\n\n\t// create websocket connection\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, terror.New(err, \"\")\n\t}\n\n\t// set up the client\n\tclient := &Client{\n\t\thub: c.HubConns[h.ID],\n\t\tws: ws,\n\t\tsend: make(chan []byte, 256),\n\t\tclient: NewUser(u, c.BlobURL),\n\t\tdbConn: c.Conn,\n\t\thubID: hubID,\n\t}\n\n\tclient.hub.register <- client\n\n\t// Allow collection of memory referenced by the caller by doing all work in\n\t// new goroutines.\n\tgo client.readPump()\n\tgo client.writePump()\n\n\tresp := []*Message{}\n\n\tfor _, m := range ms {\n\t\trespMsg := &Message{\n\t\t\tMessage: m,\n\t\t\tSender: NewUser(m.R.Sender, c.BlobURL),\n\t\t\tReactions: []*Reaction{},\n\t\t}\n\n\t\tfor _, react := range m.R.MessageReactions {\n\t\t\trespMsg.Reactions = append(respMsg.Reactions, &Reaction{\n\t\t\t\tMessageReaction: react,\n\t\t\t\tPoster: NewUser(react.R.Poster, c.BlobURL),\n\t\t\t})\n\t\t}\n\n\t\tresp = append(resp, respMsg)\n\t}\n\n\tb, err := json.Marshal(resp)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, terror.New(err, \"\")\n\t}\n\n\tclient.send <- b\n\n\t// successfully connected\n\treturn http.StatusOK, nil\n}", "func ws_MessageLoop(messages chan string, receive_channel ReceiveChannel) {\n\n\tfor {\n\t\tmsg := <-messages\n\t\tlog.Printf(\"[%s] MESSAGE !!! \", __FILE__)\n\t\trcv := Command{}\n\t\tjson.Unmarshal([]byte(msg), &rcv)\n\t\tlog.Printf(rcv.Cmd)\n\n\t\tswitch rcv.Cmd {\n\t\tcase \"connected\":\n\t\t\tlog.Printf(\"[%s] connected succefully~~\", __FILE__)\n\t\tcase \"GetContainersInfo\":\n\t\t\treceive_channel.containers <- true\n\t\tcase \"UpdateImage\":\n\t\t\tlog.Printf(\"[%s] command <UpdateImage>\", __FILE__)\n\t\t\tupdate_msg, r := parseUpdateParam(msg)\n\t\t\tif r == nil {\n\t\t\t\treceive_channel.updateinfo <- update_msg\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"[%s] UpdateImage message null !!!\")\n\t\t\t}\n\t\tcase \"err\":\n\t\t\tlog.Printf(\"[%s] Error Case in connection need to recovery\", __FILE__)\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Printf(\"[%s] add command of {%s}\", __FILE__, rcv.Cmd)\n\t\t}\n\n\t}\n}", "func send(w http.ResponseWriter, ch chan int){\r\n\tfor {\r\n\t\tselect {\r\n\t\tcase value := <-ch:\r\n\t\t\tif (value == 1){\r\n\t\t\t\tw.Write([]byte(\"hello http1\"))\r\n\t\t\t\tif f, ok := w.(http.Flusher); ok {\r\n\t\t\t\t\tf.Flush()\r\n\t\t\t\t}\r\n\r\n\t\t\t} else {\r\n\t\t\t\tw.Write([]byte(\"hello http2\"))\r\n\t\t\t\tif f, ok := w.(http.Flusher); ok {\r\n\t\t\t\t\tf.Flush()\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func SendToChannel(msg interface{}, code TaskCode) error {\n\tinitOnce.Do(func() {\n\t\tCh = make(chan map[TaskCode][]byte, 10)\n\t})\n\n\tbytes, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmapData := make(map[TaskCode][]byte)\n\tmapData[code] = bytes\n\tCh <- mapData\n\treturn nil\n}", "func (me *FgClient) WsSendCommand(comm interface{}) error {\n\t//fmt.Println(\"SendCommand\", comm)\n\tif me.WsConn == nil {\n\t\treturn nil\n\t}\n\tbits, err := json.Marshal(comm)\n\tif err != nil {\n\t\tfmt.Println(\"SendCommand.jsonerror\", err)\n\t\treturn err\n\t}\n\t//fmt.Println(\"bits\", string(bits))\n\t// TODO catch\n\tif _, err := me.WsConn.Write(bits); err != nil {\n\t\t//log.Fatal(err)\n\t\tfmt.Println(\"written\", err)\n\t}\n\treturn nil\n}", "func serveWs(w http.ResponseWriter, req *http.Request) {\n\tfmt.Println(\"Registering client to WS\")\n\tif req.Method != \"GET\" {\n\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\treturn\n\t}\n\tws, err := upgrader.Upgrade(w, req, nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error %+v\\n\", err)\n\t\treturn\n\t}\n\tc := &connection{send: make(chan []byte, 256), ws: ws}\n\th.register <- c\n\tgo c.writePump()\n}", "func serveWs(b *broker, w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Fatalln(\"init websocket conn error.\", err)\n\t}\n\n\tag := &agent{b: b, conn: conn, agentCh: make(chan *message, 256)}\n\tagentID := uuid.NewV4().String()\n\n\t// build map to register agent\n\treg := make(map[string]*agent)\n\treg[agentID] = ag\n\tlog.Printf(\"register agent to broker. agentID=%s, agent=%v\", agentID, ag)\n\tb.register <- reg\n\n\t// one goroutine to handle communication between agent to remote client, and broker\n\tgo ag.start()\n}", "func (c *Client) WritePump() {\n\n\tticker := time.NewTicker(pingPeriod)\n\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.Conn.Close()\n\t}()\n\n\t// for i := 0; i < {\n\n\t// \tbreak\n\t// }\n\n\tfor {\n\n\t\tselect {\n\t\tcase message, ok := <-c.Send:\n\t\t\tc.Conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.Conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.Conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\tn := len(c.Send)\n\n\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\tnewMessage := <-c.Send\n\t\t\t\tw.Write(newMessage)\n\t\t\t}\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.Conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func ServeWs(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif err := r.ParseForm(); err != nil {\n\t\tlog.Errorln(\"error parsing form on websocket serve, err:\", err)\n\t}\n\n\tcookie := model.CookieDetail{CookieName: values.UserCookieName, Collection: values.UsersCollectionName}\n\n\tif err := cookie.CheckCookie(r); err != nil {\n\t\tws, err := model.Upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tlog.Errorln(\"error upgrading websocket while sending error message, err: \", err)\n\t\t\treturn\n\t\t}\n\n\t\tif err := ws.WriteJSON(struct {\n\t\t\tMessageType string `json:\"msgType\"`\n\t\t}{\n\t\t\tvalues.UnauthorizedAcces,\n\t\t}); err != nil {\n\t\t\tlog.Errorln(\"could not send unauthorized message to user, err:\", err)\n\t\t}\n\n\t\tif err := ws.Close(); err != nil {\n\t\t\tlog.Errorln(\"error closing websocket on unauthorized access, err:\", err)\n\t\t}\n\n\t\treturn\n\t}\n\n\tws, err := model.Upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Errorln(\"error upgrading websocket, err:\", err)\n\t\treturn\n\t}\n\tmodel.HubConstruct.RegisterWS(ws, cookie.Email)\n}", "func (c *Client) writePump() {\n\tc.log.Trace(\"writePump\")\n\tticker := time.NewTicker(c.hub.options.PingPeriod)\n\tdefer func() {\n\t\tc.log.Trace(\"writePump closed\")\n\t\tif err := recover(); err != nil {\n\t\t\tif er, ok := err.(error); ok {\n\t\t\t\tc.log.Error(\"writePump error. \" + er.Error())\n\t\t\t}\n\t\t\tdebug.PrintStack()\n\t\t}\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(c.hub.options.WriteTimeout))\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\tc.log.Error(\"writePump - get NextWriter error:\" + err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\t_, err = w.Write(message)\n\t\t\tif err != nil {\n\t\t\t\tc.log.Error(\"writePump - write msg error:\" + err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Add queued chat messages to the current websocket message.\n\t\t\t// n := len(c.send)\n\t\t\t// for i := 0; i < n; i++ {\n\t\t\t// \t// w.Write(newline)\n\t\t\t// \t_, err = w.Write(<-c.send)\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tc.log.Error(\"writePump - write msg error:\" + err.Error())\n\t\t\t// \t}\n\t\t\t// }\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\tc.log.Error(\"writePump - writer close failed. error:\" + err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(c.hub.options.WriteTimeout))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *ConnManager) SendMulti(keys []string, msg interface{}) {\n\tfor _, k := range keys {\n\t\tv, ok := m.Get(k)\n\t\tif ok {\n\t\t\tif conn, ok := v.(*websocket.Conn); ok {\n\t\t\t\tif err := websocket.JSON.Send(conn, msg); err != nil {\n\t\t\t\t\tfmt.Println(\"Send msg error: \", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"invalid type, expect *websocket.Conn\")\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"connection not exist\")\n\t\t}\n\t}\n}", "func (c *Client) sendMessage(message []byte, ok bool) {\n\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\tif !ok {\n\t\t// The service closed the channel.\n\t\tc.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\treturn\n\t}\n\n\tw, err := c.conn.NextWriter(websocket.TextMessage)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tw.Write(message)\n\n\tif err := w.Close(); nil != err {\n\t\treturn\n\t}\n}", "func SendMsg(j string, t string, d string, c *websocket.Conn) {\n\tm := procondata.Msg{j, t, d}\n\n\tif err := c.WriteJSON(m); err != nil {\n\t\tfmt.Println(\"Error writing Json in utils.go\", err)\n\t}\n}", "func wsHandler(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tchannel := params[\"channel\"]\n\tclientServer := params[\"clientServer\"]\n\n\tvar fromServer bool\n\n\tswitch clientServer {\n\tcase \"client\":\n\t\tfromServer = false\n\tcase \"server\":\n\t\tfromServer = true\n\tdefault:\n\t\thttp.Error(w, \"bad path not /x/client or /x/server\", http.StatusNotFound)\n\t\treturn\n\n\t}\n\n\tupgraderMutex.Lock()\n\tc, err := upgrader.Upgrade(w, r, nil)\n\tupgraderMutex.Unlock()\n\tcheck(err)\n\tdefer func() {\n\t\tcheck(c.Close())\n\t}()\n\n\tconnections[key{channel, fromServer}] = connection{myconn: c, paired: nil}\n\n\tglog.Warningln(\"connection from \", c.RemoteAddr())\n\n\tfor {\n\t\tmtype, msg, err := c.ReadMessage()\n\t\tif websocket.IsCloseError(err) {\n\t\t\tglog.Warningln(\"remote conn closed, dropping off\")\n\t\t\treturn\n\t\t}\n\t\tcheck(err)\n\n\t\tmessages <- message{channel, mtype, msg, fromServer, c}\n\t}\n}", "func ServeWs(user string, hub *Hub, w http.ResponseWriter, r *http.Request) {\n\th := http.Header{}\n\tpro := r.Header.Get(\"Sec-WebSocket-Protocol\")\n\th.Add(\"Sec-WebSocket-Protocol\", pro) //带有websocket的Protocol子header需要传入对应header,不然会有1006错误\n\tconn, err := upgrader.Upgrade(w, r, h) //返回一个websocket连接\n\tif err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\"connect\": err}).Info(\"websocket\")\n\t\treturn\n\t}\n\t//生成一个client,里面包含用户信息连接信息等信息\n\tclient := &Client{hub: hub, name: user, conn: conn, send: make(chan []byte, 256)}\n\tclient.hub.register <- client //将这个连接放入注册,在run中会加一个\n\tgo client.writePump() //新开一个写入,因为有一个用户连接就新开一个,相互不影响,在内部实现心跳包检测连接,详细看函数内部\n\tclient.readPump() //读取websocket中的信息,详细看函数内部\n\n}", "func (conn *Connection) WriteConn(parent context.Context, wsc config.WebSocketSettings, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tif conn.done() {\n\t\treturn\n\t}\n\tconn.wGroup.Add(1)\n\tdefer func() {\n\t\tconn.wGroup.Done()\n\t\tutils.CatchPanic(\"connection.go WriteConn()\")\n\t}()\n\n\tticker := time.NewTicker(wsc.PingPeriod)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-parent.Done():\n\t\t\tfmt.Println(\"WriteConn done catched\")\n\t\t\treturn\n\t\tcase message, ok := <-conn.send:\n\n\t\t\t//fmt.Println(\"saw!\")\n\t\t\t//fmt.Println(\"server wrote:\", string(message))\n\t\t\tif !ok {\n\t\t\t\t//fmt.Println(\"errrrrr!\")\n\t\t\t\tconn.write(websocket.CloseMessage, []byte{}, wsc)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tstr := string(message)\n\t\t\tvar start, end, counter int\n\t\t\tfor i, s := range str {\n\t\t\t\tif s == '\"' {\n\t\t\t\t\tcounter++\n\t\t\t\t\tif counter == 3 {\n\t\t\t\t\t\tstart = i + 1\n\t\t\t\t\t} else if counter == 4 {\n\t\t\t\t\t\tend = i\n\t\t\t\t\t} else if counter > 4 {\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 start != end {\n\t\t\t\tprint := str[start:end]\n\t\t\t\t//print = str\n\t\t\t\tfmt.Println(\"#\", conn.ID(), \" get that:\", print)\n\t\t\t}\n\n\t\t\tconn.ws.SetWriteDeadline(time.Now().Add(wsc.WriteWait))\n\t\t\tw, err := conn.ws.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tif err := conn.write(websocket.PingMessage, []byte{}, wsc); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func mapClients() {\n\t// This variable has the count of number of Connections\n\tclientConnectionNumber := 0\n\t// This variable maps count with client connection\n\tvar clientConnectionsMap = make(map[int]*websocket.Conn)\n\t//Sending pings to client websites\n\tticker := time.NewTicker(20 * time.Second)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\t// If a new connection is avaialble the add it to the map\n\t\tcase newClientConnection := <-clientConnections:\n\t\t\t{\n\t\t\t\tclientConnectionsMap[clientConnectionNumber] = newClientConnection\n\t\t\t\tclientConnectionNumber++\n\t\t\t\tfmt.Println(\"New Client Added :: Number : \", clientConnectionNumber, \"Length :: \", len(clientConnectionsMap))\n\t\t\t\tnewWebConnection <- 1\n\n\t\t\t}\n\t\t// if a connection has to be deleted from the map variable\n\t\tcase deleteClientConnection := <-deleteClientConnection:\n\t\t\t{\n\t\t\t\tfor index, conn := range clientConnectionsMap {\n\t\t\t\t\tif conn == deleteClientConnection {\n\t\t\t\t\t\tdelete(clientConnectionsMap, index)\n\t\t\t\t\t\tfmt.Println(\"Old Client Deleted :: Number : \", clientConnectionNumber, \", Index :: \", index, \", Length :: \", len(clientConnectionsMap))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// forward data coming from edge directly to web without db\n\t\tcase msg := <-dataToWeb:\n\t\t\t{\n\t\t\t\tfmt.Println(\"Data - \", msg)\n\t\t\t\tfor _, conn := range clientConnectionsMap {\n\t\t\t\t\t//\tif msg.Id != 0 && msg.Data != 0 {\n\t\t\t\t\tif msg.Id != 0 {\n\t\t\t\t\t\terr := conn.WriteJSON(msg)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//// Maintains Constant Ping with Websites's Websocket\n\t\tcase <-ticker.C:\n\t\t\t{\n\n\t\t\t\tfor _, conn := range clientConnectionsMap {\n\n\t\t\t\t\terr := conn.WriteMessage(websocket.PingMessage, []byte{})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"Websocket ping fail\", runtime.NumGoroutine())\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Println(\"Successful Ping to web \")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (hub *Hub) ServeWS(w http.ResponseWriter, r *http.Request) {\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tclient := &Client{hub: hub, conn: conn, send: make(chan []byte, maxSendQueue), id: uuid.NewV4()}\n\tclient.hub.conn <- client\n\n\tgo client.WriteMessage()\n\tgo client.ReadMessage()\n\n\t//hub.rpc.channel.Close()\n\t//hub.rpc.conn.Close()\n}", "func (s *Server) SendToChannels(e Event, d EventDefinition) {\n for _, v := range d.Channels {\n ch, err := s.FindChannel(v)\n\n if err != nil {\n s.GM.Log.Errorf(\"Unable to find channel %s - Cannot send event %+v\", v, e)\n continue\n }\n\n ch.Send(e, d)\n }\n}", "func (h *Hub) run() {\n\tfor {\n\t\tselect {\n\t\tcase client := <-h.register:\n\t\t\th.clients[client] = true\n\t\tcase client := <-h.unregister:\n\t\t\tif _, ok := h.clients[client]; ok {\n\t\t\t\tdelete(h.clients, client)\n\t\t\t\tclose(client.send)\n\t\t\t}\n\t\tcase message := <-h.broadcast:\n\t\t\tfor client := range h.clients {\n\t\t\t\tselect {\n\t\t\t\tcase client.send <- message:\n\t\t\t\tdefault:\n\t\t\t\t\tclose(client.send)\n\t\t\t\t\tdelete(h.clients, client)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *server) sendState() {\n\tfor _, c := range s.clients {\n\t\tbuf := &bytes.Buffer{}\n\t\tenc := json.NewEncoder(buf)\n\t\tenc.SetIndent(\"\", \" \")\n\t\ts.game.state()\n\t\tps, _ := s.playerState(c.playerID)\n\t\terr := enc.Encode(ps)\n\t\tif err != nil {\n\t\t\tlog.Println(\"sendState encoding error:\", err)\n\t\t}\n\t\tb := buf.Bytes()\n\t\tc.messages <- b\n\t}\n}", "func (nc *NetClient) send() {\n\terrored := false\n\tfor {\n\t\tselect {\n\t\tcase protoMessage := <-nc.Composer.sendChan:\n\t\t\terr := nc.ReadWriteCloser.Write(protoMessage)\n\t\t\tif !errored && err != nil {\n\t\t\t\terrored = true\n\t\t\t\tlog.Println(\"Error writing to server:\", err)\n\t\t\t\tgo nc.Disconnect()\n\t\t\t} else if errored {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase <-nc.pingServer:\n\t\t\t// query for the root message\n\t\t\troot, _ := nc.Archive.Root()\n\t\t\tgo nc.Composer.Query(root)\n\t\t\tgo nc.Composer.AskWho()\n\t\tcase <-nc.stopSending:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *Client) writePump() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tlog.Println(\"Closing write pump\", c.id)\n\t\tticker.Stop()\n\t\tc.ws.Close()\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tif !ok {\n\t\t\t\t// The hub closed the channel.\n\t\t\t\tlog.Println(\"Hub closed channel\", c.id)\n\t\t\t\tc.write(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Println(\"Writing message\", c.id)\n\t\t\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.ws.WriteJSON(message); err != nil {\n\t\t\t\tlog.Println(\"Error writing message\", c.id, err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tlog.Println(\"Tick\", c.id)\n\t\t\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.write(websocket.PingMessage, []byte{}); err != nil {\n\t\t\t\tlog.Println(\"Could not ping client\", c.id)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func send(g *gocui.Gui, v *gocui.View) error {\n\tmsg := chatmessage.Chatmessage{\n\t\tText: v.Buffer(),\n\t\tFrom: nickname,\n\t}\n\n\t// Get the top window view and write the buffer of the bottom window view to it\n\tif m, err := g.View(\"messages\"); err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tif len(msg.Text) != 0 {\n\t\t\tm.Write([]byte(\" \" + msg.From + \": \" + msg.Text))\n\t\t}\n\t}\n\n\t// Clear the bottom window and reset the cursor\n\tv.Clear()\n\tif err := v.SetCursor(0, 0); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Send message to other clients\n\n\treturn nil\n}", "func (hub *Hub) Run() () {\n\tfor {\n\t\tselect {\n\t\t\tcase conn := <- hub.Register:\n\t\t\t\tif oldConn, ok := hub.Clients[conn.Id]; ok {\n\t\t\t\t\t_ = oldConn.Conn.Close()\n\t\t\t\t}\n\t\t\t\thub.Clients[conn.Id] = conn\n\t\t\t\tfmt.Println(\"registering a client \" + conn.Id)\n\n\t\t\tcase conn := <- hub.Unregister:\n\t\t\t\tif oldConn, ok := hub.Clients[conn.Id]; ok {\n\t\t\t\t\t_ = oldConn.Conn.Close()\n\t\t\t\t}\n\n\t\t\tcase messageToSend := <- hub.Broadcast:\n\t\t\t\t/*\n\t\t\t\t\tfirst look for the client connection from the dictionary\n\t\t\t\t\tif there is such connection send to the user\n\t\t\t\t */\n\t\t\t\tif conn, ok := hub.Clients[messageToSend.ReceiverId]; ok {\n\t\t\t\t\t/*\n\t\t\t\t\t\tconvert the message to byte and send byte to the receiver connection\n\t\t\t\t\t */\n\t\t\t\t\tif messageByte, err := messageToSend.ConvertToByte(); err != nil {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\t\tcase conn.Send <- messageByte:\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\tthis means, an error has occurred while sending a message\n\t\t\t\t\t\t\t\t\t\twhich indicates that the client connection is no more valid\n\t\t\t\t\t\t\t\t\t\tthen remove it from the dictionary\n\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t\tclose(conn.Send)\n\t\t\t\t\t\t\t\tdelete(hub.Clients, conn.Id)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) ClientWriter(sendSignal chan []byte) {\n\tlog.Println(\"WS writer started:\", c.Ip)\n\tlog.Println(\"Ping ticker duration:\", c.PingPeriod)\n\tpingTicker := time.NewTicker(time.Duration(c.PingPeriod) * time.Second)\n\tdefer func () {\n\t\tpingTicker.Stop()\n\t\tc.Conn.Close()\n\t} ()\n\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-sendSignal:\n\t\t\tc.Conn.SetWriteDeadline(time.Now().Add(time.Duration(c.WriteWait) * time.Second))\n\t\t\tif !ok {\n\t\t\t\t// If send channel is closed, close websocket\n\t\t\t\tc.Conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw, err := c.Conn.NextWriter(websocket.TextMessage)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"WS write error in client: \", c.Conn.RemoteAddr())\n\t\t\t\tlog.Println(\"Unable to send msg through socket: \", err)\n\t\t\t\t//c.isActive = false\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(message)\n\t\t\tlog.Println(\"Signal sent!\")\n\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\tlog.Println(\"Error closing WS write\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase <-pingTicker.C:\n\t\t\t// Send ping to client\n\t\t\tlog.Println(\"Sending PING to client\")\n\t\t\tc.Conn.SetWriteDeadline(time.Now().Add(time.Duration(c.WriteWait) * time.Second))\n\t\t\tif err := c.Conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {\n\t\t\t\tlog.Println(\"Unable to send PING message:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func (ws *WS) Connect(send, receive chan *RawMessage, stop chan bool) error {\n\turl, err := ws.getWebsocketURL(false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"ws Connect:\", url)\n\n\tconn, _, err := websocket.DefaultDialer.Dial(url, http.Header{\n\t\t// Origin is important, it won't connect otherwise\n\t\t\"Origin\": {\"https://6obcy.org\"},\n\t\t// User-Agent can be ommited, but we want to look legit\n\t\t\"User-Agent\": {\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36\"},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tdoneCh := make(chan bool)\n\tsetupCh := make(chan *setupMessage)\n\n\t// start recv goroutine\n\tgo func() {\n\t\tinitialized := false\n\t\tdefer close(doneCh)\n\t\tfor {\n\t\t\tmsgType, msgBytes, err := conn.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to read:\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tprefix, msg := rawToTypeAndJSON(msgBytes)\n\t\t\tif !initialized {\n\t\t\t\tif prefix == setup {\n\t\t\t\t\tsm := &setupMessage{}\n\t\t\t\t\terr := json.Unmarshal([]byte(msg), sm)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"Failed to parse setup message %s %s\\n\", err, msg)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tsetupCh <- sm\n\t\t\t\t\tinitialized = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif prefix == pong {\n\t\t\t\tif ws.Debug {\n\t\t\t\t\tfmt.Println(\"pong\")\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ws.Debug {\n\t\t\t\tfmt.Println(\"ws ->:\", string(msgBytes))\n\t\t\t}\n\n\t\t\treceive <- &RawMessage{\n\t\t\t\tType: msgType,\n\t\t\t\tPayload: msgBytes,\n\t\t\t}\n\t\t}\n\t}()\n\n\t// start send goroutine\n\tgo func() {\n\t\tfor {\n\t\t\trm := <-send\n\n\t\t\tif rm == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ws.Debug {\n\t\t\t\tfmt.Println(\"ws <-:\", string(rm.Payload))\n\t\t\t}\n\n\t\t\terr := conn.WriteMessage(rm.Type, rm.Payload)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to write:\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar setupMsg *setupMessage\n\n\tselect {\n\tcase sm := <-setupCh:\n\t\tsetupMsg = sm\n\tcase <-time.After(5 * time.Second):\n\t\tlog.Println(\"Waited 5 seconds for setup message\")\n\t}\n\n\t// create a ticker and take care of sending pings\n\tticker := time.NewTicker(time.Millisecond * time.Duration(setupMsg.PingInterval))\n\tdefer ticker.Stop()\n\n\t// start main ws goroutine\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif ws.Debug {\n\t\t\t\tfmt.Println(\"ping\")\n\t\t\t}\n\t\t\terr := conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(\"%d\", ping)))\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to ping\", err)\n\t\t\t}\n\t\tcase <-stop:\n\t\t\terr := conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, \"\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"write close:\", err)\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-doneCh:\n\t\t\tcase <-time.After(time.Second):\n\t\t\t}\n\t\t\tstop <- true\n\t\t\treturn nil\n\t\tcase <-doneCh:\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func message(w http.ResponseWriter, r *http.Request) {\n\tvar rBody request\n\n\tif err := json.NewDecoder(r.Body).Decode(&rBody); err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to decode message\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tc, err := models.GetConnectionWithRecipients(rBody.ConnectionID)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to get connection\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdbMsg := &models.Message{\n\t\tConnectionID: rBody.ConnectionID,\n\t\tMessage: rBody.Text,\n\t\tSourceUser: *c.SourceUser,\n\t\tSourceUserID: c.SourceUserID,\n\t\tDestinationUserID: c.DestinationUserID,\n\t\tChannel: rBody.Channel,\n\t}\n\n\tif err := dbMsg.Save(); err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to save message. \", err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tcMsg := models.ChannelMessage{\n\t\tID: int(dbMsg.ID),\n\t\tCreatedAt: dbMsg.CreatedAt,\n\t\tMessage: dbMsg.Message,\n\t\tReadBy: dbMsg.ReadBy,\n\t\tUser: rBody.User,\n\t}\n\n\tpayload := pubMessage{\n\t\t// populate embedded struct (promoted fields)\n\t\tdefaultProperties: defaultProperties{\n\t\t\tChannel: rBody.Channel,\n\t\t\tType: rBody.Type,\n\t\t\tSubType: rBody.SubType,\n\t\t},\n\t\tChannelMessage: cMsg,\n\t}\n\n\t// prep for ws\n\tbytes, err := json.Marshal(payload)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Unable to marshal chat message\", err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpubMessage := hub.PublishMessage{\n\t\tTopic: rBody.Channel,\n\t\tPayload: bytes,\n\t}\n\n\tbroker.Hub.Publish(pubMessage)\n\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func sendMessageAll(conn net.Conn, mess string) {\n\tfor key := range connMap {\n\t\tif connMap[key] != conn {\n\t\t\tconnMap[key].Write([]byte(\"TCCHAT_BCAST\\t\" + userMap[conn] + \"\\t\" + mess + \"\\n\"))\n\t\t}\n\t}\n}" ]
[ "0.74745584", "0.7103419", "0.67399025", "0.6642084", "0.65906745", "0.6417173", "0.63003063", "0.6281131", "0.6261049", "0.6223444", "0.61551064", "0.6148204", "0.6134059", "0.6101055", "0.60894996", "0.60782266", "0.60752773", "0.6044252", "0.6042677", "0.6040374", "0.6039484", "0.6011933", "0.6011184", "0.59490955", "0.59453464", "0.59447384", "0.59372604", "0.59304583", "0.59172153", "0.59167075", "0.5914011", "0.5908695", "0.59058875", "0.59002537", "0.58980465", "0.5881455", "0.5866448", "0.5863594", "0.58567774", "0.58541876", "0.5851393", "0.58501554", "0.5847962", "0.5831696", "0.58313817", "0.581201", "0.5809471", "0.58053505", "0.58011377", "0.57927305", "0.5773589", "0.5769851", "0.57612056", "0.5758861", "0.5747495", "0.57436204", "0.5737302", "0.5716504", "0.5712922", "0.57114124", "0.57064784", "0.5704771", "0.57027274", "0.5698621", "0.5695999", "0.5689506", "0.5686819", "0.56848025", "0.56828266", "0.56801695", "0.5673108", "0.56613946", "0.5654799", "0.5651744", "0.56500167", "0.56455255", "0.56390285", "0.56385386", "0.5636744", "0.5631175", "0.5631118", "0.5630362", "0.5629229", "0.5618288", "0.561458", "0.56118333", "0.561073", "0.5597896", "0.5586897", "0.5584134", "0.55816984", "0.5568395", "0.556768", "0.55556345", "0.55487394", "0.55481315", "0.5548038", "0.55466527", "0.55404466", "0.5540245" ]
0.77143115
0
Bootstrap registers extensions and startup system services.
func (b *Bootstrap) Bootstrap(hostname string) error { log.Infof("Mounting proc") if err := syscall.Mount("none", "/proc", "proc", 0, ""); err != nil { return err } if err := syscall.Mount("none", "/dev", "devtmpfs", 0, ""); err != nil { return err } if err := syscall.Mount("none", "/dev/pts", "devpts", 0, ""); err != nil { return err } if err := updateHostname(hostname); err != nil { return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b Bootstrapper) Bootstrap(ctx map[string]interface{}) error {\n\tdocSrv, ok := ctx[documents.BootstrappedDocumentService].(documents.Service)\n\tif !ok {\n\t\treturn errors.New(\"failed to get %s\", documents.BootstrappedDocumentService)\n\t}\n\n\tjobsMan, ok := ctx[jobs.BootstrappedService].(jobs.Manager)\n\tif !ok {\n\t\treturn errors.New(\"failed to get %s\", jobs.BootstrappedService)\n\t}\n\n\tnftSrv, ok := ctx[bootstrap.BootstrappedNFTService].(nft.Service)\n\tif !ok {\n\t\treturn errors.New(\"failed to get %s\", bootstrap.BootstrappedNFTService)\n\t}\n\n\taccountSrv, ok := ctx[config.BootstrappedConfigStorage].(config.Service)\n\tif !ok {\n\t\treturn errors.New(\"failed to get %s\", config.BootstrappedConfigStorage)\n\t}\n\n\tctx[BootstrappedCoreAPIService] = Service{\n\t\tdocSrv: docSrv,\n\t\tjobsSrv: jobsMan,\n\t\tnftSrv: nftSrv,\n\t\taccountsSrv: accountSrv,\n\t}\n\treturn nil\n}", "func (Bootstrapper) Bootstrap(ctx map[string]interface{}) error {\n\tdocService, ok := ctx[documents.BootstrappedDocumentService].(documents.Service)\n\tif !ok {\n\t\treturn errors.New(\"document service not initialized\")\n\t}\n\n\tidService, ok := ctx[identity.BootstrappedDIDService].(identity.Service)\n\tif !ok {\n\t\treturn errors.New(\"identity service not initialised\")\n\t}\n\n\tqueueSrv, ok := ctx[bootstrap.BootstrappedQueueServer].(queue.TaskQueuer)\n\tif !ok {\n\t\treturn errors.New(\"queue hasn't been initialized\")\n\t}\n\n\tjobManager, ok := ctx[jobs.BootstrappedService].(jobs.Manager)\n\tif !ok {\n\t\treturn errors.New(\"transactions repository not initialised\")\n\t}\n\n\tclient := ethereum.GetClient()\n\toracleSrv := newService(\n\t\tdocService,\n\t\tidService,\n\t\tclient,\n\t\tqueueSrv,\n\t\tjobManager)\n\tctx[BootstrappedOracleService] = oracleSrv\n\treturn nil\n}", "func (b *MyBootstrapper) Bootstrap() error {\n\tinitDaos()\n\tinitApiHandlers(goapi.ApiRouter)\n\treturn nil\n}", "func bootstrap() error {\n\tglog.Info(settings.PATROL_LOGO)\n\tif settings.DEBUG {\n\t\tglog.Infof(\"patrol: running in %s mode.\", alertcolor(\"DEBUG\"))\n\t}\n\n\t// list of patrol builtin plugins to register\n\tplugins := []core.Pluginer{\n\t\tplugins.NewCommonPlugin(Context, pluginRegistry),\n\t\tplugins.NewAuthPlugin(Context, pluginRegistry),\n\t\tplugins.NewEventsPlugin(Context, pluginRegistry),\n\t\tplugins.NewProjectsPlugin(Context),\n\t\tplugins.NewTeamsPlugin(Context),\n\t\tplugins.NewStaticPlugin(Context, pluginRegistry),\n\t\tplugins.NewRealtimePlugin(Context, pluginRegistry),\n\t}\n\tfor _, p := range plugins {\n\t\tif err := pluginRegistry.RegisterPlugin(p); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// add core plugin ids to RESTRICTED_PLUGIN_IDS\n\t\tsettings.RESTRICTED_PLUGIN_IDS = append(settings.RESTRICTED_PLUGIN_IDS, p.ID())\n\t}\n\n\treturn nil\n}", "func Bootstrap() (*cobra.Command, func()) {\n\tvar cfg string\n\n\t// Get root command\n\troot := cmd.NewRootCmd()\n\n\t// Determine config path from commandline\n\troot.PersistentFlags().StringVar(&cfg, \"config\", \"./config.yaml\", \"config file\")\n\t_ = root.PersistentFlags().Parse(os.Args[1:])\n\n\t// Setup core with config path\n\tc := core.Default(core.WithYamlFile(cfg))\n\n\t// Setup global dependencies and register modules\n\tfor _, option := range config.Register() {\n\t\toption(c)\n\t}\n\n\t// Apply root command and register commands from modules\n\tc.ApplyRootCommand(root)\n\n\treturn root, func() {\n\t\tc.Shutdown()\n\t}\n}", "func Bootstrap() {\n\terr := env.Load(\".env\")\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading .env file\", err)\n\t\tos.Exit(1)\n\t}\n\n\ti18n.MustLoadTranslationFile(\"resources/lang/en-US.yaml\")\n\n\trouterInstance = initRouter()\n}", "func (this *RouteServiceProvider) Boot() {\n\tthis.loadRoutes()\n\n\tthis.App.Booted(func(app interface{}) {\n\t\tthis.App.Make(\"router\").(*Routing.Router).GetRoutes().RefreshNameLookups()\n\t})\n}", "func BootStrap() {\n\tlog.Info(\"Bootstrapping models\")\n\tmodelRegistry.Lock()\n\tdefer modelRegistry.Unlock()\n\n\tmodelRegistry.bootstrapped = true\n\n\tcreateModelLinks()\n\tinflateInherits()\n\tsyncRelatedFieldInfo()\n\tsyncDatabase()\n\tbootStrapMethods()\n\tprocessDepends()\n}", "func init() {\n\tcore.RegisterConfigGroup(defaultConfigs)\n\tcore.RegisterServiceWithConfig(\"api\", &api.ApiServiceFactory{}, api.Configs)\n\tcore.RegisterServiceWithConfig(\"collector\", &collector.CollectorServiceFactory{}, collector.Configs)\n}", "func (r bootProviders) Bootstrap(container inter.Container) inter.Container {\n\tfor _, bootstrapper := range providers.Providers.BootProviders {\n\t\tcontainer = bootstrapper.Boot(container)\n\t}\n\n\treturn container\n}", "func (b *Bootstrapper) bootstrap() *Bootstrapper {\n\t// All error handlers\n\tb.setupErrorHandlers()\n\n\t// Adding middlewares\n\tmiddlewares.Wrap(b.Application)\n\n\t// Controllers bootstrap\n\tcontrollers.WithRouter(b.Application)\n\n\t// Gracefully handle shutdown\n\tgo b.gracefulShutdown(b.Application)\n\n\treturn b\n}", "func Start(bootstrappers ...IBootstrapper) {\n\tvar err error\n\n\t// load application configurations\n\tAppConfig = initAppConfig()\n\thttpHeaderAppId = AppConfig.GetString(\"api.http.header_app_id\")\n\thttpHeaderAccessToken = AppConfig.GetString(\"api.http.header_access_token\")\n\tAppVersion = AppConfig.GetString(\"app.version\")\n\tAppVersionNumber = utils.VersionToNumber(AppVersion)\n\n\t// setup api-router\n\tApiRouter = itineris.NewApiRouter()\n\n\t// initialize \"Location\"\n\tutils.Location, err = time.LoadLocation(AppConfig.GetString(\"timezone\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// bootstrapping\n\tif bootstrappers != nil {\n\t\tfor _, b := range bootstrappers {\n\t\t\tlog.Println(\"Bootstrapping\", b)\n\t\t\terr := b.Bootstrap()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// initialize and start gRPC server\n\tinitGrpcServer()\n\n\t// initialize and start echo server\n\tinitEchoServer()\n}", "func RegisterExtensions(sys *gohome.System) error {\n\tlog.V(\"registering extensions\")\n\n\tlog.V(\"register extension - belkin\")\n\tsys.Extensions.Register(belkin.NewExtension())\n\n\tlog.V(\"register extension - connectedbytcp\")\n\tsys.Extensions.Register(connectedbytcp.NewExtension())\n\n\tlog.V(\"register extension - fluxwifi\")\n\tsys.Extensions.Register(fluxwifi.NewExtension())\n\n\tlog.V(\"register extension - honeywell\")\n\tsys.Extensions.Register(honeywell.NewExtension())\n\n\tlog.V(\"register extension - lutron\")\n\tsys.Extensions.Register(lutron.NewExtension())\n\n\t/*\n\t\t// An example piece of hardware\n\t\tlog.V(\"register extension - example\")\n\t\tsys.Extensions.Register(example.NewExtension())\n\t*/\n\n\t//Uncomment for testing\n\tlog.V(\"register extension - testing\")\n\tsys.Extensions.Register(testing.NewExtension())\n\n\treturn nil\n}", "func StartUp() {\n\t// Initialize AppConfig variable\n\tinitConfig()\n}", "func bootstrap() Config {\n\tconfig := NewConfig()\n\n\t// Load configuration etc\n\tif !service.Bootstrap(&config) {\n\t\tos.Exit(0)\n\t}\n\n\treturn config\n}", "func (g Glados) Boot() {\n\tlogger := g.context.Logger()\n\tlogger.Infoln(\"Glados: Boot..\")\n\tdefer logger.Infoln(\"Glados: Shutdown..\")\n\tport := g.context.ListenPort()\n\tg.context.Router().RunWithPort(port)\n}", "func init() {\n\tconsul.Register()\n\tetcd.Register()\n\tzookeeper.Register()\n\tboltdb.Register()\n}", "func main() {\n\tfmt.Println(\"APPLICATION BEGIN\")\n\twebserver := new(service.Webserver)\n\tregisterConfig()\n\tregisterErrors()\n\tregisterAllApis()\n\tregisterInitFunc()\n\toverrideConfByEnvVariables()\n\twebserver.Start()\n}", "func (am AppModule) RegisterServices(cfg module.Configurator) {\n\ttypes.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper))\n\ttypes.RegisterQueryServer(cfg.QueryServer(), keeper.NewQuerier(am.keeper))\n\n\tm := keeper.NewMigrator(am.keeper, am.legacySubspace)\n\tif err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to migrate x/%s from version 1 to 2: %v\", types.ModuleName, err))\n\t}\n\n\tif err := cfg.RegisterMigration(types.ModuleName, 2, m.Migrate2to3); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to migrate x/%s from version 2 to 3: %v\", types.ModuleName, err))\n\t}\n\n\tif err := cfg.RegisterMigration(types.ModuleName, 3, m.Migrate3to4); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to migrate x/%s from version 3 to 4: %v\", types.ModuleName, err))\n\t}\n}", "func (c *Console) Bootstrap() (err error) {\n\taddrFile := filepath.Join(c.TempDir, \"console.serviced.txt\")\n\taddrBytes, err := ioutil.ReadFile(addrFile)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"readd console address from %v fail with %v\", addrFile, err)\n\t\treturn\n\t}\n\terr = c.Dial(string(addrBytes))\n\treturn\n}", "func (am AppModule) RegisterServices(cfg module.Configurator) {\n}", "func (srv *Server) Bootstrap(conf *server.Config) error {\n\tsrv.config = conf\n\tsrv.initServerSettings()\n\tsrv.prepopulatePool(conf.PopulatePool)\n\n\tsrv.initServer()\n\tsrv.app.Use(requestid.New())\n\n\tloadUnrestrictedRootRoutes(srv)\n\tloadUnrestrictedNodeRoutes(srv)\n\n\tif err := srv.EnableJWTAuthentication(); err != nil {\n\t\treturn err\n\t}\n\n\tloadRestrictedRootRoutes(srv)\n\tloadRestrictedNodeRoutes(srv)\n\n\treturn nil\n}", "func Bootstrap(env evergreen.Environment) error {\n\tsettings := env.Settings()\n\tif settings.DomainName == \"\" {\n\t\treturn errors.Errorf(\"bootstrapping %s collection requires domain name to be set in admin settings\", settings.DomainName)\n\t}\n\n\tmaxExpiration := time.Duration(math.MaxInt64)\n\tserviceConfig := certdepot.CertificateOptions{\n\t\tCA: CAName,\n\t\tCommonName: settings.DomainName,\n\t\tHost: settings.DomainName,\n\t\tExpires: maxExpiration,\n\t}\n\n\tcaConfig := certdepot.CertificateOptions{\n\t\tCA: CAName,\n\t\tCommonName: CAName,\n\t\tExpires: maxExpiration,\n\t}\n\n\tbootstrapConfig := certdepot.BootstrapDepotConfig{\n\t\tMongoDepot: mongoConfig(settings),\n\t\tCAName: CAName,\n\t\tCAOpts: &caConfig,\n\t\tServiceName: settings.DomainName,\n\t\tServiceOpts: &serviceConfig,\n\t}\n\n\tctx, cancel := env.Context()\n\tdefer cancel()\n\n\tif _, err := certdepot.BootstrapDepotWithMongoClient(ctx, env.Client(), bootstrapConfig); err != nil {\n\t\treturn errors.Wrapf(err, \"could not bootstrap %s collection\", Collection)\n\t}\n\n\tserviceName = settings.DomainName\n\n\treturn nil\n}", "func init() {\n\n\tkubeManifest.AddCommand(kubeManifestPod)\n\tkubeManifest.AddCommand(kubeManifestDaemon)\n}", "func (h *envoyBootstrapHook) Prestart(ctx context.Context, req *ifs.TaskPrestartRequest, resp *ifs.TaskPrestartResponse) error {\n\tif !req.Task.Kind.IsConnectProxy() && !req.Task.Kind.IsAnyConnectGateway() {\n\t\t// Not a Connect proxy sidecar\n\t\tresp.Done = true\n\t\treturn nil\n\t}\n\n\tserviceKind, serviceName, err := h.extractNameAndKind(req.Task.Kind)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tservice, err := h.lookupService(serviceKind, serviceName, req.TaskEnv)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgrpcAddr := h.grpcAddress(req.TaskEnv.EnvMap)\n\n\th.logger.Debug(\"bootstrapping Consul \"+serviceKind, \"task\", req.Task.Name, \"service\", serviceName)\n\n\t// Envoy runs an administrative listener. There is no way to turn this feature off.\n\t// https://github.com/envoyproxy/envoy/issues/1297\n\tenvoyAdminBind := buildEnvoyAdminBind(h.alloc, serviceName, req.Task.Name, req.TaskEnv)\n\n\t// Consul configures a ready listener. There is no way to turn this feature off.\n\tenvoyReadyBind := buildEnvoyReadyBind(h.alloc, serviceName, req.Task.Name, req.TaskEnv)\n\n\t// Set runtime environment variables for the envoy admin and ready listeners.\n\tresp.Env = map[string]string{\n\t\thelper.CleanEnvVar(envoyAdminBindEnvPrefix+serviceName, '_'): envoyAdminBind,\n\t\thelper.CleanEnvVar(envoyReadyBindEnvPrefix+serviceName, '_'): envoyReadyBind,\n\t}\n\n\t// Envoy bootstrap configuration may contain a Consul token, so write\n\t// it to the secrets directory like Vault tokens.\n\tbootstrapFilePath := filepath.Join(req.TaskDir.SecretsDir, \"envoy_bootstrap.json\")\n\n\t// Write everything related to the command to enable debugging\n\tbootstrapStderrPath := filepath.Join(req.TaskDir.LogDir, \"envoy_bootstrap.stderr.0\")\n\tbootstrapEnvPath := filepath.Join(req.TaskDir.SecretsDir, \".envoy_bootstrap.env\")\n\tbootstrapCmdPath := filepath.Join(req.TaskDir.SecretsDir, \".envoy_bootstrap.cmd\")\n\n\tsiToken, err := h.maybeLoadSIToken(req.Task.Name, req.TaskDir.SecretsDir)\n\tif err != nil {\n\t\th.logger.Error(\"failed to generate envoy bootstrap config\", \"sidecar_for\", service.Name)\n\t\treturn fmt.Errorf(\"failed to generate envoy bootstrap config: %w\", err)\n\t}\n\th.logger.Debug(\"check for SI token for task\", \"task\", req.Task.Name, \"exists\", siToken != \"\")\n\n\tbootstrap := h.newEnvoyBootstrapArgs(h.alloc.TaskGroup, service, grpcAddr, envoyAdminBind, envoyReadyBind, siToken, bootstrapFilePath)\n\n\t// Create command line arguments\n\tbootstrapArgs := bootstrap.args()\n\n\t// Write args to file for debugging\n\targsFile, err := os.Create(bootstrapCmdPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write bootstrap command line: %w\", err)\n\t}\n\tdefer argsFile.Close()\n\tif _, err := io.WriteString(argsFile, strings.Join(bootstrapArgs, \" \")+\"\\n\"); err != nil {\n\t\treturn fmt.Errorf(\"failed to encode bootstrap command line: %w\", err)\n\t}\n\n\t// Create environment\n\tbootstrapEnv := bootstrap.env(os.Environ())\n\n\t// Write env to file for debugging\n\tenvFile, err := os.Create(bootstrapEnvPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write bootstrap environment: %w\", err)\n\t}\n\tdefer envFile.Close()\n\tenvEnc := json.NewEncoder(envFile)\n\tenvEnc.SetIndent(\"\", \" \")\n\tif err := envEnc.Encode(bootstrapEnv); err != nil {\n\t\treturn fmt.Errorf(\"failed to encode bootstrap environment: %w\", err)\n\t}\n\n\t// keep track of latest error returned from exec-ing consul envoy bootstrap\n\tvar cmdErr error\n\n\t// Since Consul services are registered asynchronously with this task\n\t// hook running, retry until timeout or success.\n\tbackoffOpts := decay.BackoffOptions{\n\t\tMaxSleepTime: h.envoyBootstrapWaitTime,\n\t\tInitialGapSize: h.envoyBoostrapInitialGap,\n\t\tMaxJitterSize: h.envoyBootstrapMaxJitter,\n\t}\n\tbackoffErr := decay.Backoff(func() (bool, error) {\n\t\t// If hook is killed, just stop.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t}\n\n\t\t// Prepare bootstrap command to run.\n\t\tcmd := exec.CommandContext(ctx, \"consul\", bootstrapArgs...)\n\t\tcmd.Env = bootstrapEnv\n\n\t\t// Redirect stdout to secrets/envoy_bootstrap.json.\n\t\tstdout, fileErr := os.Create(bootstrapFilePath)\n\t\tif fileErr != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to create secrets/envoy_bootstrap.json for envoy: %w\", fileErr)\n\t\t}\n\t\tdefer stdout.Close()\n\t\tcmd.Stdout = stdout\n\n\t\t// Redirect stderr into another file for later debugging.\n\t\tstderr, fileErr := os.OpenFile(bootstrapStderrPath, os.O_RDWR|os.O_CREATE, 0644)\n\t\tif fileErr != nil {\n\t\t\treturn false, fmt.Errorf(\"failed to create alloc/logs/envoy_bootstrap.stderr.0 for envoy: %w\", fileErr)\n\t\t}\n\t\tdefer stderr.Close()\n\t\tcmd.Stderr = stderr\n\n\t\t// Generate bootstrap\n\t\tcmdErr = cmd.Run()\n\n\t\t// Command succeeded, exit.\n\t\tif cmdErr == nil {\n\t\t\t// Bootstrap written. Mark as done and move on.\n\t\t\tresp.Done = true\n\t\t\treturn false, nil\n\t\t}\n\n\t\t// Command failed, prepare for retry\n\t\t//\n\t\t// Cleanup the bootstrap file. An errors here is not\n\t\t// important as (a) we test to ensure the deletion\n\t\t// occurs, and (b) the file will either be rewritten on\n\t\t// retry or eventually garbage collected if the task\n\t\t// fails.\n\t\t_ = os.Remove(bootstrapFilePath)\n\n\t\treturn true, cmdErr\n\t}, backoffOpts)\n\n\tif backoffErr != nil {\n\t\t// Wrap the last error from Consul and set that as our status.\n\t\t_, recoverable := cmdErr.(*exec.ExitError)\n\t\treturn structs.NewRecoverableError(\n\t\t\tfmt.Errorf(\"error creating bootstrap configuration for Connect proxy sidecar: %v\", cmdErr),\n\t\t\trecoverable,\n\t\t)\n\t}\n\n\treturn nil\n}", "func (backend *TestHTTPBackend) Bootstrap() error {\n\t_, err := backend.Server.JustListen()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbackend.RealPort = backend.Server.RealPort\n\tbackend.RealAddr = backend.Server.RealAddr\n\n\tbackend.WaitGroup.Add(1)\n\tgo backend.Server.JustServe(backend.WaitGroup)\n\treturn nil\n}", "func BootstrapServers(tmpPath string, restPort uint, grpcPort uint, serviceRegisterCallback func(stubsStore stub.StubsMatcher) grpchandler.MockService) {\n\tsetupLogrus()\n\n\terrorsEngine, err := stub.NewCustomErrorEngine(tmpPath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tstub.SetErrorEngine(errorsEngine)\n\n\tstubsStore := stub.NewInMemoryStubsStore()\n\tstubsMatcher := stub.NewStubsMatcher(stubsStore)\n\n\trecordingsStore := stub.NewRecordingsStore()\n\n\tservice := serviceRegisterCallback(stubsMatcher)\n\tlog.Info(\"Supported methods: \", strings.Join(service.GetSupportedMethods(), \" | \"))\n\tstubsExamples := service.GetPayloadExamples()\n\n\tgrpchandler.SetSupportedMockService(service)\n\tgrpchandler.SetRecordingsStore(recordingsStore)\n\n\tgo StartRESTServer(restPort, CreateRESTControllers(stubsExamples, stubsStore, recordingsStore, service))\n\tStarGRPCServer(grpcPort, service)\n}", "func init() {\n\treexec.Register(\"discover-nsfs-bindmounts\", discoverNsfsBindmounts)\n}", "func main() {\n\tfmt.Println(\"Starting management container...\")\n\tservice.Start()\n\tlog.Info(service.Container().Stats())\n\trouter := service.Container().Router\n\tsetupWebapp := service.SetupWebApplication(router)\n\trouter.PathPrefix(\"/setup\").HandlerFunc(setupWebapp.HandleRequest)\n\tmonitorWebapp := service.MonitorWebApplication(router)\n\trouter.PathPrefix(\"/\").HandlerFunc(monitorWebapp.HandleRequest)\n\tstartup()\n}", "func (proxy *OAuthProxy) registerExtensions(openshiftCAs StringArray) {\n\t//fill in\n\tproxy.RegisterRequestHandlers(cl.NewHandlers(openshiftCAs))\n}", "func Boot(ctx context.Context, settings *Settings, cfg *config.Config) (Bootstrap, error) {\n\t// NOTE(longsleep): Ensure to use same salt length as the hash size.\n\t// See https://www.ietf.org/mail-archive/web/jose/current/msg02901.html for\n\t// reference and https://github.com/golang-jwt/jwt/v4/issues/285 for\n\t// the issue in upstream jwt-go.\n\tfor _, alg := range []string{jwt.SigningMethodPS256.Name, jwt.SigningMethodPS384.Name, jwt.SigningMethodPS512.Name} {\n\t\tsm := jwt.GetSigningMethod(alg)\n\t\tif signingMethodRSAPSS, ok := sm.(*jwt.SigningMethodRSAPSS); ok {\n\t\t\tsigningMethodRSAPSS.Options.SaltLength = rsa.PSSSaltLengthEqualsHash\n\t\t}\n\t}\n\n\tbs := &bootstrap{\n\t\tconfig: &Config{\n\t\t\tConfig: cfg,\n\t\t\tSettings: settings,\n\t\t},\n\t}\n\n\terr := bs.initialize(settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = bs.setup(ctx, settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bs, nil\n}", "func (cptool *CPTool) Bootstrap() error {\n\tcptool.loadAllLanguages()\n\treturn nil\n}", "func Bootstrap() (err error) {\n\tonce.Do(func() {\n\t\troot, err = getLogger(Logging{\n\t\t\tEnv: \"dev\",\n\t\t\tLevel: \"debug\",\n\t\t})\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func init() {\n\tHome, err := homedir.Dir()\n\tif err != nil {\n\t\tzap.S().Fatalw(\"error finding home directory\", err)\n\t}\n\n\t// Search config in home directory with name \".[Executable]\" (without extension).\n\tviper.AddConfigPath(\".\")\n\tviper.AddConfigPath(Home)\n\tviper.SetConfigName(\".\" + Executable)\n\tviper.SetTypeByDefaultValue(true)\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\tviper.SetDefault(\"kubeconfig\", filepath.Join(Home, \".kube\", \"config\"))\n\tviper.SetDefault(\"namespace\", \"\")\n}", "func (repo *Workdir) LoadExtensions() error {\n\trepo.locate(repo.Workdir)\n\tfor _, dirname := range repo.versionPaths {\n\t\tversion, err := NewVersion(repo.ctx, dirname)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to NewVersion\")\n\t\t}\n\t\trepo.Versions = append(repo.Versions, version)\n\t}\n\n\tif len(repo.Versions) == 0 {\n\t\treturn errors.Errorf(\"there is no extension in the repo %s, please ensure this is an extension repo\")\n\t}\n\n\treturn nil\n}", "func (Bootstrapper) Bootstrap(context map[string]interface{}) error {\n\tcfg, err := configstore.RetrieveConfig(false, context)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttxManager, ok := context[jobs.BootstrappedService].(jobs.Manager)\n\tif !ok {\n\t\treturn errors.New(\"transactions repository not initialised\")\n\t}\n\n\tif _, ok := context[bootstrap.BootstrappedQueueServer]; !ok {\n\t\treturn errors.New(\"queue hasn't been initialized\")\n\t}\n\tqueueSrv := context[bootstrap.BootstrappedQueueServer].(*queue.Server)\n\n\tsapi, err := gsrpc.NewSubstrateAPI(cfg.GetCentChainNodeURL())\n\tif err != nil {\n\t\treturn err\n\t}\n\tcentSAPI := &defaultSubstrateAPI{sapi}\n\tclient := NewAPI(centSAPI, cfg, queueSrv)\n\textStatusTask := NewExtrinsicStatusTask(cfg.GetCentChainIntervalRetry(), cfg.GetCentChainMaxRetries(), txManager, centSAPI.GetBlockHash, centSAPI.GetBlock, centSAPI.GetMetadataLatest, centSAPI.GetStorage)\n\tqueueSrv.RegisterTaskType(extStatusTask.TaskTypeName(), extStatusTask)\n\tcontext[BootstrappedCentChainClient] = client\n\n\treturn nil\n}", "func Bootstrap() *fiber.App {\n\tapp := fiber.New(fiber.Config{\n\t\tServerHeader: \"JellyPi\",\n\t\tStrictRouting: true,\n\t\tCaseSensitive: true,\n\t\tReadTimeout: time.Second * 5,\n\t})\n\n\tapp.Use(recover.New())\n\tapp.Use(logger.New())\n\tapp.Use(cors.New())\n\n\tSetupRoutes(app)\n\n\treturn app\n}", "func init() {\n\trootCmd.AddCommand(listServersCmd)\n\trootCmd.AddCommand(lsCmd)\n\n\taddFlags(listServersCmd)\n\taddFlags(lsCmd)\n}", "func init() {\n\tfor group, values := range defaultConfigs {\n\t\tcore.RegisterConfig(group, values)\n\t}\n\tcore.RegisterService(\"indicator\", indicator.Configs, &indicator.IndicatorServiceFactory{})\n\tcore.RegisterService(\"executor\", executor.Configs, &executor.ExecutorServiceFactory{})\n}", "func (bs *bootstrap) setup(ctx context.Context, settings *Settings) error {\n\tmanagers, err := newManagers(ctx, bs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbs.managers = managers\n\n\tidentityManager, err := bs.setupIdentity(ctx, settings)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmanagers.Set(\"identity\", identityManager)\n\n\tguestManager, err := bs.setupGuest(ctx, identityManager)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmanagers.Set(\"guest\", guestManager)\n\n\toidcProvider, err := bs.setupOIDCProvider(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmanagers.Set(\"oidc\", oidcProvider)\n\tmanagers.Set(\"handler\", oidcProvider) // Use OIDC provider as default HTTP handler.\n\n\terr = managers.Apply()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to apply managers: %v\", err)\n\t}\n\n\t// Final steps\n\terr = oidcProvider.InitializeMetadata()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to initialize provider metadata: %v\", err)\n\t}\n\n\treturn nil\n}", "func init() {\n\tos.Setenv(\"PATH\", strings.Join([]string{os.Getenv(\"PATH\"), \"/opt/puppetlabs/bin\"}, \":\"))\n}", "func (b *base) init(services []Service) (err error) {\n\tif err = b.initConfig(); err != nil {\n\t\treturn\n\t}\n\tif err = b.initNewrelic(); err != nil {\n\t\treturn\n\t}\n\tif err = b.initSentry(); err != nil {\n\t\treturn\n\t}\n\tb.initLogger()\n\tb.initDriver()\n\tb.initRouter(services)\n\treturn\n}", "func (app *App) InitDependencyInjection() {\n\tapp.AppDI = di.InitDI()\n}", "func init() {\n\tRegister(\"http\", StartHTTP)\n}", "func BootstrapCLI(args []string) error {\n\trootCmd := BuildCLI()\n\treturn rootCmd.Execute()\n}", "func boot() error {\n\tvar err error\n\tApp.DB, err = database.Connect(&App.Conf.Database)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tApp.Version = Version\n\tmodels.Setup(&App)\n\treturn models.Migrate()\n}", "func (s *Service) Init(sharedCfg *config.SharedCfg, cmd, serveCmd *cobra.Command) error {\n\tdal.InitMetrics(reg)\n\tapp.InitMetrics(reg)\n\tgrpc.InitMetrics(reg)\n\n\tctx := def.NewContext(app.ServiceName)\n\tgoosePostgresCmd := cobrax.NewGoosePostgresCmd(ctx, migrations.Goose(), config.GetGoosePostgres)\n\tcmd.AddCommand(goosePostgresCmd)\n\n\treturn config.Init(sharedCfg, config.FlagSets{\n\t\tServe: serveCmd.Flags(),\n\t\tGoosePostgres: goosePostgresCmd.Flags(),\n\t})\n}", "func init() {\n\tnewApp := core.NewSimpleApplication()\n\n\t// Now, enjoy your web!\n\tnewApp.StartApp(wtsMap)\n}", "func StartUp() {\n\tloadParams()\n\tinitConfig(configFile)\n\tsetupLogging()\n}", "func Init() {\n\tmodAServices.SetAppCalculator(&appServices.AppCalculator{})\n\t// ... add more here\n}", "func RegisterHttpsServicesAndStartListener() {\n\taph := aphService{}\n\n\t// HelloWorldHandler := httptransport.NewServer(\n\t// \tmakeHelloWorldEndpoint(aph),\n\t// \tdecodeHelloWorldRequest,\n\t// \tencodeResponse,\n\t// )\n\t// HelloDaerahHandler := httptransport.NewServer(\n\t// \tmakeHelloDaerahEndpoint(aph),\n\t// \tdecodeHelloDaerahRequest,\n\t// \tencodeResponse,\n\t// )\n\tGetItenaryHandler := httptransport.NewServer(\n\t\tmakeGetItenaryEndpoint(aph),\n\t\tdecodeGetItenaryRequest,\n\t\tencodeResponse,\n\t)\n\t// http.Handle(\"/HelloWorld\", HelloWorldHandler)\n\t// http.Handle(\"/HelloDaerah\", HelloDaerahHandler)\n\thttp.Handle(\"/GetItenary\", GetItenaryHandler)\n}", "func bootStrapMethods() {\n\tfor _, mi := range modelRegistry.registryByName {\n\t\tmi.methods.bootstrapped = true\n\t}\n}", "func Bootstrap(in *ContextIn) *ContextOut {\n\n\t// transform middleware slice\n\tmiddlewares := make([]mux.MiddlewareFunc, len(in.MiddlewaresToRegister))\n\tfor i, middleware := range in.MiddlewaresToRegister {\n\t\tmiddlewares[i] = middleware\n\t}\n\n\tout := &ContextOut{}\n\tout.Server = &server{\n\t\tport: in.Port,\n\t\troutes: in.RoutesToRegister,\n\t\tmiddlewares: middlewares,\n\t}\n\n\treturn out\n}", "func main() {\n\tloggingInit(service.Interactive())\n\tif !service.Interactive() {\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\tviper.AddConfigPath(path.Join(os.Getenv(\"ProgramData\"), \"YubiHSM\"))\n\t\t} else {\n\t\t\t// These paths will work for most UNIXy platforms. macOS may need something else.\n\t\t\tconfigPaths := [2]string{\"/etc\", \"/usr/local/etc\"}\n\t\t\tfor _, configPath := range configPaths {\n\t\t\t\tviper.AddConfigPath(path.Join(configPath, \"yubihsm\"))\n\t\t\t}\n\t\t}\n\t}\n\n\tsvcConfig := &service.Config{\n\t\tName: \"yhconsrv\",\n\t\tDisplayName: \"YubiHSM Connector Service\",\n\t\tDescription: \"Implements the http-usb interface for the YubiHSM\",\n\t}\n\tprg := &program{}\n\ts, err := service.New(prg, svcConfig)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tsignalChannel := make(chan os.Signal, 1)\n\n\tsignal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)\n\n\tgo func() {\n\t\tsignalEncountered := <-signalChannel\n\t\tlog.Info(\"Shutting down.\")\n\n\t\t// Put any process wide shutdown calls here\n\t\tusbclose(\"Process terminate\")\n\n\t\tsignal.Reset(signalEncountered)\n\t\tos.Exit(0)\n\t}()\n\n\trootCmd := &cobra.Command{\n\t\tUse: \"yubihsm-connector\",\n\t\tLong: `YubiHSM Connector v` + Version.String(),\n\t\tSilenceUsage: true,\n\t\tSilenceErrors: true,\n\t\tPersistentPreRun: func(cmd *cobra.Command, args []string) {\n\t\t\tconfig := viper.GetString(\"config\")\n\t\t\tif config != \"\" {\n\t\t\t\tviper.SetConfigFile(config)\n\t\t\t}\n\t\t},\n\t\tPreRunE: func(cmd *cobra.Command, args []string) (err error) {\n\t\t\tif err = viper.ReadInConfig(); err != nil {\n\t\t\t\tif _, ok := err.(viper.ConfigFileNotFoundError); !ok {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif viper.GetBool(\"debug\") {\n\t\t\t\tlog.SetLevel(log.DebugLevel)\n\t\t\t}\n\n\t\t\tcertkeyErr := fmt.Errorf(\"cert and key must both be specified\")\n\t\t\tif viper.GetString(\"cert\") != \"\" && viper.GetString(\"key\") == \"\" {\n\t\t\t\treturn certkeyErr\n\t\t\t} else if viper.GetString(\"cert\") == \"\" && viper.GetString(\"key\") != \"\" {\n\t\t\t\treturn certkeyErr\n\t\t\t}\n\n\t\t\tserial, err := ensureSerial(viper.GetString(\"serial\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"config\": viper.ConfigFileUsed(),\n\t\t\t\t\"pid\": os.Getpid(),\n\t\t\t\t\"seccomp\": viper.GetBool(\"seccomp\"),\n\t\t\t\t\"syslog\": viper.GetBool(\"syslog\"),\n\t\t\t\t\"version\": Version.String(),\n\t\t\t\t\"cert\": viper.GetString(\"cert\"),\n\t\t\t\t\"key\": viper.GetString(\"key\"),\n\t\t\t\t\"timeout\": timeoutToMs(viper.GetUint32(\"timeout\")),\n\t\t\t\t\"serial\": serial,\n\t\t\t}).Debug(\"preflight complete\")\n\n\t\t\treturn nil\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) (err error) {\n\t\t\treturn s.Run()\n\t\t},\n\t}\n\trootCmd.PersistentFlags().StringP(\"config\", \"c\", \"\", \"config file\")\n\tviper.BindPFlag(\"config\", rootCmd.PersistentFlags().Lookup(\"config\"))\n\trootCmd.PersistentFlags().BoolP(\"debug\", \"d\", false, \"debug output\")\n\tviper.BindPFlag(\"debug\", rootCmd.PersistentFlags().Lookup(\"debug\"))\n\trootCmd.PersistentFlags().BoolP(\"seccomp\", \"s\", false, \"enable seccomp\")\n\tviper.BindPFlag(\"seccomp\", rootCmd.PersistentFlags().Lookup(\"seccomp\"))\n\trootCmd.PersistentFlags().StringP(\"cert\", \"\", \"\", \"certificate (X509)\")\n\tviper.BindPFlag(\"cert\", rootCmd.PersistentFlags().Lookup(\"cert\"))\n\trootCmd.PersistentFlags().StringP(\"key\", \"\", \"\", \"certificate key\")\n\tviper.BindPFlag(\"key\", rootCmd.PersistentFlags().Lookup(\"key\"))\n\trootCmd.PersistentFlags().StringP(\"serial\", \"\", \"\", \"device serial\")\n\tviper.BindPFlag(\"serial\", rootCmd.PersistentFlags().Lookup(\"serial\"))\n\trootCmd.PersistentFlags().StringP(\"listen\", \"l\", \"localhost:12345\", \"listen address\")\n\tviper.BindPFlag(\"listen\", rootCmd.PersistentFlags().Lookup(\"listen\"))\n\trootCmd.PersistentFlags().BoolP(\"syslog\", \"L\", false, \"log to syslog/eventlog\")\n\tviper.BindPFlag(\"syslog\", rootCmd.PersistentFlags().Lookup(\"syslog\"))\n\trootCmd.PersistentFlags().BoolVar(&hostHeaderAllowlisting, \"enable-host-header-allowlist\", false, \"Enable Host header allowlisting\")\n\tviper.BindPFlag(\"enable-host-allowlist\", rootCmd.PersistentFlags().Lookup(\"enable-host-header-allowlist\"))\n\trootCmd.PersistentFlags().StringSliceVar(&hostHeaderAllowlist, \"host-header-allowlist\", hostHeaderAllowlist, \"Host header allowlist\")\n\tviper.BindPFlag(\"host-allowlist\", rootCmd.PersistentFlags().Lookup(\"host-header-allowlist\"))\n\trootCmd.PersistentFlags().Uint32P(\"timeout\", \"t\", 0, \"(DEPRECATED) USB operation timeout in milliseconds (default 0, never timeout)\")\n\tviper.BindPFlag(\"timeout\", rootCmd.PersistentFlags().Lookup(\"timeout\"))\n\n\tconfigCmd := &cobra.Command{\n\t\tUse: \"config\",\n\t\tLong: `YubiHSM Connector configuration\n\nMost configuration knobs for the connector are not available at the command\nline, and must be supplied via a configurtion file.\n\nlisten: localhost:12345\nsyslog: false\ncert: /path/to/certificate.crt\nkey: /path/to/certificate.key\nserial: 0123456789\n`,\n\t}\n\tconfigCheckCmd := &cobra.Command{\n\t\tUse: \"check\",\n\t\tLong: `Syntax check configuration`,\n\t\tSilenceErrors: true,\n\t\tSilenceUsage: true,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tif err := viper.ReadInConfig(); err != nil {\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"error\": err,\n\t\t\t\t\t\"config\": viper.ConfigFileUsed(),\n\t\t\t\t}).Fatal(\"syntax errors in configuration file\")\n\t\t\t} else {\n\t\t\t\tlog.Info(\"OK!\")\n\t\t\t}\n\t\t},\n\t}\n\tconfigGenCmd := &cobra.Command{\n\t\tUse: \"generate\",\n\t\tLong: `Generate a skeleton configuration from default values`,\n\t\tSilenceErrors: true,\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) (err error) {\n\t\t\tvar buf []byte\n\n\t\t\tconfig := viper.AllSettings()\n\t\t\tdelete(config, \"debug\")\n\t\t\tdelete(config, \"config\")\n\t\t\tdelete(config, \"seccomp\")\n\n\t\t\tif buf, err = yaml.Marshal(&config); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfmt.Fprintf(os.Stdout, \"%s\", buf)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tversionCmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tLong: `Print program version`,\n\t\tSilenceErrors: true,\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) (err error) {\n\t\t\tfmt.Fprintf(os.Stdout, \"%s\\n\", Version.String())\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tinstallCmd := &cobra.Command{\n\t\tUse: \"install\",\n\t\tLong: \"Install YubiHSM Connector service\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn s.Install()\n\t\t},\n\t}\n\n\tuninstallCmd := &cobra.Command{\n\t\tUse: \"uninstall\",\n\t\tLong: \"Uninstall YubiHSM Connector service\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn s.Uninstall()\n\t\t},\n\t}\n\n\tstartCmd := &cobra.Command{\n\t\tUse: \"start\",\n\t\tLong: \"Starts YubiHSM Connector service\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn s.Start()\n\t\t},\n\t}\n\n\tstopCmd := &cobra.Command{\n\t\tUse: \"stop\",\n\t\tLong: \"Stops YubiHSM Connector service\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn s.Stop()\n\t\t},\n\t}\n\n\trestartCmd := &cobra.Command{\n\t\tUse: \"restart\",\n\t\tLong: \"Restarts YubiHSM Connector service\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn s.Restart()\n\t\t},\n\t}\n\n\tconfigCmd.AddCommand(configCheckCmd, configGenCmd)\n\trootCmd.AddCommand(configCmd)\n\trootCmd.AddCommand(versionCmd)\n\trootCmd.AddCommand(installCmd)\n\trootCmd.AddCommand(uninstallCmd)\n\trootCmd.AddCommand(startCmd)\n\trootCmd.AddCommand(stopCmd)\n\trootCmd.AddCommand(restartCmd)\n\n\tviper.SetConfigName(\"yubihsm-connector\")\n\n\tviper.SetEnvPrefix(\"YUBIHSM_CONNECTOR\")\n\tviper.AutomaticEnv()\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func init() {\n\n\tcobra.OnInitialize(func() {\n\t\tconfig.Initialize(rootCmd)\n\t})\n\n\tconfig.InitializeFlags(rootCmd)\n}", "func OnAppStart(f func()) {\n\tstartupHooks = append(startupHooks, f)\n}", "func (e *Extender) Start() error {\n\te.lock.Lock()\n\tdefer e.lock.Unlock()\n\n\tif e.started {\n\t\treturn fmt.Errorf(\"Extender has already been started\")\n\t}\n\t// TODO: Make the listen port configurable\n\te.server = &http.Server{Addr: \":8099\"}\n\thttp.HandleFunc(\"/\", e.serveHTTP)\n\tgo func() {\n\t\tif err := e.server.ListenAndServe(); err != http.ErrServerClosed {\n\t\t\tlog.Panicf(\"Error starting extender server: %v\", err)\n\t\t}\n\t}()\n\n\tprometheus.MustRegister(HyperConvergedPodsCounter)\n\tprometheus.MustRegister(NonHyperConvergePodsCounter)\n\tprometheus.MustRegister(SemiHyperConvergePodsCounter)\n\tif err := e.collectExtenderMetrics(); err != nil {\n\t\treturn err\n\t}\n\n\te.started = true\n\treturn nil\n}", "func main() {\n\n\t// Initialize Logger instance\n\tlog, err := logger.New(serviceName, logger.Options{\n\t\tFormat: logger.SyslogLogFormat,\n\t})\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\terr = os.Setenv(\"KUBECONFIG\", path.Join(\n\t\tconfig.KubeConfig[configprovider.FilePath],\n\t\tfmt.Sprintf(\"%s.%s\", config.KubeConfig[configprovider.FileName], config.KubeConfig[configprovider.FileType])),\n\t)\n\tif err != nil {\n\t\t// Fail silently\n\t\tlog.Warn(err)\n\t}\n\n\t// Initialize application specific configs and dependencies\n\t// App and request config\n\tcfg, err := config.New(configprovider.ViperKey)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tos.Exit(1)\n\t}\n\n\tservice := &grpc.Service{}\n\terr = cfg.GetObject(adapter.ServerKey, service)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tos.Exit(1)\n\t}\n\n\tkubeconfigHandler, err := config.NewKubeconfigBuilder(configprovider.ViperKey)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tos.Exit(1)\n\t}\n\n\t// // Initialize Tracing instance\n\t// tracer, err := tracing.New(service.Name, service.TraceURL)\n\t// if err != nil {\n\t// \tlog.Err(\"Tracing Init Failed\", err.Error())\n\t// \tos.Exit(1)\n\t// }\n\n\t// Initialize Handler intance\n\thandler := nginx.New(cfg, log, kubeconfigHandler)\n\thandler = adapter.AddLogger(log, handler)\n\n\tservice.Handler = handler\n\tservice.Channel = make(chan interface{}, 10)\n\tservice.StartedAt = time.Now()\n\n\tgo registerCapabilities(service.Port, log) //Registering static capabilities\n\tgo registerDynamicCapabilities(service.Port, log) //Registering latest capabilities periodically\n\n\t// Server Initialization\n\tlog.Info(\"Adapter Listening at port: \", service.Port)\n\terr = grpc.Start(service, nil)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\tos.Exit(1)\n\t}\n}", "func (am AppModule) RegisterServices(cfg module.Configurator) {\n\ttypes.RegisterMsgServer(cfg.MsgServer(), keeper.MsgServer(am.keeper))\n\ttypes.RegisterQueryServer(cfg.QueryServer(), keeper.QueryServer(am.keeper))\n}", "func Init() {\n\n //创建服务\n service := micro.NewService(\n micro.Name(\"rolesssService\"),\n micro.Version(\"latest\"),\n )\n service.Init()\n cli1 = rolepb.NewRoleService(\"role-service\", service.Client())\n}", "func (am AppModule) RegisterServices(cfg module.Configurator) {\n\ttypes.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServer(am.keeper))\n\ttypes.RegisterQueryServer(cfg.QueryServer(), keeper.NewQueryServer(am.keeper))\n}", "func bootStrap() error {\n\tvar err error\n\tallObjects, err = client.ListObjects(runParams.proxyURL, runParams.bucket, myName)\n\treturn err\n}", "func (c *swimCluster) Bootstrap() {\n\tfor _, node := range c.nodes {\n\t\tnode.Bootstrap(&BootstrapOptions{\n\t\t\tDiscoverProvider: statichosts.New(c.Addresses()...),\n\t\t})\n\t}\n}", "func viperSetup() error {\n\tviper.SetDefault(\"providers\", []string{})\n\tviper.SetDefault(\"webserver.debug\", false)\n\tviper.SetDefault(\"webserver.cors.origin\", \"https://127.0.0.1:3000\")\n\tviper.SetDefault(\"webserver.address\", \"0.0.0.0:8080\")\n\n\tviper.AddConfigPath(\"./\")\n\tviper.AddConfigPath(\"./config\")\n\tviper.AddConfigPath(\"$HOME/.calp\")\n\tviper.AddConfigPath(\"/etc/calp\")\n\tviper.SetConfigName(\"config\")\n\n\tif err := viper.ReadInConfig(); err != nil {\n\t\treturn err\n\t}\n\n\tviper.SetEnvPrefix(\"CALP\")\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\tviper.AutomaticEnv()\n\n\treturn nil\n}", "func init() {\n\tif err := RegisterDriver(k8s.Name, NewK8S); err != nil {\n\t\tpanic(err.Error())\n\t}\n}", "func (b *Bootstrapper) Bootstrap() *Bootstrapper {\n\treturn b\n}", "func init() {\n\tMigrations = append(Migrations, addUserMigration0001)\n}", "func StartApplicatin() {\n\tmapUrls()\n\trouter.Run(\":8080\")\n}", "func init() {\n\tcodegen.RegisterPluginFirst(\"zaplogger\", \"gen\", nil, Generate)\n\tcodegen.RegisterPluginLast(\"zaplogger-updater\", \"example\", nil, UpdateExample)\n}", "func init() {\n\tRegistry.Add(eksinfo.New())\n\tRegistry.Add(vpcinfo.New())\n\tRegistry.Add(iamresourceusage.New())\n}", "func (*GenericFramework) Startup(ctx *NetworkContext) {}", "func init() {\n\tcollectors.Register(\"system\", func() (collectors.Collector, error) {\n\t\treturn &SystemCollector{\n\t\t\tresourceManager: platform.GetResourceManager(),\n\t\t}, nil\n\t})\n}", "func Start(cmd *cobra.Command, args []string) error {\n\tvar err error\n\tcfg, err = config.BindWithCobra(cmd)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstartServices()\n\treturn nil\n}", "func init() {\n\tvanguard.AddAuthRoute(\"GET\", \"/U/bootstrapEveAuth\", bootstrapEveSSO)\n\tvanguard.AddAuthRoute(\"GET\", \"/U/bootstrapEveSSOAnswer\", bootstrapEveSSOAnswer)\n}", "func (b *Bootstrapper) Start(c core.Components) error {\n\tlog.Info(\"[ Bootstrapper ] Starting Bootstrap ...\")\n\n\trootDomainRef, err := getRootDomainRef(c)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"[ Bootstrapper ] couldn't get ref of rootDomain\")\n\t}\n\tif rootDomainRef != nil {\n\t\tb.rootDomainRef = rootDomainRef\n\t\tlog.Info(\"[ Bootstrapper ] RootDomain was found in ledger. Don't do bootstrap\")\n\t\treturn nil\n\t}\n\n\tb.rootPubKey, err = getRootMemberPubKey(b.rootKeysFile)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"[ Bootstrapper ] couldn't get root member keys\")\n\t}\n\n\tisLightExecutor, err := isLightExecutor(c)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"[ Bootstrapper ] couldn't check if node is light executor\")\n\t}\n\tif !isLightExecutor {\n\t\tlog.Info(\"[ Bootstrapper ] Node is not light executor. Don't do bootstrap\")\n\t\treturn nil\n\t}\n\n\t_, insgocc, err := goplugintestutils.Build()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"[ Bootstrapper ] couldn't build insgocc\")\n\t}\n\n\tam := c.Ledger.GetArtifactManager()\n\tcb := goplugintestutils.NewContractBuilder(am, insgocc)\n\tb.classRefs = cb.Classes\n\tdefer cb.Clean()\n\n\terr = buildSmartContracts(cb)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"[ Bootstrapper ] couldn't build contracts\")\n\t}\n\n\terr = b.activateSmartContracts(am, cb)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"[ Bootstrapper ]\")\n\t}\n\n\treturn nil\n}", "func init() {\n\t// Search config in home directory with name \"eve-ng-api\" (without extension).\n\tviper.AddConfigPath(\"config/\")\n\tviper.SetConfigType(\"yaml\")\n\tviper.SetConfigName(\"eve-ng-api\")\n\n\t//Set env var prefix to only match certain vars\n\tviper.SetEnvPrefix(\"EVE_NG_API\")\n\n\t// read in environment variables that match\n\tviper.AutomaticEnv()\n\n\t// If a config file is found, read it in.\n\tviper.ReadInConfig()\n}", "func (c *kubernetesDeploymentManifest) Bootstrap(ctx context.Context, profile ServiceRequest, env map[string]string, waitCB func() error) error {\n\tspan, _ := apm.StartSpanOptions(ctx, \"Bootstrapping kubernetes deployment\", \"kubernetes.manifest.bootstrap\", apm.SpanOptions{\n\t\tParent: apm.SpanFromContext(ctx).TraceContext(),\n\t})\n\tdefer span.End()\n\n\terr := cluster.Initialize(ctx, \"../../../cli/config/kubernetes/kind.yaml\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO: we would need to understand how to pass the environment argument to anything running in the namespace\n\tkubectl = cluster.Kubectl().WithNamespace(ctx, getNamespaceFromProfile(profile))\n\t_, err = kubectl.Run(ctx, \"apply\", \"-k\", \"../../../cli/config/kubernetes/base\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = waitCB()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (op *AddonOperator) Start() error {\n\tif err := op.bootstrap(); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(\"Start first converge for modules\")\n\t// Loading the onStartup hooks into the queue and running all modules.\n\t// Turning tracking changes on only after startup ends.\n\n\t// Bootstrap main queue with tasks to run Startup process.\n\top.BootstrapMainQueue(op.TaskQueues)\n\t// Start main task queue handler\n\top.TaskQueues.StartMain()\n\n\t// Global hooks are registered, initialize their queues.\n\top.CreateAndStartQueuesForGlobalHooks()\n\n\t// ManagerEventsHandler handle events for kubernetes and schedule bindings.\n\t// Start it before start all informers to catch all kubernetes events (#42)\n\top.ManagerEventsHandler.Start()\n\n\t// Enable events from schedule manager.\n\top.ScheduleManager.Start()\n\n\top.KubeConfigManager.Start()\n\top.ModuleManager.Start()\n\top.StartModuleManagerEventHandler()\n\n\treturn nil\n}", "func init() {\n\tregister(\"jemoji\", jemojiPlugin{})\n\tregister(\"jekyll-mentions\", jekyllMentionsPlugin{})\n\tregister(\"jekyll-optional-front-matter\", jekyllOptionalFrontMatterPlugin{})\n\n\t// Gojekyll behaves as though the following plugins are always loaded.\n\t// Define them here so we don't see warnings that they aren't defined.\n\tregister(\"jekyll-live-reload\", plugin{})\n\tregister(\"jekyll-sass-converter\", plugin{})\n}", "func Init() {\n\tdocker.Init()\n\thost.Init()\n\tlabel.Init()\n\tospackages.Init()\n\tdiff.Init()\n\tcontainer.Init()\n}", "func (am AppModule) RegisterServices(cfg module.Configurator) {\n\ttypes.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper))\n\ttypes.RegisterQueryServer(cfg.QueryServer(), am.keeper)\n}", "func initConfig() {\n\tviper.SetEnvPrefix(\"EOS_BIOS\")\n\tviper.AutomaticEnv() // read in environment variables that match\n}", "func Init() {\n\tprovisioner.Register(\"docker\", &Docker{})\n}", "func init() {\n\tRegisterProxifiedApplication(NewEnvProxySetter())\n}", "func (b *Bootstrapper) Initialize(config Config) error {\n\tb.Config = config\n\tb.Ctx.Log.Info(\"Starting bootstrap...\")\n\n\tif b.Config.StartupAlpha > 0 {\n\t\treturn nil\n\t}\n\treturn b.startup()\n}", "func (s *server) RegisterServices(gs *grpc.Server) {\n\tttnpb.RegisterApplicationPackageRegistryServer(gs, s)\n\tfor _, subsystem := range s.handlers {\n\t\tif subsystem, ok := subsystem.(rpcserver.ServiceRegisterer); ok {\n\t\t\tsubsystem.RegisterServices(gs)\n\t\t}\n\t}\n}", "func bootup (w http.ResponseWriter, r *http.Request ) {\n\tfmt.Fprintf( w, \"<h1>%s</h1>\\n\", \"Starting app for translating gophers language...\" )\n\tfmt.Fprintf( w, \"<h4>%s</h4>\\n\", \"We currently support two POST endpoints /word and /sentence\" )\n}", "func NewBootstrap(config config.Config) {\n\tchatServer = chat.NewServer()\n\tchatServer.Listen()\n\tlogs.Info(\"Chat Server started\")\n\n\tif config.TelnetAddress != \"\" {\n\t\tlogs.FatalIfErrf(startTelnet(config), \"Could not start telnet server.\")\n\t} else {\n\t\tlogs.Warnf(\"TelnetAddress is empty, not running Telnet Driver\")\n\t}\n\n\tif config.WebAddress != \"\" {\n\t\tstartWeb(config)\n\t} else {\n\t\tlogs.Warnf(\"WebAddress is empty, not running Web Drivers\")\n\t}\n}", "func init() {\n\tgrpccmd.RegisterServiceCmd(_WorkerManagementCmd)\n\t_WorkerManagementCmd.AddCommand(\n\t\t_WorkerManagement_StatusCmd,\n\t\t_WorkerManagement_StatusCmd_gen,\n\t\t_WorkerManagement_DevicesCmd,\n\t\t_WorkerManagement_DevicesCmd_gen,\n\t\t_WorkerManagement_FreeDevicesCmd,\n\t\t_WorkerManagement_FreeDevicesCmd_gen,\n\t\t_WorkerManagement_TasksCmd,\n\t\t_WorkerManagement_TasksCmd_gen,\n\t\t_WorkerManagement_AskPlansCmd,\n\t\t_WorkerManagement_AskPlansCmd_gen,\n\t\t_WorkerManagement_CreateAskPlanCmd,\n\t\t_WorkerManagement_CreateAskPlanCmd_gen,\n\t\t_WorkerManagement_RemoveAskPlanCmd,\n\t\t_WorkerManagement_RemoveAskPlanCmd_gen,\n\t\t_WorkerManagement_PurgeAskPlansCmd,\n\t\t_WorkerManagement_PurgeAskPlansCmd_gen,\n\t)\n}", "func (rcm *RecentCommandsService) Init() error {\n\terr := rcm.app.DBService.DB.AutoMigrate(&RecentCommand{}).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to migrate RecentCommand: %w\", err)\n\t}\n\treturn nil\n}", "func init() {\n\tloadTheEnv()\n\tcreateDBInstance()\n\tloadRepDB()\n\tstartKafka()\n}", "func (api *API) SetupGRPCServices() {\n\tapi.Services.SetupAnalyzerService()\n\tapi.Services.SetupAnonymizerService()\n\tapi.Services.SetupAnonymizerImageService()\n\tapi.Services.SetupSchedulerService()\n\tapi.Services.SetupOCRService()\n\tapi.Services.SetupRecognizerStoreService()\n}", "func init() {\n\tcobra.OnInitialize(initConfig)\n\n\t// load the defaults from the default map here, add new defaults on the map\n\tfor key, val := range defaults {\n\t\tviper.SetDefault(key, val)\n\t}\n\n\trootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME/.xendit-account-service.yaml)\")\n}", "func (m *InfrastructureProviderAWS) Bootstrap() {\n\tm.createInstances()\n\tfor i := 0; i < 50; i++ {\n\t\ttime.Sleep(5 * time.Second)\n\t\tif m.assureRunning() {\n\t\t\tlog.Info(\"all instances are running\")\n\t\t\tbreak\n\t\t}\n\t}\n\tm.collectPublicAddresses()\n\tm.dumpPrivateKeys()\n\t// TODO: general retry function, even if VM is in state \"running\" ssh may be unavailable,\n\t// has no flag to know it for sure\n\tlog.Infof(\"awaiting ssh is available\")\n\ttime.Sleep(60 * time.Second)\n\tm.provision()\n}", "func init() {\n\tworkflow.Register(Workflow)\n\tactivity.Register(helloworldActivity)\n}", "func (r *registry) doSetup() (_ *Extensions, err error) {\n\tif r.setup {\n\t\treturn r.extensions, nil\n\t}\n\n\tif len(r.factories) == 0 {\n\t\tr.extensions = nil\n\t\tr.setup = true\n\t\treturn nil, nil\n\t}\n\n\tclearBuilder := &clearFuncBuilder{}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tclearBuilder.Build()()\n\t\t}\n\t}()\n\n\tmanifests := make([]*Manifest, 0, len(r.factories))\n\tfor i := range r.extensionNames {\n\t\tname := r.extensionNames[i]\n\t\terr = clearBuilder.DoWithCollectClear(func() (func(), error) {\n\t\t\tfactory := r.factories[name]\n\t\t\tm, clear, err := newManifestWithSetup(name, factory)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tmanifests = append(manifests, m)\n\t\t\treturn clear, nil\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tr.extensions = &Extensions{manifests: manifests}\n\tr.setup = true\n\tr.close = clearBuilder.Build()\n\treturn r.extensions, nil\n}", "func init() {\n\tcobra.OnInitialize(initConfig)\n\n\tRootCmd.PersistentFlags().StringP(\"config\", \"\", \"\", \"config file to use\")\n\tRootCmd.PersistentFlags().BoolP(\"verbose\", \"v\", false, \"verbose output\")\n\n\tRootCmd.Flags().StringSlice(\"kafka.brokers\", []string{\"localhost:9092\"}, \"kafka brokers address\")\n\tRootCmd.Flags().String(\"metrics.addr\", \"127.0.0.1:9100\", \"metrics address\")\n\n\tif err := viper.BindPFlags(RootCmd.PersistentFlags()); err != nil {\n\t\tlog.WithError(err).Error(\"Could not bind persistent flags\")\n\t}\n\n\tif err := viper.BindPFlags(RootCmd.Flags()); err != nil {\n\t\tlog.WithError(err).Error(\"Could not bind flags\")\n\t}\n}", "func (b *Bootstrapper) Start(c core.Components) error {\n\tlog.Info(\"[ Bootstrapper ] Starting Bootstrap ...\")\n\n\trootDomainRef, err := getRootDomainRef(c)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"[ Bootstrapper ] couldn't get ref of rootDomain\")\n\t}\n\tif rootDomainRef != nil {\n\t\tb.rootDomainRef = rootDomainRef\n\t\tlog.Info(\"[ Bootstrapper ] RootDomain was found in ledger. Don't do bootstrap\")\n\t\treturn nil\n\t}\n\n\tisLightExecutor, err := isLightExecutor(c)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"[ Bootstrapper ] couldn't check if node is light executor\")\n\t}\n\tif !isLightExecutor {\n\t\tlog.Info(\"[ Bootstrapper ] Node is not light executor. Don't do bootstrap\")\n\t\treturn nil\n\t}\n\n\t_, insgocc, err := testutil.Build()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"[ Bootstrapper ] couldn't build insgocc\")\n\t}\n\n\tam := c.Ledger.GetArtifactManager()\n\tcb := testutil.NewContractBuilder(am, insgocc)\n\tdefer cb.Clean()\n\n\terr = buildSmartContracts(cb)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"[ Bootstrapper ] couldn't build contracts\")\n\t}\n\n\terr = b.activateSmartContracts(am, cb)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"[ Bootstrapper ]\")\n\t}\n\n\treturn nil\n}", "func (l *LocalService) Init() error {\n\treturn nil\n}", "func init() {\n\tinterfaces.AddPlugin(\"cloudfoundryhosting\", nil, Init)\n}" ]
[ "0.58835244", "0.58062816", "0.5806258", "0.577923", "0.5588837", "0.5588225", "0.54006773", "0.53664774", "0.5350824", "0.5263559", "0.52489525", "0.5238717", "0.5185569", "0.5158178", "0.5131922", "0.5111831", "0.51068217", "0.5072038", "0.5047539", "0.50268966", "0.50123847", "0.5006592", "0.49951142", "0.49916795", "0.49383748", "0.49211642", "0.49194044", "0.48971343", "0.4870607", "0.485414", "0.48527646", "0.48483443", "0.484313", "0.48400164", "0.48372185", "0.48357964", "0.4818945", "0.48161882", "0.481413", "0.48130026", "0.48119813", "0.48048827", "0.47947454", "0.47772083", "0.47751048", "0.47682354", "0.47656003", "0.4762466", "0.4753276", "0.4747684", "0.4740012", "0.47255328", "0.4717857", "0.46973017", "0.46935937", "0.4689735", "0.46862897", "0.46844643", "0.46731666", "0.46714842", "0.46712655", "0.4668055", "0.46636125", "0.4651024", "0.4650132", "0.46444783", "0.46434185", "0.46257198", "0.46084076", "0.46062106", "0.4599337", "0.45958626", "0.4593612", "0.45900828", "0.45880833", "0.45709485", "0.45633572", "0.45581692", "0.45544687", "0.45440164", "0.4542194", "0.45415115", "0.45405158", "0.4538664", "0.45300663", "0.45292914", "0.45265898", "0.45262444", "0.45096537", "0.450605", "0.45009163", "0.44991767", "0.4497168", "0.44968998", "0.4490861", "0.44760692", "0.4475538", "0.4472844", "0.44462696", "0.4443039" ]
0.471325
53
NewQuotaRateLimit registers a new resource with the given unique name, arguments, and options.
func NewQuotaRateLimit(ctx *pulumi.Context, name string, args *QuotaRateLimitArgs, opts ...pulumi.ResourceOption) (*QuotaRateLimit, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.Rate == nil { return nil, errors.New("invalid value for required argument 'Rate'") } var resource QuotaRateLimit err := ctx.RegisterResource("vault:index/quotaRateLimit:QuotaRateLimit", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewRateLimit(client curator.CuratorFramework, username string,\n\ttotalAllowedQuota, baseQuota int64, lockTimeout time.Duration, refreshWindow time.Duration,\n\tenableOptimization bool, optimizationPctAsk float64, optimizationPctLeft float64) (*RateLimit, error) {\n\tvar err error\n\trl := &RateLimit{\n\t\tusername: username,\n\t\ttotalAllowedQuota: totalAllowedQuota,\n\t\tusableQuotaLeft: totalAllowedQuota,\n\t\tbaseQuota: baseQuota,\n\t\tlockTimeout: lockTimeout,\n\t\trefreshWindow: refreshWindow,\n\t\tclient: client,\n\t\tbaseQuotaPath: prefix + \"/\" + username + baseSuffix,\n\t\tusableQuotaPath: prefix + \"/\" + username + usableSuffix,\n\t\ttotalQuotaPath: prefix + \"/\" + username + totalSuffix,\n\t\trefreshQuotaPath: prefix + \"/\" + username + refreshSuffix,\n\t\toptimizationPctAsk: optimizationPctAsk,\n\t\toptimizationPctLeft: optimizationPctLeft,\n\t\tenableOptimization: enableOptimization,\n\t}\n\n\t// initialize the lock to be used and inject it wherever required.\n\trl.lock, err = recipe.NewInterProcessMutex(rl.client, lockPath+username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(prefix, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(prefix+\"/\"+rl.username, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.baseQuotaPath, []byte(strconv.FormatInt(rl.baseQuota, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.totalQuotaPath, []byte(strconv.FormatInt(rl.totalAllowedQuota, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.usableQuotaPath, []byte(strconv.FormatInt(rl.usableQuotaLeft, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.refreshQuotaPath, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.addWatch()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// concurrently look to refresh quota\n\tgo rl.refreshQuota()\n\t// mimic user requests being processed with random size\n\tgo rl.startRequests()\n\t// just in case there is skewness observed through loadbalancer and\n\t// quota gets concentrated on a single rate limit node\n\tgo rl.relinquish()\n\n\treturn rl, nil\n}", "func NewRateLimit(limit int, deltat time.Duration) *RateLimit {\n\treturn &RateLimit{Rate{NewCounter(0), deltat}, limit, time.Now()}\n}", "func (m *Manager) NewRateLimit(conf ratelimit.Config) (ratelimit.V1, error) {\n\treturn bundle.AllRateLimits.Init(conf, m)\n}", "func NewRateLimit(storage store.Store, statsClient stats.Client) *RateLimit {\n\treturn &RateLimit{storage, statsClient}\n}", "func newQuota() *catalogue.Quota {\n\treturn &catalogue.Quota{\n\t\tCores: 99999,\n\t\tFloatingIPs: 99999,\n\t\tInstances: 99999,\n\t\tKeyPairs: 99999,\n\t\tRAM: 99999,\n\t\tTenant: \"test-tenant\",\n\t}\n}", "func NewRateLimiter(bandwidth, ops models.TokenBucket, opts ...RateLimiterOpt) *models.RateLimiter {\n\tlimiter := &models.RateLimiter{\n\t\tBandwidth: &bandwidth,\n\t\tOps: &ops,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(limiter)\n\t}\n\n\treturn limiter\n}", "func CreateQuota(f cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {\n\tname, err := NameFromCommandArgs(cmd, args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar generator kubectl.StructuredGenerator\n\tswitch generatorName := cmdutil.GetFlagString(cmd, \"generator\"); generatorName {\n\tcase cmdutil.ResourceQuotaV1GeneratorName:\n\t\tgenerator = &kubectl.ResourceQuotaGeneratorV1{\n\t\t\tName: name,\n\t\t\tHard: cmdutil.GetFlagString(cmd, \"hard\"),\n\t\t\tScopes: cmdutil.GetFlagString(cmd, \"scopes\"),\n\t\t}\n\tdefault:\n\t\treturn cmdutil.UsageError(cmd, fmt.Sprintf(\"Generator: %s not supported.\", generatorName))\n\t}\n\treturn RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{\n\t\tName: name,\n\t\tStructuredGenerator: generator,\n\t\tDryRun: cmdutil.GetFlagBool(cmd, \"dry-run\"),\n\t\tOutputFormat: cmdutil.GetFlagString(cmd, \"output\"),\n\t})\n}", "func (client QuotaRequestClient) Create(ctx context.Context, subscriptionID string, providerID string, location string, resourceName string, createQuotaRequest CurrentQuotaLimitBase, ifMatch string) (result QuotaRequestCreateFuture, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/QuotaRequestClient.Create\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response() != nil {\n\t\t\t\tsc = result.Response().StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.CreatePreparer(ctx, subscriptionID, providerID, location, resourceName, createQuotaRequest, ifMatch)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"reservations.QuotaRequestClient\", \"Create\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresult, err = client.CreateSender(req)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"reservations.QuotaRequestClient\", \"Create\", result.Response(), \"Failure sending request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func newQuotaPool(q int) *quotaPool {\n\tqp := &quotaPool{\n\t\tacquireChannel: make(chan int, 1),\n\t}\n\tif q > 0 {\n\t\tqp.acquireChannel <- q\n\t} else {\n\t\tqp.quota = q\n\t}\n\treturn qp\n}", "func NewLimitRate(name string, options LimitRateOptions) *LimitRate {\n\tthis := LimitRate{}\n\tthis.Name = name\n\tthis.Options = options\n\treturn &this\n}", "func NewUsageLimit(ctx *pulumi.Context,\n\tname string, args *UsageLimitArgs, opts ...pulumi.ResourceOption) (*UsageLimit, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Amount == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Amount'\")\n\t}\n\tif args.ClusterIdentifier == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ClusterIdentifier'\")\n\t}\n\tif args.FeatureType == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'FeatureType'\")\n\t}\n\tif args.LimitType == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'LimitType'\")\n\t}\n\tvar resource UsageLimit\n\terr := ctx.RegisterResource(\"aws:redshift/usageLimit:UsageLimit\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func New(config config.Config) (RateLimiter, error) {\n\n\tstorage, err := resolveBucketStore(config.Storage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlimits := []limit.Limit{}\n\tfor name, config := range config.Limits {\n\t\tlimit, err := limit.New(name, config, storage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlimits = append(limits, limit)\n\t}\n\n\trateLimiter := &rateLimiter{limits: limits}\n\treturn rateLimiter, nil\n}", "func New(c *aqm.Config) *Limiter {\n\tl := &Limiter{\n\t\trate: vegas.New(),\n\t\tqueue: aqm.New(c),\n\t}\n\tgo func() {\n\t\tticker := time.NewTicker(time.Second * 1)\n\t\tdefer ticker.Stop()\n\t\tfor {\n\t\t\t<-ticker.C\n\t\t\tv := l.rate.Stat()\n\t\t\tq := l.queue.Stat()\n\t\t\tlog.Info(\"rate/limit: limit(%d) inFlight(%d) minRtt(%v) rtt(%v) codel packets(%d)\", v.Limit, v.InFlight, v.MinRTT, v.LastRTT, q.Packets)\n\t\t}\n\t}()\n\treturn l\n}", "func CreateResourceQuota(parent *tenancyv1alpha1.TanzuNamespace) (metav1.Object, error) {\n\n\tfmap := template.FuncMap{\n\t\t\"defaultResourceQuotaCPURequests\": defaultResourceQuotaCPURequests,\n\t\t\"defaultResourceQuotaMemoryRequests\": defaultResourceQuotaMemoryRequests,\n\t\t\"defaultResourceQuotaCPULimits\": defaultResourceQuotaCPULimits,\n\t\t\"defaultResourceQuotaMemoryLimits\": defaultResourceQuotaMemoryLimits,\n\t}\n\n\tchildContent, err := runTemplate(\"tanzu-resource-quota\", resourceResourceQuota, parent, fmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdecode := scheme.Codecs.UniversalDeserializer().Decode\n\tobj, _, err := decode([]byte(childContent), nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresourceObj := obj.(*k8s_api.ResourceQuota)\n\tresourceObj.Namespace = defaultNamespace(parent.Name, &parent.Spec)\n\n\treturn resourceObj, nil\n}", "func NewLimiter(rate float64, burst float64, initialTokens float64) *Limiter {\n\treturn &Limiter{\n\t\trate: rate,\n\t\tburst: burst,\n\t\ttokens: initialTokens,\n\t\tlast: time.Now(),\n\t}\n}", "func NewResourceQuota(client clientset.Interface, registry quota.Registry) (admission.Interface, error) {\n\tliveLookupCache, err := lru.New(100)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlw := &cache.ListWatch{\n\t\tListFunc: func(options api.ListOptions) (runtime.Object, error) {\n\t\t\treturn client.Core().ResourceQuotas(api.NamespaceAll).List(options)\n\t\t},\n\t\tWatchFunc: func(options api.ListOptions) (watch.Interface, error) {\n\t\t\treturn client.Core().ResourceQuotas(api.NamespaceAll).Watch(options)\n\t\t},\n\t}\n\tindexer, reflector := cache.NewNamespaceKeyedIndexerAndReflector(lw, &api.ResourceQuota{}, 0)\n\treflector.Run()\n\treturn &quotaAdmission{\n\t\tHandler: admission.NewHandler(admission.Create, admission.Update),\n\t\tclient: client,\n\t\tindexer: indexer,\n\t\tregistry: registry,\n\t\tliveLookupCache: liveLookupCache,\n\t\tliveTTL: time.Duration(30 * time.Second),\n\t}, nil\n}", "func NewCmdCreateQuota(f cmdutil.Factory, cmdOut io.Writer) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"quota NAME [--hard=key1=value1,key2=value2] [--scopes=Scope1,Scope2] [--dry-run=bool]\",\n\t\tAliases: []string{\"resourcequota\"},\n\t\tShort: i18n.T(\"Create a quota with the specified name.\"),\n\t\tLong: quotaLong,\n\t\tExample: quotaExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\terr := CreateQuota(f, cmdOut, cmd, args)\n\t\t\tcmdutil.CheckErr(err)\n\t\t},\n\t}\n\n\tcmdutil.AddApplyAnnotationFlags(cmd)\n\tcmdutil.AddValidateFlags(cmd)\n\tcmdutil.AddPrinterFlags(cmd)\n\tcmdutil.AddGeneratorFlags(cmd, cmdutil.ResourceQuotaV1GeneratorName)\n\tcmd.Flags().String(\"hard\", \"\", i18n.T(\"A comma-delimited set of resource=quantity pairs that define a hard limit.\"))\n\tcmd.Flags().String(\"scopes\", \"\", i18n.T(\"A comma-delimited set of quota scopes that must all match each object tracked by the quota.\"))\n\treturn cmd\n}", "func New(opts Options) (*Queue, error) {\n\tif opts.HardLimit <= 0 || opts.HardLimit < opts.SoftQuota {\n\t\treturn nil, errHardLimit\n\t}\n\tif opts.BurstCredit < 0 {\n\t\treturn nil, errBurstCredit\n\t}\n\tif opts.SoftQuota <= 0 {\n\t\topts.SoftQuota = opts.HardLimit\n\t}\n\tif opts.BurstCredit == 0 {\n\t\topts.BurstCredit = float64(opts.SoftQuota)\n\t}\n\tsentinel := new(entry)\n\tq := &Queue{\n\t\tsoftQuota: opts.SoftQuota,\n\t\thardLimit: opts.HardLimit,\n\t\tcredit: opts.BurstCredit,\n\t\tback: sentinel,\n\t\tfront: sentinel,\n\t}\n\tq.nempty = sync.NewCond(&q.mu)\n\treturn q, nil\n}", "func (c *SpaceQuotaClient) Create(ctx context.Context, r *resource.SpaceQuotaCreateOrUpdate) (*resource.SpaceQuota, error) {\n\tvar q resource.SpaceQuota\n\t_, err := c.client.post(ctx, \"/v3/space_quotas\", r, &q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &q, nil\n}", "func New(policy *Policy) *RateLimiter {\n\trl := &RateLimiter{\n\t\tpolicy: policy,\n\t\tstartTime: nowFunc(),\n\t}\n\treturn rl\n}", "func (client QuotaRequestClient) CreatePreparer(ctx context.Context, subscriptionID string, providerID string, location string, resourceName string, createQuotaRequest CurrentQuotaLimitBase, ifMatch string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"location\": autorest.Encode(\"path\", location),\n\t\t\"providerId\": autorest.Encode(\"path\", providerID),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", subscriptionID),\n\t}\n\n\tconst APIVersion = \"2019-07-19-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPut(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}\", pathParameters),\n\t\tautorest.WithJSON(createQuotaRequest),\n\t\tautorest.WithQueryParameters(queryParameters),\n\t\tautorest.WithHeader(\"If-Match\", autorest.String(ifMatch)))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func CreateRateLimiter(limit int) RateLimiter {\n\treturn &rateLimiter{limit: limit}\n}", "func New(qps int64) *limiter {\n\tif qps <= 0 {\n\t\treturn nil\n\t}\n\n\trl := &limiter{\n\t\tqps: qps,\n\t}\n\trl.current = make(map[string]int64, 0)\n\n\t// launch a goroutine to reset the counter every second\n\tgo rl.reset()\n\n\treturn rl\n}", "func (m *Manager) StoreRateLimit(ctx context.Context, name string, conf ratelimit.Config) error {\n\treturn component.ErrInvalidType(\"rate_limit\", conf.Type)\n}", "func New(timeout time.Duration, cache GetSetter) Throttler {\n\tsalt, err := randomBytes(16)\n\tif err != nil {\n\t\tpanic(\"cannot initialize rate limiter\")\n\t}\n\treturn &Limiter{\n\t\tcache: cache,\n\t\ttimeout: timeout,\n\t\tsalt: salt,\n\t}\n}", "func NewLimiter(max int64, ttl time.Duration, conf *rate.ConfigRedis) *Limiter {\n\tlimiter := &Limiter{Max: max, TTL: ttl}\n\tlimiter.MessageContentType = \"text/plain; charset=utf-8\"\n\tlimiter.Message = \"You have reached maximum request limit.\"\n\tlimiter.StatusCode = 429\n\tlimiter.tokenBuckets = make(map[string]*rate.Limiter)\n\tlimiter.IPLookups = []string{\"RemoteAddr\", \"X-Forwarded-For\", \"X-Real-IP\"}\n\n\tif err := rate.SetRedis(conf); err != nil {\n\t\tlog.Println(\"fail to set rate limiter's redis: \", err)\n\t}\n\n\treturn limiter\n}", "func New(rate int, opts ...Option) Limiter {\n\treturn newAtomicBased(rate, opts...)\n}", "func getResourceQuota(cpu, memory int) *v1.ResourceQuota {\n\t// Don's use \"MustParse\" it might panic at runtime , have some validation\n\thard := v1.ResourceList{\n\t\tv1.ResourceCPU: resource.MustParse(getCPUMilli(cpu)),\n\t\tv1.ResourceMemory: resource.MustParse(getMemoryMI(memory)),\n\t}\n\n\treturn &v1.ResourceQuota{\n\t\tSpec: v1.ResourceQuotaSpec{\n\t\t\tHard: hard,\n\t\t},\n\t}\n}", "func New(quantum time.Duration) *limiter {\n\tl := &limiter{\n\t\tquantum: quantum,\n\t\tschedule: make(chan ask, 1),\n\t\tclosecap: make(chan bool, 1),\n\t\tdone: make(chan bool),\n\t}\n\tl.closecap <- true\n\tgo l.run()\n\treturn l\n}", "func New(rate int, opts ...Option) Limiter {\r\n\treturn newAtomicBased(rate, opts...)\r\n}", "func newRateLimiter(delay time.Duration) *rateLimiter {\n\treturn &rateLimiter{\n\t\tdelay: delay,\n\t\tops: make(map[string]time.Time),\n\t}\n}", "func NewRateLimiter(r rate.Limit, b int) *RateLimiter {\n\treturn NewRateLimiterWithValue(r, b, 0)\n}", "func NewRateLimiter(limit int64) *limiter {\n\treturn &limiter{\n\t\tstart: time.Now(),\n\t\tlimit: limit,\n\t\tdelay: 0.5,\n\t}\n}", "func NewRateLimiter(capacity int) *RateLimiter {\n\tsemaphore := make(chan bool, capacity)\n\n\t// Fill channel\n\tfor i := 0; i < capacity; i++ {\n\t\tsemaphore <- true\n\t}\n\n\treturn &RateLimiter{semaphore}\n}", "func NewLimiter(\n\tlimiterGUID string,\n\trateStr string,\n\trateType string,\n\tkeyGetter KeyGetter,\n\treporter RateExceededReporter,\n\tmaxEntriesInMemory int,\n\tbehavior string,\n\terrorCode int,\n\terrorSubCode int,\n\tmetricLabel string,\n\tmetric *prometheus.CounterVec,\n\tmetricIncrementer MetricIncrementer,\n\topts ...golimiter.Option) (l RateLimiter, err error) {\n\trate, err := golimiter.NewRateFromFormatted(rateStr)\n\tif err != nil {\n\t\treturn l, err\n\t}\n\t// gotta override the default exp with the rate's exp (regardless of opts)\n\tnewOpts := append([]golimiter.Option{golimiter.WithLimiterExpiration(rate.Period)}, opts...)\n\tstore := golimiter.NewInMemoryLimiterStore(maxEntriesInMemory, newOpts...)\n\tif limiterGUID == \"\" {\n\t\tlimiterGUID = uuid.New().String()\n\t}\n\tl = RateLimiter{\n\t\tLimiterGUID: limiterGUID,\n\t\tLimiter: golimiter.New(store, rate),\n\t\tStore: store,\n\t\tKeyGetter: keyGetter,\n\t\tReporter: reporter,\n\t\tType: rateType,\n\t\tBehavior: behavior,\n\t\tRate: rateStr,\n\t\tErrorCode: errorCode,\n\t\tErrorSubCode: errorCode,\n\t\tMetricLabel: metricLabel,\n\t\tMetric: metric,\n\t\tMetricIncremeter: metricIncrementer,\n\t}\n\treturn l, nil\n}", "func CreateLimiter(limit rate.Limit) *rate.Limiter {\n\treturn rate.NewLimiter(limit, GetGoodBurst(limit))\n}", "func NewRateLimiter(r float64, b int) *RateLimiter {\n\treturn &RateLimiter{limiter: rate.NewLimiter(rate.Limit(r), b)}\n}", "func WithRateLimit(rateLimit float64, burst int) RPCOption {\n\treturn func(cfg *rpcConfig) error {\n\t\tcfg.limit = rateLimit\n\t\tcfg.burst = burst\n\t\treturn nil\n\t}\n}", "func NewRateLimiter(h cachemanager.Handler) RateLimiter {\n\treturn &rateLimiter{\n\t\tbuckets: make(map[time.Duration]int),\n\t\thandler: h,\n\t}\n}", "func ratelimiter(args map[string]interface{}) *ratelimit.Ratelimiter {\n\trate, err := strconv.Atoi(args[\"--ratelimit-max-rate\"].(string))\n\tif err != nil {\n\t\tlog.Fatalf(\"error parsing --ratelimit-max-rate: %s\", err)\n\t}\n\n\tif rate <= 0 {\n\t\treturn nil\n\t}\n\n\tkeys, err := strconv.Atoi(args[\"--ratelimit-max-keys\"].(string))\n\tif err != nil {\n\t\tlog.Fatalf(\"error parsing --ratelimit-max-keys: %s\", err)\n\t}\n\n\treturn ratelimit.New(rate, keys)\n}", "func NewRateLimiter(store data.Store, threshold int) *RateLimiter {\n\treturn &RateLimiter{\n\t\tstore: store,\n\t\tthreshold: threshold,\n\t}\n}", "func newRateLimiter() *middlewares.Limiter {\n\treturn middlewares.NewLimiter(newRedis())\n}", "func registerRateLimitServiceServer(s *grpc.Server, srv ratelimit.RateLimitServiceServer) {\n\ts.RegisterService(&_rateLimitService_serviceDesc, srv)\n}", "func (f *FakeWorkQueue) AddRateLimited(item interface{}) {}", "func NewRateLimiter(freq time.Duration, burstSize int) *Limiter {\n\treturn &Limiter{\n\t\tconnectionFreq: freq,\n\t\tconnectionBurstSize: burstSize,\n\t}\n}", "func NewRateLimiter(intervalInMillis int64, maxInInterval int, client *redis.Client) *RateLimiter {\n\treturn &RateLimiter{\n\t\tintervalInMillis: intervalInMillis,\n\t\tmaxInInterval: maxInInterval,\n\t\tclient: client,\n\t}\n}", "func (h *handlerState) Quota(ctx context.Context, tracker attribute.Tracker, request *mixerpb.QuotaRequest, response *mixerpb.QuotaResponse) {\n\tresponse.RequestIndex = request.RequestIndex\n\tstatus := h.execute(ctx, tracker, request.AttributeUpdate, config.QuotaMethod)\n\n\tif status.Code == int32(code.Code_OK) {\n\t\tresponse.Amount = 1\n\t}\n}", "func NewQpsLimiter(opts ...QpsLimiterOpt) (*QpsLimiter, error) {\r\n\tvar qpsLimiter QpsLimiter\r\n\tif SetQpsLimiterErr := qpsLimiter.SetQpsLimiter(opts...); nil != SetQpsLimiterErr {\r\n\t\treturn nil, fmt.Errorf(\"SetQpsLimiter failed -> SetQpsLimiterErr:%v\", SetQpsLimiterErr)\r\n\t}\r\n\taddKillerCheck(killerFirstPriority, \"qpsLimiter_\"+qpsLimiter.bc.CfgData.Service, &qpsLimiter)\r\n\treturn &qpsLimiter, nil\r\n}", "func newRateLimiter() *rateLimiter {\n\tdecayFactor := 9.0 / 8.0\n\treturn &rateLimiter{\n\t\tstats: info.RateLimiterStats{\n\t\t\tTargetRate: 1,\n\t\t},\n\t\tdecayPeriod: 5 * time.Second,\n\t\tdecayFactor: decayFactor,\n\t\texit: make(chan struct{}),\n\t}\n}", "func NewRateLimiter(interval time.Duration, n int) *RateLimiter {\n\treturn &RateLimiter{\n\t\tips: make(map[string]*rate.Limiter),\n\t\tinterval: rate.Every(interval),\n\t\tn: n,\n\t}\n}", "func ResourceQuotaForPriorityClassScope(name, namespace string, priorityClasses []string) *corev1.ResourceQuota {\n\treturn &corev1.ResourceQuota{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"v1\",\n\t\t\tKind: \"ResourceQuota\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t},\n\t\tSpec: corev1.ResourceQuotaSpec{\n\t\t\tScopeSelector: &corev1.ScopeSelector{\n\t\t\t\tMatchExpressions: []corev1.ScopedResourceSelectorRequirement{\n\t\t\t\t\t{\n\t\t\t\t\t\tScopeName: corev1.ResourceQuotaScopePriorityClass,\n\t\t\t\t\t\tOperator: corev1.ScopeSelectorOpIn,\n\t\t\t\t\t\tValues: priorityClasses,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func New(limits *Limits, header interface{}, c *redis.Client) *Limiter {\n\tlMap := make(limitsMap)\n\n\tif c == nil {\n\t\tvar err error\n\t\tclient, err = goredisify.Conn(os.Getenv(\"REDIS_URL\"))\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t} else {\n\t\tclient = c\n\t}\n\n\tfor _, limit := range *limits {\n\t\tkey := limit.Method + \":\" + limit.Path\n\t\tlMap[key] = limit\n\t}\n\n\treturn &Limiter{header, lMap}\n}", "func (client AccountQuotaPolicyClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, policyName string, body AccountQuotaPolicyResourceDescription) (result AccountQuotaPolicyCreateOrUpdateFuture, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/AccountQuotaPolicyClient.CreateOrUpdate\")\n defer func() {\n sc := -1\n if result.Response() != nil {\n sc = result.Response().StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n if err := validation.Validate([]validation.Validation{\n { TargetValue: body,\n Constraints: []validation.Constraint{\t{Target: \"body.AccountQuotaPolicyResourceDescriptionProperties\", Name: validation.Null, Rule: true, Chain: nil }}}}); err != nil {\n return result, validation.NewError(\"microsoftazuremanagementaisupercomputer.AccountQuotaPolicyClient\", \"CreateOrUpdate\", err.Error())\n }\n\n req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, accountName, policyName, body)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"microsoftazuremanagementaisupercomputer.AccountQuotaPolicyClient\", \"CreateOrUpdate\", nil , \"Failure preparing request\")\n return\n }\n\n result, err = client.CreateOrUpdateSender(req)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"microsoftazuremanagementaisupercomputer.AccountQuotaPolicyClient\", \"CreateOrUpdate\", result.Response(), \"Failure sending request\")\n return\n }\n\n return\n}", "func (e *EnqueueRequestForNamespaces) Create(ctx context.Context, evt event.CreateEvent, q workqueue.RateLimitingInterface) {\n\te.add(ctx, evt.Object, q)\n}", "func (client AccountQuotaPolicyClient) CreateOrUpdateSender(req *http.Request) (future AccountQuotaPolicyCreateOrUpdateFuture, err error) {\n var resp *http.Response\n resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n if err != nil {\n return\n }\n future.Future, err = azure.NewFutureFromResponse(resp)\n return\n }", "func NewRateLimiter(strategy RateLimiterStrategy, recheckPeriod time.Duration) *RateLimiter {\n\treturn &RateLimiter{\n\t\tstrategy: strategy,\n\t\trecheckPeriod: recheckPeriod,\n\t\ttenants: map[string]*tenantLimiter{},\n\t}\n}", "func NewRateLimiter(rate float64, capacity int64) *Limiter {\n\treturn &Limiter{\n\t\tresponder: RateLimitResponder,\n\t\tbucket: ratelimit.NewBucketWithRate(rate, capacity),\n\t}\n}", "func NewRateLimiter(config *config.RuntimeSecurityConfig, client statsd.ClientInterface) *RateLimiter {\n\trl := &RateLimiter{\n\t\tlimiters: make(map[string]Limiter),\n\t\tstatsdClient: client,\n\t\tconfig: config,\n\t}\n\n\treturn rl\n}", "func (n *Globals) SetRateLimit(url string, maxTimes int, duration time.Duration) {\n\tn.rateLimiterData[url] = RateLimiterData{\n\t\tmaxTimes,\n\t\tduration,\n\t}\n\tn.rateLimiters[url] = rate.New(maxTimes, duration)\n}", "func NewRateLimitWatcher(c Client, logger log.Logger, threshold int) AroundFunctionCreator {\n\treturn &rateLimitWatcher{client: c, logger: logger, threshold: threshold}\n}", "func (client AccountQuotaPolicyClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, accountName string, policyName string, body AccountQuotaPolicyResourceDescription) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"accountName\": accountName,\n \"policyName\": policyName,\n \"resourceGroupName\": resourceGroupName,\n \"subscriptionId\": autorest.Encode(\"path\",client.SubscriptionID),\n }\n\n const APIVersion = \"2020-12-01-preview\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPut(),\nautorest.WithBaseURL(client.BaseURI),\nautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.AISupercomputer/accounts/{accountName}/accountQuotaPolicies/{policyName}\",pathParameters),\nautorest.WithJSON(body),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func NewRateLimitSyncer(registry *ratelimit.Registry, serviceLister externalServiceLister) *RateLimitSyncer {\n\tr := &RateLimitSyncer{\n\t\tregistry: registry,\n\t\tserviceLister: serviceLister,\n\t\tlimit: 500,\n\t}\n\treturn r\n}", "func GetQuotaRateLimit(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *QuotaRateLimitState, opts ...pulumi.ResourceOption) (*QuotaRateLimit, error) {\n\tvar resource QuotaRateLimit\n\terr := ctx.ReadResource(\"vault:index/quotaRateLimit:QuotaRateLimit\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s *grpcServer) Quota(stream mixerpb.Mixer_QuotaServer) error {\n\treturn s.dispatcher(stream, \"/istio.mixer.v1.Mixer/Quota\",\n\t\tfunc() (proto.Message, proto.Message, *mixerpb.Attributes, *mixerpb.Attributes, *rpc.Status) {\n\t\t\trequest := &mixerpb.QuotaRequest{}\n\t\t\tresponse := &mixerpb.QuotaResponse{}\n\t\t\tresponse.AttributeUpdate = &mixerpb.Attributes{}\n\t\t\treturn request, response, &request.AttributeUpdate, response.AttributeUpdate, &response.Result\n\t\t},\n\t\tfunc(ctx context.Context, requestBag *attribute.MutableBag, responseBag *attribute.MutableBag, request proto.Message, response proto.Message) {\n\t\t\ts.handlers.Quota(ctx, requestBag, responseBag, request.(*mixerpb.QuotaRequest), response.(*mixerpb.QuotaResponse))\n\t\t})\n}", "func NewLimiter(limit int64, seconds int) Limiter {\n\treturn &concreteLimiter{\n\t\tRedisCli: cache.GetRedis(),\n\t\tLimit: limit,\n\t\tSeconds: seconds,\n\t}\n}", "func NewRateLimiter(max float64, purgeDuration time.Duration) RateLimiter {\n\trl := RateLimiter{}\n\n\tif purgeDuration == 0 {\n\t\trl = RateLimiter{\n\t\t\ttollbooth.NewLimiter(max, nil),\n\t\t\tfalse,\n\t\t}\n\t} else {\n\t\trl = RateLimiter{\n\t\t\ttollbooth.NewLimiter(max, &limiter.ExpirableOptions{DefaultExpirationTTL: purgeDuration}),\n\t\t\tfalse,\n\t\t}\n\t}\n\n\trl.Limiter.SetIPLookups([]string{\"X-Forwarded-For\", \"RemoteAddr\", \"X-Real-IP\"})\n\n\treturn rl\n}", "func (at *Onlinesim) SetRateLimit(customRateLimit int) {\n\tat.rateLimiter = time.Tick(time.Second / time.Duration(customRateLimit))\n}", "func AddQuota(quota models.Quota) (int64, error) {\n\tnow := time.Now()\n\tquota.CreationTime = now\n\tquota.UpdateTime = now\n\treturn GetOrmer().Insert(&quota)\n}", "func RegisterResourceLimit(limits map[ResourceName]string) error {\n\tif len(limits) == 2 && verifyString(limits[ResourceCPU]) && verifyString(limits[ResourceMemory]) {\n\t\tresourceLimit[ResourceCPU] = limits[ResourceCPU]\n\t\tresourceLimit[ResourceMemory] = limits[ResourceMemory]\n\t\treturn nil\n\t}\n\treturn errors.New(\"resource limit must include cpu and memory and only include cpu and memory\")\n\n}", "func New(ctx context.Context, rate, timespan int) (Bucket, error) {\n\tq := make(chan struct{}, rate)\n\tb := Bucket{ctx: ctx, queue: q, rate: rate, timespan: timespan}\n\tgo b.leak()\n\treturn b, nil // maybe return pointer?\n}", "func NewItemQuotaRequestBuilder(rawUrl string, requestAdapter i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.RequestAdapter)(*ItemQuotaRequestBuilder) {\n urlParams := make(map[string]string)\n urlParams[\"request-raw-url\"] = rawUrl\n return NewItemQuotaRequestBuilderInternal(urlParams, requestAdapter)\n}", "func NewLimiter() *Limiter {\n\treturn &Limiter{\n\t\tstamp: make(map[string]float64),\n\t}\n}", "func NewTimeLimiter(timeWindow time.Duration, capacity int64) *Limiter {\n\treturn &Limiter{\n\t\tresponder: RateLimitResponder,\n\t\tbucket: ratelimit.NewBucket(timeWindow, capacity),\n\t}\n}", "func NewRateLimiter(rateBytesPerSec, refillPeriodMicros int64, fairness int32) *RateLimiter {\n\tcR := C.rocksdb_ratelimiter_create(\n\t\tC.int64_t(rateBytesPerSec),\n\t\tC.int64_t(refillPeriodMicros),\n\t\tC.int32_t(fairness),\n\t)\n\treturn newNativeRateLimiter(cR)\n}", "func NewCommand() *cli.Command { //nolint:funlen\n\tconst (\n\t\tapiKeyMinLength = 8\n\t)\n\n\treturn &cli.Command{\n\t\tName: \"quota\",\n\t\tAliases: []string{\"q\"},\n\t\tUsage: \"Get currently used quota\",\n\t\tAction: func(c *cli.Context) error {\n\t\t\tvar apiKeys = c.StringSlice(shared.APIKeyFlag.Name)\n\n\t\t\tif len(apiKeys) == 0 {\n\t\t\t\treturn errors.New(\"API key(s) was not provided\")\n\t\t\t}\n\n\t\t\tvar (\n\t\t\t\tctx, cancel = context.WithCancel(c.Context) // main context creation\n\t\t\t\toss = breaker.NewOSSignals(ctx) // OS signals listener\n\t\t\t)\n\n\t\t\toss.Subscribe(func(os.Signal) { cancel() })\n\n\t\t\tdefer func() {\n\t\t\t\tcancel() // call cancellation function after all for \"service\" goroutines stopping\n\t\t\t\toss.Stop() // stop system signals listening\n\t\t\t}()\n\n\t\t\tvar (\n\t\t\t\twg sync.WaitGroup\n\t\t\t\terrColor = text.Colors{text.FgRed, text.Bold}\n\t\t\t)\n\n\t\t\tfor _, key := range apiKeys {\n\t\t\t\tif len(key) <= apiKeyMinLength {\n\t\t\t\t\t_, _ = fmt.Fprint(os.Stderr, errColor.Sprintf(\"API key (%s) is too short\\n\", key))\n\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\twg.Add(1)\n\n\t\t\t\tgo func(key string) {\n\t\t\t\t\tdefer wg.Done()\n\n\t\t\t\t\tif ctx.Err() != nil { // check if context was canceled\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tif count, err := tinypng.NewClient(key).UsedQuota(ctx); err != nil {\n\t\t\t\t\t\t_, _ = fmt.Fprint(os.Stderr, errColor.Sprintf(\"Key %s error: %s\\n\", maskString(key), err))\n\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar color = text.FgRed\n\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase count <= 300: //nolint:gomnd\n\t\t\t\t\t\t\tcolor = text.FgGreen\n\n\t\t\t\t\t\tcase count <= 400: //nolint:gomnd\n\t\t\t\t\t\t\tcolor = text.FgYellow\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t_, _ = fmt.Fprintf(os.Stdout,\n\t\t\t\t\t\t\t\"Used quota (key %s) is: %s\\n\",\n\t\t\t\t\t\t\ttext.Colors{text.FgHiBlue}.Sprint(maskString(key)),\n\t\t\t\t\t\t\ttext.Colors{color, text.Bold}.Sprintf(\"%d\", count),\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}(key)\n\t\t\t}\n\n\t\t\twg.Wait()\n\n\t\t\treturn nil\n\t\t},\n\t\tFlags: []cli.Flag{\n\t\t\tshared.APIKeyFlag,\n\t\t},\n\t}\n}", "func NewTokenBucket(capacity uint32, rate time.Duration, lifetime time.Duration) (*TokenBucket, error) {\n\t// To protect for inaccurate function usage. In case of rate == 0 returns - error.\n\tif rate == 0 {\n\t\treturn nil, errors.ErrTokenBucketInvalidFillRate\n\t}\n\n\ttb := &TokenBucket{\n\t\t//ctx: ctx,\n\t\tcapacity: capacity,\n\t\tcurrentAmount: capacity,\n\t\trate: rate,\n\t\tlifeTime: lifetime,\n\t\tlastAccessTime: time.Now(),\n\t\tshutDown: make(chan bool, 1),\n\t\tmx: sync.RWMutex{},\n\t}\n\t// Create a go routine with the time.Ticker to fill the bucket with desired rate.\n\tgo func(tb *TokenBucket) {\n\t\ttb.ticker = time.NewTicker(tb.rate)\n\n\t\tdefer tb.ticker.Stop()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-tb.ticker.C:\n\t\t\t\ttb.mx.RLock()\n\t\t\t\tif time.Since(tb.lastAccessTime) > tb.lifeTime {\n\t\t\t\t\t// Inactive timeout exeded - initiate the closure procedure of the bucket.\n\t\t\t\t\t// log.Println(\"Idle timeout exiting...\")\n\t\t\t\t\ttb.shutDown <- true\n\t\t\t\t\ttb.mx.RUnlock()\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ttb.mx.RUnlock()\n\n\t\t\t\tif tb.currentAmount == tb.capacity { //Token Bucken is full all next tokens will be discarded\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\ttb.mx.Lock()\n\t\t\t\ttb.currentAmount++ // Add one token to the bucket\n\t\t\t\ttb.mx.Unlock()\n\t\t\tdefault: // Added to avoid blocking when we have looong time period for ticker\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}(tb)\n\n\treturn tb, nil\n}", "func NewLimiterWithMetrics(n int, maxConnsCount, concurrentConnsCount, waitingConnsCount prometheus.Gauge) *Limiter {\n\tmaxConnsCount.Set(float64(n))\n\n\treturn &Limiter{\n\t\tsem: make(chan struct{}, n),\n\t\tconcurrentConnsCount: concurrentConnsCount,\n\t\twaitingConnsCount: waitingConnsCount,\n\t}\n}", "func New() *Limiter {\n\tl := &Limiter{make(chan int, 1), make(chan struct{}, 1)}\n\tl.waiter <- struct{}{}\n\treturn l\n}", "func RegisterQuotaPlugin(factory QuotaPluginFactory) {\n\tif factory == nil {\n\t\tpanic(\"collector.RegisterQuotaPlugin() called with nil QuotaPluginFactory instance\")\n\t}\n\tinfo := factory(ServiceConfiguration{}, map[string]bool{}).ServiceInfo()\n\tif info.Type == \"\" {\n\t\tpanic(\"QuotaPlugin instance with empty service type!\")\n\t}\n\tif info.Area == \"\" {\n\t\tpanic(\"QuotaPlugin instance with empty area!\")\n\t}\n\tif quotaPluginFactories[info.Type] != nil {\n\t\tpanic(\"collector.RegisterQuotaPlugin() called multiple times for service type: \" + info.Type)\n\t}\n\tquotaPluginFactories[info.Type] = factory\n\tserviceTypesByArea[info.Area] = append(serviceTypesByArea[info.Area], info.Type)\n}", "func SetRateLimit() *RateLimit {\n\treturn &RateLimit{\n\t\tSpot: request.NewRateLimit(huobiSpotRateInterval, huobiSpotRequestRate),\n\t\tFuturesAuth: request.NewRateLimit(huobiFuturesRateInterval, huobiFuturesAuthRequestRate),\n\t\tFuturesUnauth: request.NewRateLimit(huobiFuturesRateInterval, huobiFuturesUnAuthRequestRate),\n\t\tSwapAuth: request.NewRateLimit(huobiSwapRateInterval, huobiSwapAuthRequestRate),\n\t\tSwapUnauth: request.NewRateLimit(huobiSwapRateInterval, huobiSwapUnauthRequestRate),\n\t\tFuturesXfer: request.NewRateLimit(huobiFuturesTransferRateInterval, huobiFuturesTransferReqRate),\n\t}\n}", "func (p *nfsProvisioner) createQuota(directory string, capacity resource.Quantity) (string, uint16, error) {\n\tpath := path.Join(p.exportDir, directory)\n\n\tlimit := strconv.FormatInt(capacity.Value(), 10)\n\n\tblock, projectID, err := p.quotaer.AddProject(path, limit)\n\tif err != nil {\n\t\treturn \"\", 0, fmt.Errorf(\"error adding project for path %s: %v\", path, err)\n\t}\n\n\terr = p.quotaer.SetQuota(projectID, path, limit)\n\tif err != nil {\n\t\tp.quotaer.RemoveProject(block, projectID)\n\t\treturn \"\", 0, fmt.Errorf(\"error setting quota for path %s: %v\", path, err)\n\t}\n\n\treturn block, projectID, nil\n}", "func newLimiter() *limiter.Limiter {\n\n\tlmt := tollbooth.NewLimiter(2, &limiter.ExpirableOptions{DefaultExpirationTTL: time.Hour})\n\n\tlmt.SetIPLookups([]string{\"X-Forwarded-For\", \"RemoteAddr\", \"X-Real-IP\"})\n\tlmt.SetOnLimitReached(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"request limit reached\")\n\t})\n\n\treturn lmt\n\n}", "func (in *RateLimit) DeepCopy() *RateLimit {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RateLimit)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (a *Client) SetQuota(params *SetQuotaParams) (*SetQuotaOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewSetQuotaParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"setQuota\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/api/v1/quotas\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &SetQuotaReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*SetQuotaOK), nil\n\n}", "func (k *KogitoAppBuildObject) AddResourceLimit(name, value string) {\n\tif k.Resources.Limits == nil {\n\t\tk.Resources.Limits = corev1.ResourceList{}\n\t}\n\n\tk.Resources.Limits[corev1.ResourceName(name)] = resource.MustParse(value)\n}", "func ExampleSetLongRateLimit() {\n\tSetLongRateLimit(500, 10*time.Minute)\n}", "func (j *JuiceFSEngine) genQuotaCmd(value *JuiceFS, mount datav1alpha1.Mount) error {\n\toptions := mount.Options\n\tfor k, v := range options {\n\t\tif k == \"quota\" {\n\t\t\tqs, err := j.getQuota(v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"invalid quota %s\", v)\n\t\t\t}\n\t\t\tif value.Fuse.SubPath == \"\" {\n\t\t\t\treturn fmt.Errorf(\"subPath must be set when quota is enabled\")\n\t\t\t}\n\t\t\tif value.Edition == CommunityEdition {\n\t\t\t\t// ce\n\t\t\t\t// juicefs quota set ${metaurl} --path ${path} --capacity ${capacity}\n\t\t\t\tvalue.Configs.QuotaCmd = fmt.Sprintf(\"%s quota set %s --path %s --capacity %d\", common.JuiceCeCliPath, value.Source, value.Fuse.SubPath, qs)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// ee\n\t\t\t// juicefs quota set ${metaurl} --path ${path} --capacity ${capacity}\n\t\t\tcli := common.JuiceCliPath\n\t\t\tvalue.Configs.QuotaCmd = fmt.Sprintf(\"%s quota set %s --path %s --capacity %d\", cli, value.Source, value.Fuse.SubPath, qs)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}", "func NewTokenBucketRateLimiter(qps float32, burst int) RateLimiter {\n\tlimiter := rate.NewLimiter(rate.Limit(qps), burst)\n\treturn newTokenBucketRateLimiter(limiter, realClock{}, qps)\n}", "func (c *Limiter) Create() Limit {\n\treturn rate.NewLimiter(\n\t\trate.Every(c.connectionFreq),\n\t\tc.connectionBurstSize)\n}", "func (m *Drive) SetQuota(value Quotaable)() {\n m.quota = value\n}", "func (lim *Limiter) AddLimit() {\n\tnow, newLimit := lim.queue(time.Now())\n\n\tlim.last = now\n\tlim.limit = newLimit\n\n\t//fmt.Println(lim)\n}", "func (bas *BaseService) SetRateLimit(persec int) {\n\tbas.rlock.Lock()\n\tdefer bas.rlock.Unlock()\n\n\tif persec == 0 {\n\t\tbas.rlimit = nil\n\t\treturn\n\t}\n\n\tbas.rlimit = ratelimit.New(persec, ratelimit.WithoutSlack)\n}", "func (client *AccountsClient) listUsagesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientListUsagesOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/usages\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif accountName == \"\" {\n\t\treturn nil, errors.New(\"parameter accountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-05-01\")\n\tif options != nil && options.Filter != nil {\n\t\treqQP.Set(\"$filter\", *options.Filter)\n\t}\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func CreateUsageTimeLimitPolicy() *policy.UsageTimeLimit {\n\tnow := time.Now()\n\tdailyTimeUsageLimit := policy.RefTimeUsageLimitEntry{\n\t\tLastUpdatedMillis: strconv.FormatInt(now.Unix(), 10 /*base*/),\n\t\t// There's 1440 minutes in a day, so no screen time limit.\n\t\tUsageQuotaMins: 1440,\n\t}\n\n\thour, _, _ := now.Clock()\n\tresetTime := policy.RefTime{\n\t\t// Make sure the policy doesn't reset before the test ends\n\t\tHour: (hour + 2) % 24,\n\t\tMinute: 0,\n\t}\n\treturn &policy.UsageTimeLimit{\n\t\tVal: &policy.UsageTimeLimitValue{\n\t\t\tOverrides: []*policy.UsageTimeLimitValueOverrides{},\n\t\t\tTimeUsageLimit: &policy.UsageTimeLimitValueTimeUsageLimit{\n\t\t\t\tFriday: &policy.RefTimeUsageLimitEntry{\n\t\t\t\t\tLastUpdatedMillis: dailyTimeUsageLimit.LastUpdatedMillis,\n\t\t\t\t\tUsageQuotaMins: dailyTimeUsageLimit.UsageQuotaMins,\n\t\t\t\t},\n\t\t\t\tMonday: &policy.UsageTimeLimitValueTimeUsageLimitMonday{\n\t\t\t\t\tLastUpdatedMillis: dailyTimeUsageLimit.LastUpdatedMillis,\n\t\t\t\t\tUsageQuotaMins: dailyTimeUsageLimit.UsageQuotaMins,\n\t\t\t\t},\n\t\t\t\tResetAt: &resetTime,\n\t\t\t\tSaturday: &policy.UsageTimeLimitValueTimeUsageLimitSaturday{\n\t\t\t\t\tLastUpdatedMillis: dailyTimeUsageLimit.LastUpdatedMillis,\n\t\t\t\t\tUsageQuotaMins: dailyTimeUsageLimit.UsageQuotaMins,\n\t\t\t\t},\n\t\t\t\tSunday: &policy.UsageTimeLimitValueTimeUsageLimitSunday{\n\t\t\t\t\tLastUpdatedMillis: dailyTimeUsageLimit.LastUpdatedMillis,\n\t\t\t\t\tUsageQuotaMins: dailyTimeUsageLimit.UsageQuotaMins,\n\t\t\t\t},\n\t\t\t\tThursday: &policy.UsageTimeLimitValueTimeUsageLimitThursday{\n\t\t\t\t\tLastUpdatedMillis: dailyTimeUsageLimit.LastUpdatedMillis,\n\t\t\t\t\tUsageQuotaMins: dailyTimeUsageLimit.UsageQuotaMins,\n\t\t\t\t},\n\t\t\t\tTuesday: &policy.UsageTimeLimitValueTimeUsageLimitTuesday{\n\t\t\t\t\tLastUpdatedMillis: dailyTimeUsageLimit.LastUpdatedMillis,\n\t\t\t\t\tUsageQuotaMins: dailyTimeUsageLimit.UsageQuotaMins,\n\t\t\t\t},\n\t\t\t\tWednesday: &policy.UsageTimeLimitValueTimeUsageLimitWednesday{\n\t\t\t\t\tLastUpdatedMillis: dailyTimeUsageLimit.LastUpdatedMillis,\n\t\t\t\t\tUsageQuotaMins: dailyTimeUsageLimit.UsageQuotaMins,\n\t\t\t\t},\n\t\t\t},\n\t\t\tTimeWindowLimit: &policy.UsageTimeLimitValueTimeWindowLimit{\n\t\t\t\tEntries: []*policy.UsageTimeLimitValueTimeWindowLimitEntries{},\n\t\t\t},\n\t\t},\n\t}\n}", "func NewAccountQuotaPolicyClient(subscriptionID string) AccountQuotaPolicyClient {\n return NewAccountQuotaPolicyClientWithBaseURI(DefaultBaseURI, subscriptionID)\n}", "func TestQuota(t *testing.T) {\n\tinitializationCh := make(chan struct{})\n\t// Set up a master\n\tvar m *master.Master\n\ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t<-initializationCh\n\t\tm.Handler.ServeHTTP(w, req)\n\t}))\n\tdefer s.Close()\n\tadmissionCh := make(chan struct{})\n\tclientset := clientset.NewForConfigOrDie(&restclient.Config{QPS: -1, Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}})\n\tadmission, err := resourcequota.NewResourceQuota(clientset, quotainstall.NewRegistry(clientset), 5, admissionCh)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tdefer close(admissionCh)\n\n\tmasterConfig := framework.NewIntegrationTestMasterConfig()\n\tmasterConfig.AdmissionControl = admission\n\tm, err = master.New(masterConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"Error in bringing up the master: %v\", err)\n\t}\n\tclose(initializationCh)\n\n\tns := framework.CreateTestingNamespace(\"quotaed\", s, t)\n\tdefer framework.DeleteTestingNamespace(ns, s, t)\n\tns2 := framework.CreateTestingNamespace(\"non-quotaed\", s, t)\n\tdefer framework.DeleteTestingNamespace(ns2, s, t)\n\n\tcontrollerCh := make(chan struct{})\n\tdefer close(controllerCh)\n\n\tgo replicationcontroller.NewReplicationManagerFromClientForIntegration(clientset, controller.NoResyncPeriodFunc, replicationcontroller.BurstReplicas, 4096).\n\t\tRun(3, controllerCh)\n\n\tresourceQuotaRegistry := quotainstall.NewRegistry(clientset)\n\tgroupKindsToReplenish := []unversioned.GroupKind{\n\t\tapi.Kind(\"Pod\"),\n\t}\n\tresourceQuotaControllerOptions := &resourcequotacontroller.ResourceQuotaControllerOptions{\n\t\tKubeClient: clientset,\n\t\tResyncPeriod: controller.NoResyncPeriodFunc,\n\t\tRegistry: resourceQuotaRegistry,\n\t\tGroupKindsToReplenish: groupKindsToReplenish,\n\t\tReplenishmentResyncPeriod: controller.NoResyncPeriodFunc,\n\t\tControllerFactory: resourcequotacontroller.NewReplenishmentControllerFactoryFromClient(clientset),\n\t}\n\tgo resourcequotacontroller.NewResourceQuotaController(resourceQuotaControllerOptions).Run(2, controllerCh)\n\n\tstartTime := time.Now()\n\tscale(t, ns2.Name, clientset)\n\tendTime := time.Now()\n\tt.Logf(\"Took %v to scale up without quota\", endTime.Sub(startTime))\n\n\tquota := &api.ResourceQuota{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: \"quota\",\n\t\t\tNamespace: ns.Name,\n\t\t},\n\t\tSpec: api.ResourceQuotaSpec{\n\t\t\tHard: api.ResourceList{\n\t\t\t\tapi.ResourcePods: resource.MustParse(\"1000\"),\n\t\t\t},\n\t\t},\n\t}\n\twaitForQuota(t, quota, clientset)\n\n\tstartTime = time.Now()\n\tscale(t, \"quotaed\", clientset)\n\tendTime = time.Now()\n\tt.Logf(\"Took %v to scale up with quota\", endTime.Sub(startTime))\n}", "func (scheduler *SchedulerFair) UpdateQuota() {\r\n\tscheduler.queuesMu.Lock()\r\n\tdefer scheduler.queuesMu.Unlock()\r\n\tscheduler.queuesQuotaMu.Lock()\r\n\tdefer scheduler.queuesQuotaMu.Unlock()\r\n\t//log.Info(\"Updating queues quota~\")\r\n\r\n\t/* phase 1: DRF */\r\n\tusingGPU := 0\r\n\tusingCPU := 0\r\n\tusingMemory := 0\r\n\tallocatedGPU := 0\r\n\tallocatedCPU := 0\r\n\tallocatedMemory := 0\r\n\tscheduler.resourceAllocationsMu.Lock()\r\n\tfor _, quota := range scheduler.resourceAllocations {\r\n\t\tusingGPU += quota.NumberGPU\r\n\t\tusingCPU += quota.CPU\r\n\t\tusingMemory += quota.Memory\r\n\t}\r\n\tscheduler.resourceAllocationsMu.Unlock()\r\n\r\n\tfor _, quota := range scheduler.queuesQuota {\r\n\t\tallocatedGPU += quota.NumberGPU\r\n\t\tallocatedCPU += quota.CPU\r\n\t\tallocatedMemory += quota.Memory\r\n\t}\r\n\r\n\tpool := InstanceOfResourcePool()\r\n\r\n\tavailableGPU := pool.TotalGPU*1000 - usingGPU*1000 - allocatedGPU\r\n\tavailableCPU := pool.TotalCPU*1000 - usingCPU*1000 - allocatedCPU\r\n\t//availableMemory := pool.TotalMemory - usingMemory - allocatedMemory\r\n\t/* <0 means some nodes exited */\r\n\t//log.Info(availableGPU)\r\n\tif availableGPU <= 0 {\r\n\t\treturn\r\n\t}\r\n\r\n\tvar candidates []string\r\n\trequests := map[string]ResourceCount{}\r\n\tweights := 0\r\n\r\n\tfor queue, jobs := range scheduler.queues {\r\n\t\tif len(jobs) == 0 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tweights += InstanceOfGroupManager().groups[queue].Weight\r\n\t\trequest := ResourceCount{}\r\n\t\tfor i, job := range jobs {\r\n\t\t\tGPU := 0\r\n\t\t\tCPU := 0\r\n\t\t\tMemory := 0\r\n\t\t\tfor _, task := range job.Tasks {\r\n\t\t\t\tGPU += task.NumberGPU\r\n\t\t\t\tCPU += task.NumberCPU\r\n\t\t\t\tMemory += task.Memory\r\n\t\t\t}\r\n\t\t\trequest.NumberGPU += GPU\r\n\t\t\trequest.CPU += CPU\r\n\t\t\trequest.Memory += Memory\r\n\t\t\t/* increase priority at most 10 jobs, to avoid small jobs always goes first in a batch */\r\n\t\t\tif job.Priority == jobs[0].Priority && i < 10 {\r\n\t\t\t\tscheduler.queues[queue][i].BasePriority += 1.0\r\n\t\t\t}\r\n\t\t}\r\n\t\tsort.Sort(sort.Reverse(scheduler.queues[queue]))\r\n\r\n\t\t/* minimum is 1, to avoid divide by zero error following */\r\n\t\tif request.NumberGPU == 0 {\r\n\t\t\trequest.NumberGPU = 1\r\n\t\t}\r\n\t\tif quota, ok := scheduler.queuesQuota[queue]; ok && quota.NumberGPU >= request.NumberGPU*1000 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\trequests[queue] = request\r\n\t\tcandidates = append(candidates, queue)\r\n\t}\r\n\r\n\tif len(candidates) == 0 {\r\n\t\treturn\r\n\t}\r\n\tlog.Debug(\"Can allocate \", availableGPU)\r\n\tlog.Debug(\"Before \")\r\n\tfor queue, quota := range scheduler.queuesQuota {\r\n\t\tlog.Debug(\"Queue<->\", queue)\r\n\t\tlog.Debug(\"GPU:\", quota.NumberGPU)\r\n\t\tlog.Debug(\"CPU:\", quota.CPU)\r\n\t\tlog.Debug(\"Memory:\", quota.Memory)\r\n\t}\r\n\r\n\tper := availableGPU / weights\r\n\tfor _, queue := range candidates {\r\n\t\tif _, ok := scheduler.queuesQuota[queue]; !ok {\r\n\t\t\tscheduler.queuesQuota[queue] = &ResourceCount{}\r\n\t\t}\r\n\t\tweight := InstanceOfGroupManager().groups[queue].Weight\r\n\t\tquota := scheduler.queuesQuota[queue]\r\n\r\n\t\t/* if allocate is more than request, reduce weight */\r\n\t\tlog.Info(quota.NumberGPU, per, weight, requests[queue].NumberGPU)\r\n\t\tbase := per * weight\r\n\t\tif quota.NumberGPU+base > requests[queue].NumberGPU*1000 {\r\n\t\t\tbase = requests[queue].NumberGPU*1000 - quota.NumberGPU\r\n\t\t}\r\n\r\n\t\tquota.NumberGPU += base\r\n\t\tavailableGPU -= base\r\n\r\n\t\tquota.CPU += (requests[queue].CPU * base) / requests[queue].NumberGPU\r\n\t\tavailableCPU -= (requests[queue].CPU * base) / requests[queue].NumberGPU\r\n\t\tquota.Memory += ((requests[queue].Memory * base) / requests[queue].NumberGPU) / 1000\r\n\t}\r\n\t/* avoid resource leak, and reserve full */\r\n\tavailableGPU = availableGPU % 1000\r\n\tif availableGPU > 0 {\r\n\t\tfor _, queue := range candidates {\r\n\t\t\tquota := scheduler.queuesQuota[queue]\r\n\t\t\tquota.NumberGPU += availableGPU\r\n\t\t\tquota.CPU += (requests[queue].CPU * availableGPU) / requests[queue].NumberGPU\r\n\t\t\tquota.Memory += ((requests[queue].Memory * availableGPU) / requests[queue].NumberGPU) / 1000\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\tlog.Debug(\"After \")\r\n\tfor queue, quota := range scheduler.queuesQuota {\r\n\t\tlog.Debug(\"Queue<->\", queue)\r\n\t\tlog.Debug(\"GPU:\", quota.NumberGPU)\r\n\t\tlog.Debug(\"CPU:\", quota.CPU)\r\n\t\tlog.Debug(\"Memory:\", quota.Memory)\r\n\t}\r\n\r\n\t/* Phase 2: clear IOUs */\r\n\tfor queue, IOUs := range scheduler.IOUs {\r\n\t\t/* no IOU, skip */\r\n\t\tif t, ok := scheduler.IOUs[queue]; !ok || len(t) == 0 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\t/* nothing to pay */\r\n\t\tif tmp, ok := scheduler.queuesQuota[queue]; !ok || tmp.NumberGPU == 0 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tminIOU := 0\r\n\t\ttotalIOU := 0\r\n\t\tfor _, IOU := range IOUs {\r\n\t\t\tif IOU.NumberGPU > minIOU && IOU.NumberGPU != 0 {\r\n\t\t\t\tminIOU = IOU.NumberGPU\r\n\t\t\t\ttotalIOU += IOU.NumberGPU\r\n\t\t\t}\r\n\t\t}\r\n\t\tquota := scheduler.queuesQuota[queue]\r\n\t\tif quota.NumberGPU >= totalIOU {\r\n\t\t\t/* can clear all */\r\n\t\t\tminIOU = totalIOU\r\n\t\t}\r\n\t\tif quota.NumberGPU < minIOU*len(IOUs) {\r\n\t\t\tminIOU = quota.NumberGPU / len(IOUs)\r\n\t\t}\r\n\r\n\t\tfor q, IOU := range IOUs {\r\n\t\t\tif IOU.NumberGPU <= minIOU {\r\n\t\t\t\tquota.NumberGPU -= IOU.NumberGPU\r\n\t\t\t\tscheduler.queuesQuota[q].NumberGPU += IOU.NumberGPU\r\n\t\t\t\tIOU.NumberGPU = 0\r\n\t\t\t} else {\r\n\t\t\t\tquota.NumberGPU -= minIOU\r\n\t\t\t\tscheduler.queuesQuota[q].NumberGPU += minIOU\r\n\t\t\t\tIOU.NumberGPU -= minIOU\r\n\t\t\t}\r\n\t\t\tlog.Info(queue, \" pay IOU to \", q, \" now \", IOU.NumberGPU)\r\n\t\t\t/* clear */\r\n\t\t\tif IOU.NumberGPU == 0 {\r\n\t\t\t\tdelete(scheduler.IOUs[queue], q)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif minIOU == 0 {\r\n\t\t\tfor q, IOU := range IOUs {\r\n\t\t\t\tquota.NumberGPU -= 1\r\n\t\t\t\tscheduler.queuesQuota[q].NumberGPU += 1\r\n\t\t\t\tIOU.NumberGPU -= 1\r\n\t\t\t\tlog.Info(queue, \" pay IOU to \", q, \" now \", IOU.NumberGPU)\r\n\t\t\t\t/* clear */\r\n\t\t\t\tif IOU.NumberGPU == 0 {\r\n\t\t\t\t\tdelete(scheduler.IOUs[queue], q)\r\n\t\t\t\t}\r\n\t\t\t\tif quota.NumberGPU == 0 {\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func NewBounded(limit int) Queue {\n\treturn newBounded(limit)\n}", "func UpdateQuota(c context.Context, limit, usage float64, metric, project, region string) {\n\tquotaLimit.Set(c, limit, metric, project, region)\n\tquotaRemaining.Set(c, limit-usage, metric, project, region)\n\tquotaUsage.Set(c, usage, metric, project, region)\n}", "func setLimits(ns string, lims limits) {\n\n\tif len(lims) == 0 {\n\t\treturn\n\t}\n\n\tdefinition := `\n---\napiVersion: v1\nkind: LimitRange\nmetadata:\n name: limit-range\nspec:\n limits:\n`\n\td, err := yaml.Marshal(&lims)\n\tif err != nil {\n\t\tlogError(err.Error())\n\t}\n\n\tdefinition = definition + Indent(string(d), strings.Repeat(\" \", 4))\n\n\tif err := ioutil.WriteFile(\"temp-LimitRange.yaml\", []byte(definition), 0666); err != nil {\n\t\tlogError(err.Error())\n\t}\n\n\tcmd := command{\n\t\tCmd: \"bash\",\n\t\tArgs: []string{\"-c\", \"kubectl apply -f temp-LimitRange.yaml -n \" + ns},\n\t\tDescription: \"creating LimitRange in namespace [ \" + ns + \" ]\",\n\t}\n\n\texitCode, e := cmd.exec(debug, verbose)\n\n\tif exitCode != 0 {\n\t\tlogError(\"ERROR: failed to create LimitRange in namespace [ \" + ns + \" ]: \" + e)\n\t}\n\n\tdeleteFile(\"temp-LimitRange.yaml\")\n\n}" ]
[ "0.70255303", "0.6392232", "0.6372643", "0.6265869", "0.62243545", "0.61384356", "0.6130965", "0.61270595", "0.6043387", "0.58570546", "0.58482", "0.5845201", "0.57947737", "0.57201415", "0.5692513", "0.56593245", "0.56315416", "0.559504", "0.55927944", "0.55651486", "0.5547203", "0.55375797", "0.55362076", "0.5509823", "0.5499448", "0.54982877", "0.5491149", "0.5474331", "0.5453786", "0.5452771", "0.5432719", "0.5428253", "0.54203075", "0.5417783", "0.5396248", "0.5395974", "0.53899413", "0.5358102", "0.53531396", "0.5318253", "0.5316755", "0.5285627", "0.52847826", "0.5279262", "0.5270467", "0.5239257", "0.52380365", "0.52351457", "0.52277386", "0.5223094", "0.52175725", "0.52094847", "0.51915264", "0.51585567", "0.51442426", "0.51422", "0.51369846", "0.5136389", "0.51244265", "0.51223916", "0.5074857", "0.5065224", "0.50651175", "0.5064118", "0.50418323", "0.50395674", "0.5030331", "0.49937096", "0.49935502", "0.49809194", "0.49781457", "0.4969191", "0.49642435", "0.49605417", "0.49552637", "0.4913386", "0.4910788", "0.49029845", "0.48701674", "0.4856614", "0.4843744", "0.48380095", "0.48340675", "0.4831862", "0.48116642", "0.4808017", "0.48066613", "0.48046598", "0.47981426", "0.4794477", "0.47817555", "0.4769688", "0.47689426", "0.47671324", "0.47636285", "0.47613955", "0.47602314", "0.47507054", "0.47354653", "0.47340456" ]
0.7799792
0
GetQuotaRateLimit gets an existing QuotaRateLimit resource's state with the given name, ID, and optional state properties that are used to uniquely qualify the lookup (nil if not required).
func GetQuotaRateLimit(ctx *pulumi.Context, name string, id pulumi.IDInput, state *QuotaRateLimitState, opts ...pulumi.ResourceOption) (*QuotaRateLimit, error) { var resource QuotaRateLimit err := ctx.ReadResource("vault:index/quotaRateLimit:QuotaRateLimit", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *WorkerPool) GetRateLimit(ctx context.Context, rlRequest *RateLimitReq) (retval *RateLimitResp, reterr error) {\n\t// Delegate request to assigned channel based on request key.\n\tworker := p.getWorker(rlRequest.UniqueKey)\n\thandlerRequest := &request{\n\t\tctx: ctx,\n\t\tresp: make(chan *response, 1),\n\t\trequest: rlRequest,\n\t}\n\n\t// Send request.\n\tselect {\n\tcase worker.getRateLimitRequest <- handlerRequest:\n\t\t// Successfully sent request.\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\t}\n\n\tmetricWorkerQueueLength.WithLabelValues(\"GetRateLimit\", worker.name).Observe(float64(len(worker.getRateLimitRequest)))\n\n\t// Wait for response.\n\tselect {\n\tcase handlerResponse := <-handlerRequest.resp:\n\t\t// Successfully read response.\n\t\treturn handlerResponse.rl, handlerResponse.err\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\t}\n}", "func NewQuotaRateLimit(ctx *pulumi.Context,\n\tname string, args *QuotaRateLimitArgs, opts ...pulumi.ResourceOption) (*QuotaRateLimit, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Rate == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Rate'\")\n\t}\n\tvar resource QuotaRateLimit\n\terr := ctx.RegisterResource(\"vault:index/quotaRateLimit:QuotaRateLimit\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func GetQuota(id int64) (*models.Quota, error) {\n\tq := models.Quota{ID: id}\n\terr := GetOrmer().Read(&q, \"ID\")\n\tif err == orm.ErrNoRows {\n\t\treturn nil, nil\n\t}\n\treturn &q, err\n}", "func (s *Strava) GetRateLimits() (requestTime time.Time, limitShort, limitLong, usageShort, usageLong int) {\n\trateLimiting := strava.RateLimiting\n\treturn rateLimiting.RequestTime, rateLimiting.LimitShort, rateLimiting.LimitLong, rateLimiting.UsageShort, rateLimiting.UsageLong\n}", "func (r *Registry) Get(s Settings) *Ratelimit {\n\tif s.Type == DisableRatelimit || s.Type == NoRatelimit {\n\t\treturn nil\n\t}\n\treturn r.get(s)\n}", "func (in *RateLimit) DeepCopy() *RateLimit {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(RateLimit)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (h *RateLimit) GetName() string {\n\treturn \"rate_limit\"\n}", "func (p *PilotPanel) GetRateLimiting(inv invocation.Invocation, serviceType string) control.RateLimitingConfig {\n\treturn control.RateLimitingConfig{}\n}", "func SetRateLimit() *RateLimit {\n\treturn &RateLimit{\n\t\tSpot: request.NewRateLimit(huobiSpotRateInterval, huobiSpotRequestRate),\n\t\tFuturesAuth: request.NewRateLimit(huobiFuturesRateInterval, huobiFuturesAuthRequestRate),\n\t\tFuturesUnauth: request.NewRateLimit(huobiFuturesRateInterval, huobiFuturesUnAuthRequestRate),\n\t\tSwapAuth: request.NewRateLimit(huobiSwapRateInterval, huobiSwapAuthRequestRate),\n\t\tSwapUnauth: request.NewRateLimit(huobiSwapRateInterval, huobiSwapUnauthRequestRate),\n\t\tFuturesXfer: request.NewRateLimit(huobiFuturesTransferRateInterval, huobiFuturesTransferReqRate),\n\t}\n}", "func (m *Manager) NewRateLimit(conf ratelimit.Config) (ratelimit.V1, error) {\n\treturn bundle.AllRateLimits.Init(conf, m)\n}", "func (q *Control) GetQuota(targetPath string, quota *Quota) error {\n\treturn ErrQuotaNotSupported\n}", "func (c *Client) RateLimit() RateLimit {\n\tif c.limit != nil {\n\t\treturn *c.limit\n\t}\n\taccount, err := c.Account.Get()\n\tif err != nil {\n\t\treturn RateLimit{}\n\t}\n\tc.limit = &RateLimit{}\n\tfor _, metric := range account.Metrics {\n\t\tif metric.PlanLevel > 0 {\n\t\t\tc.limit.Limit = metric.PlanLevel\n\t\t\tc.limit.Remaining = metric.Remaining\n\t\t}\n\t}\n\treturn *c.limit\n}", "func (o MethodSettingsSettingsPtrOutput) ThrottlingRateLimit() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v *MethodSettingsSettings) *float64 {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ThrottlingRateLimit\n\t}).(pulumi.Float64PtrOutput)\n}", "func GetUsageLimit(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *UsageLimitState, opts ...pulumi.ResourceOption) (*UsageLimit, error) {\n\tvar resource UsageLimit\n\terr := ctx.ReadResource(\"aws:redshift/usageLimit:UsageLimit\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (q *Control) GetQuota(targetPath string, quota *Quota) error {\n\tq.RLock()\n\tprojectID, ok := q.quotas[targetPath]\n\tq.RUnlock()\n\tif !ok {\n\t\treturn errors.Errorf(\"quota not found for path: %s\", targetPath)\n\t}\n\n\t//\n\t// get the quota limit for the container's project id\n\t//\n\tvar d C.fs_disk_quota_t\n\n\tcs := C.CString(q.backingFsBlockDev)\n\tdefer C.free(unsafe.Pointer(cs))\n\n\t_, _, errno := unix.Syscall6(unix.SYS_QUOTACTL, C.Q_XGETPQUOTA,\n\t\tuintptr(unsafe.Pointer(cs)), uintptr(C.__u32(projectID)),\n\t\tuintptr(unsafe.Pointer(&d)), 0, 0)\n\tif errno != 0 {\n\t\treturn errors.Wrapf(errno, \"Failed to get quota limit for projid %d on %s\",\n\t\t\tprojectID, q.backingFsBlockDev)\n\t}\n\tquota.Size = uint64(d.d_blk_hardlimit) * 512\n\n\treturn nil\n}", "func (p *WorkerPool) handleGetRateLimit(handlerRequest *request, cache Cache) {\n\tctx := tracing.StartNamedScopeDebug(handlerRequest.ctx, \"WorkerPool.handleGetRateLimit\")\n\tdefer tracing.EndScope(ctx, nil)\n\n\tvar rlResponse *RateLimitResp\n\tvar err error\n\n\tswitch handlerRequest.request.Algorithm {\n\tcase Algorithm_TOKEN_BUCKET:\n\t\trlResponse, err = tokenBucket(ctx, p.conf.Store, cache, handlerRequest.request)\n\t\tif err != nil {\n\t\t\tmsg := \"Error in tokenBucket\"\n\t\t\tcountError(err, msg)\n\t\t\terr = errors.Wrap(err, msg)\n\t\t\ttrace.SpanFromContext(ctx).RecordError(err)\n\t\t}\n\n\tcase Algorithm_LEAKY_BUCKET:\n\t\trlResponse, err = leakyBucket(ctx, p.conf.Store, cache, handlerRequest.request)\n\t\tif err != nil {\n\t\t\tmsg := \"Error in leakyBucket\"\n\t\t\tcountError(err, msg)\n\t\t\terr = errors.Wrap(err, msg)\n\t\t\ttrace.SpanFromContext(ctx).RecordError(err)\n\t\t}\n\n\tdefault:\n\t\terr = errors.Errorf(\"Invalid rate limit algorithm '%d'\", handlerRequest.request.Algorithm)\n\t\ttrace.SpanFromContext(ctx).RecordError(err)\n\t\tmetricCheckErrorCounter.WithLabelValues(\"Invalid algorithm\").Add(1)\n\t}\n\n\thandlerResponse := &response{\n\t\trl: rlResponse,\n\t\terr: err,\n\t}\n\n\tselect {\n\tcase handlerRequest.resp <- handlerResponse:\n\t\t// Success.\n\n\tcase <-ctx.Done():\n\t\t// Context canceled.\n\t\ttrace.SpanFromContext(ctx).RecordError(err)\n\t}\n}", "func NewRateLimit(storage store.Store, statsClient stats.Client) *RateLimit {\n\treturn &RateLimit{storage, statsClient}\n}", "func (r *RateLimiter) Get(ip string) *rate.Limiter {\n\tr.mtx.RLock()\n\tlimiter, ok := r.ips[ip]\n\tr.mtx.RUnlock()\n\n\tif !ok {\n\t\tlimiter = rate.NewLimiter(r.interval, r.n)\n\t\tr.mtx.Lock()\n\t\tr.ips[ip] = limiter\n\t\tr.mtx.Unlock()\n\t}\n\n\treturn limiter\n}", "func (s *Server) Get(_ context.Context, request *rpcLimit.GetLimitsRequest) (*rpcLimit.GetLimitsResponse, error) {\n\tresult := make([]*rpcLimit.LimitWithId, 0, len(request.Identifiers))\n\tsrv := s.limitService\n\n\tfor _, reqId := range request.Identifiers {\n\t\tfound, err := srv.Find(requestIdToLimitId(reqId))\n\n\t\tif errors.Cause(err) == limit.ErrNotFound || len(found) == 0 {\n\t\t\tresult = append(result, &rpcLimit.LimitWithId{\n\t\t\t\tLimit: &rpcLimit.Limit{Exists: false},\n\t\t\t\tLimitId: reqId,\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, l := range found {\n\t\t\tresult = append(result, &rpcLimit.LimitWithId{\n\t\t\t\tLimit: limitValueToRequestLimit(l.Available()),\n\t\t\t\tLimitId: limitIdToRequestId(l.Identifier()),\n\t\t\t})\n\t\t}\n\t}\n\treturn &rpcLimit.GetLimitsResponse{\n\t\tLimits: result,\n\t}, nil\n}", "func (o AccountThrottleSettingOutput) RateLimit() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v AccountThrottleSetting) *float64 { return v.RateLimit }).(pulumi.Float64PtrOutput)\n}", "func (c *FakeClient) GetRateLimiter() flowcontrol.RateLimiter {\n\treturn nil\n}", "func (bas *BaseService) CheckRateLimit() {\n\tbas.rlock.Lock()\n\trlimit := bas.rlimit\n\tbas.rlock.Unlock()\n\n\tif rlimit != nil {\n\t\trlimit.Take()\n\t}\n}", "func (t *Throttler) Get(pool, namespace, token string) *Limiter {\n\ttokenLimitKey := t.buildLimitKey(pool, namespace, token)\n\tt.mu.RLock()\n\tif limiter, ok := t.cache[tokenLimitKey]; ok {\n\t\tt.mu.RUnlock()\n\t\treturn limiter\n\t}\n\tt.mu.RUnlock()\n\treturn nil\n}", "func NewRateLimit(limit int, deltat time.Duration) *RateLimit {\n\treturn &RateLimit{Rate{NewCounter(0), deltat}, limit, time.Now()}\n}", "func NewRateLimit(client curator.CuratorFramework, username string,\n\ttotalAllowedQuota, baseQuota int64, lockTimeout time.Duration, refreshWindow time.Duration,\n\tenableOptimization bool, optimizationPctAsk float64, optimizationPctLeft float64) (*RateLimit, error) {\n\tvar err error\n\trl := &RateLimit{\n\t\tusername: username,\n\t\ttotalAllowedQuota: totalAllowedQuota,\n\t\tusableQuotaLeft: totalAllowedQuota,\n\t\tbaseQuota: baseQuota,\n\t\tlockTimeout: lockTimeout,\n\t\trefreshWindow: refreshWindow,\n\t\tclient: client,\n\t\tbaseQuotaPath: prefix + \"/\" + username + baseSuffix,\n\t\tusableQuotaPath: prefix + \"/\" + username + usableSuffix,\n\t\ttotalQuotaPath: prefix + \"/\" + username + totalSuffix,\n\t\trefreshQuotaPath: prefix + \"/\" + username + refreshSuffix,\n\t\toptimizationPctAsk: optimizationPctAsk,\n\t\toptimizationPctLeft: optimizationPctLeft,\n\t\tenableOptimization: enableOptimization,\n\t}\n\n\t// initialize the lock to be used and inject it wherever required.\n\trl.lock, err = recipe.NewInterProcessMutex(rl.client, lockPath+username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(prefix, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(prefix+\"/\"+rl.username, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.baseQuotaPath, []byte(strconv.FormatInt(rl.baseQuota, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.totalQuotaPath, []byte(strconv.FormatInt(rl.totalAllowedQuota, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.usableQuotaPath, []byte(strconv.FormatInt(rl.usableQuotaLeft, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.refreshQuotaPath, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.addWatch()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// concurrently look to refresh quota\n\tgo rl.refreshQuota()\n\t// mimic user requests being processed with random size\n\tgo rl.startRequests()\n\t// just in case there is skewness observed through loadbalancer and\n\t// quota gets concentrated on a single rate limit node\n\tgo rl.relinquish()\n\n\treturn rl, nil\n}", "func (o MethodSettingsSettingsOutput) ThrottlingRateLimit() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v MethodSettingsSettings) *float64 { return v.ThrottlingRateLimit }).(pulumi.Float64PtrOutput)\n}", "func (client *Client) GetRateLimitStats() map[string]RateLimit {\n\tclient.m.Lock()\n\tdefer client.m.Unlock()\n\t// Shallow copy to avoid corrupted data\n\tmapCopy := make(map[string]RateLimit, len(client.rateLimitingStats))\n\tfor k, v := range client.rateLimitingStats {\n\t\tmapCopy[k] = v\n\t}\n\treturn mapCopy\n}", "func (m *Drive) GetQuota()(Quotaable) {\n return m.quota\n}", "func (rl *RateLimit) Name() string {\n\treturn \"ratelimit\"\n}", "func (s *RateBasedRule) SetRateLimit(v int64) *RateBasedRule {\n\ts.RateLimit = &v\n\treturn s\n}", "func (s *CreateRateBasedRuleInput) SetRateLimit(v int64) *CreateRateBasedRuleInput {\n\ts.RateLimit = &v\n\treturn s\n}", "func (p *ioThrottlerPool) GetLimitByID(id string) (r rate.Limit, b int, err error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tl, ok := p.connections[id]\n\tif !ok {\n\t\treturn 0, 0, fmt.Errorf(\"limiter for connection %s not found\", id)\n\t}\n\treturn l.limiter.Limit(), l.limiter.Burst(), nil\n}", "func (s *UpdateRateBasedRuleInput) SetRateLimit(v int64) *UpdateRateBasedRuleInput {\n\ts.RateLimit = &v\n\treturn s\n}", "func (m *Manager) StoreRateLimit(ctx context.Context, name string, conf ratelimit.Config) error {\n\treturn component.ErrInvalidType(\"rate_limit\", conf.Type)\n}", "func (a *Client) GetQuota(params *GetQuotaParams) (*GetQuotaOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetQuotaParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getQuota\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/quotas\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetQuotaReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetQuotaOK), nil\n\n}", "func (r *RateLimit) Limit(ctx context.Context, f request.EndpointLimit) error {\n\tswitch f {\n\t// TODO: Add futures and swap functionality\n\tcase huobiFuturesAuth:\n\t\treturn r.FuturesAuth.Wait(ctx)\n\tcase huobiFuturesUnAuth:\n\t\treturn r.FuturesUnauth.Wait(ctx)\n\tcase huobiFuturesTransfer:\n\t\treturn r.FuturesXfer.Wait(ctx)\n\tcase huobiSwapAuth:\n\t\treturn r.SwapAuth.Wait(ctx)\n\tcase huobiSwapUnauth:\n\t\treturn r.SwapUnauth.Wait(ctx)\n\tdefault:\n\t\t// Spot calls\n\t\treturn r.Spot.Wait(ctx)\n\t}\n}", "func (rl *limiter) GetRate() int64 {\n\trl.lock.RLock()\n\tqps := rl.qps\n\trl.lock.RUnlock()\n\n\treturn qps\n}", "func (o UsagePlanThrottleSettingsOutput) RateLimit() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v UsagePlanThrottleSettings) *float64 { return v.RateLimit }).(pulumi.Float64PtrOutput)\n}", "func (o UsagePlanThrottleSettingsPtrOutput) RateLimit() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v *UsagePlanThrottleSettings) *float64 {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.RateLimit\n\t}).(pulumi.Float64PtrOutput)\n}", "func RateLimit(w http.ResponseWriter, r *http.Request) {\n\tvar tc *http.Client\n\n\tc := cloudpkgs.NewContext(w, r)\n\tctx := context.Background()\n\n\tt := c.Request.Header.Get(\"Authorization\")\n\tif t != \"\" {\n\t\tts := oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: t},\n\t\t)\n\t\ttc = oauth2.NewClient(ctx, ts)\n\t}\n\n\tclient := cloudapi.NewAPIClient(tc)\n\n\trate, _, err := client.Client.RateLimits(ctx)\n\tif err != nil {\n\t\tc.WriteJSON(http.StatusRequestTimeout, cloudpkgs.H{\"status\": http.StatusRequestTimeout})\n\t\treturn\n\t}\n\n\tc.WriteJSON(http.StatusOK, cloudpkgs.H{\"status\": http.StatusOK, \"rate\": rate})\n}", "func (o QuotaRateLimitOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *QuotaRateLimit) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func NewGetLimitsForbidden() *GetLimitsForbidden {\n\treturn &GetLimitsForbidden{}\n}", "func NewRateLimiter(bandwidth, ops models.TokenBucket, opts ...RateLimiterOpt) *models.RateLimiter {\n\tlimiter := &models.RateLimiter{\n\t\tBandwidth: &bandwidth,\n\t\tOps: &ops,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(limiter)\n\t}\n\n\treturn limiter\n}", "func (r *Registry) Get(baseURL string) *rate.Limiter {\n\treturn r.GetOrSet(baseURL, nil)\n}", "func (c *SpaceQuotaClient) Get(ctx context.Context, guid string) (*resource.SpaceQuota, error) {\n\tvar q resource.SpaceQuota\n\terr := c.client.get(ctx, path.Format(\"/v3/space_quotas/%s\", guid), &q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &q, nil\n}", "func (i *IPRateLimiter) GetLimiter(ip string) *rate.Limiter {\n\ti.mu.Lock()\n\tlimiter, exists := i.ips[ip]\n\n\tif !exists {\n\t\ti.mu.Unlock()\n\t\treturn i.AddIP(ip)\n\t}\n\n\ti.mu.Unlock()\n\n\treturn limiter\n}", "func New(config config.Config) (RateLimiter, error) {\n\n\tstorage, err := resolveBucketStore(config.Storage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlimits := []limit.Limit{}\n\tfor name, config := range config.Limits {\n\t\tlimit, err := limit.New(name, config, storage)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlimits = append(limits, limit)\n\t}\n\n\trateLimiter := &rateLimiter{limits: limits}\n\treturn rateLimiter, nil\n}", "func (scs *StorageContractSet) RetrieveRateLimit() (readBPS, writeBPS int64, packetSize uint64) {\n\treturn scs.rl.RetrieveRateLimit()\n}", "func (s gPUQuotaNamespaceLister) Get(name string) (*v1alpha1.GPUQuota, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"gpuquota\"), name)\n\t}\n\treturn obj.(*v1alpha1.GPUQuota), nil\n}", "func (l *RateLimiter) Limit() rate.Limit {\n\treturn l.limiter.Limit()\n}", "func (m *ItemQuotaRequestBuilder) Get(ctx context.Context, requestConfiguration *ItemQuotaRequestBuilderGetRequestConfiguration)(ie98116770ca9f5eee835504331ccb9976e822c2f776cca356ee95c843b4cce86.ConnectionQuotaable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.BaseRequestBuilder.RequestAdapter.Send(ctx, requestInfo, ie98116770ca9f5eee835504331ccb9976e822c2f776cca356ee95c843b4cce86.CreateConnectionQuotaFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(ie98116770ca9f5eee835504331ccb9976e822c2f776cca356ee95c843b4cce86.ConnectionQuotaable), nil\n}", "func (o LookupQueueResultOutput) RateLimits() RateLimitsResponseOutput {\n\treturn o.ApplyT(func(v LookupQueueResult) RateLimitsResponse { return v.RateLimits }).(RateLimitsResponseOutput)\n}", "func (o QuotaRateLimitOutput) Rate() pulumi.Float64Output {\n\treturn o.ApplyT(func(v *QuotaRateLimit) pulumi.Float64Output { return v.Rate }).(pulumi.Float64Output)\n}", "func NewLimitRate(name string, options LimitRateOptions) *LimitRate {\n\tthis := LimitRate{}\n\tthis.Name = name\n\tthis.Options = options\n\treturn &this\n}", "func (p *projectQuota) GetQuota(targetPath string) (*types.DiskQuotaSize, error) {\n\tbackingFsBlockDev, err := p.findAvailableBackingDev(targetPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// no need to create new project id\n\tprjId, _, err := p.findOrCreateProjectId(targetPath, \"\", projIdNoCreate, !persistToFile)\n\tif err != nil {\n\t\tklog.Errorf(\"find project id err: %v\", err)\n\t\treturn nil, err\n\t}\n\n\treturn getProjectQuota(backingFsBlockDev.device, prjId)\n}", "func RateLimiter(next http.RoundTripper) http.RoundTripper {\n\treturn &ratelimiter{\n\t\trt: next,\n\t\tlm: sync.Map{},\n\t}\n}", "func New(c *aqm.Config) *Limiter {\n\tl := &Limiter{\n\t\trate: vegas.New(),\n\t\tqueue: aqm.New(c),\n\t}\n\tgo func() {\n\t\tticker := time.NewTicker(time.Second * 1)\n\t\tdefer ticker.Stop()\n\t\tfor {\n\t\t\t<-ticker.C\n\t\t\tv := l.rate.Stat()\n\t\t\tq := l.queue.Stat()\n\t\t\tlog.Info(\"rate/limit: limit(%d) inFlight(%d) minRtt(%v) rtt(%v) codel packets(%d)\", v.Limit, v.InFlight, v.MinRTT, v.LastRTT, q.Packets)\n\t\t}\n\t}()\n\treturn l\n}", "func getResourceQuota(cpu, memory int) *v1.ResourceQuota {\n\t// Don's use \"MustParse\" it might panic at runtime , have some validation\n\thard := v1.ResourceList{\n\t\tv1.ResourceCPU: resource.MustParse(getCPUMilli(cpu)),\n\t\tv1.ResourceMemory: resource.MustParse(getMemoryMI(memory)),\n\t}\n\n\treturn &v1.ResourceQuota{\n\t\tSpec: v1.ResourceQuotaSpec{\n\t\t\tHard: hard,\n\t\t},\n\t}\n}", "func (p *ioThrottlerPool) GetGlobalLimit() (r rate.Limit, b int) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\treturn p.globalLimiter.Limit(), p.globalLimiter.Burst()\n}", "func ratelimiter(args map[string]interface{}) *ratelimit.Ratelimiter {\n\trate, err := strconv.Atoi(args[\"--ratelimit-max-rate\"].(string))\n\tif err != nil {\n\t\tlog.Fatalf(\"error parsing --ratelimit-max-rate: %s\", err)\n\t}\n\n\tif rate <= 0 {\n\t\treturn nil\n\t}\n\n\tkeys, err := strconv.Atoi(args[\"--ratelimit-max-keys\"].(string))\n\tif err != nil {\n\t\tlog.Fatalf(\"error parsing --ratelimit-max-keys: %s\", err)\n\t}\n\n\treturn ratelimit.New(rate, keys)\n}", "func (c *Client) RateLimit() int {\n\treturn c.rateLimit\n}", "func (r *LimiterReader) LimitingBitRate() infounit.BitRate {\n\tr.mu.RLock()\n\tdefer r.mu.RUnlock()\n\treturn r.rate\n}", "func (o UsagePlanApiStageThrottleOutput) RateLimit() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v UsagePlanApiStageThrottle) *float64 { return v.RateLimit }).(pulumi.Float64PtrOutput)\n}", "func getHTTPLocalRateLimitFilter() *hcmv3.HttpFilter {\n\tlocalRateLimitConfig := &local_ratelimit_v3.LocalRateLimit{\n\t\tStatPrefix: localRateLimitStatPrefix,\n\t}\n\tmarshalledRateLimitConfig, err := ptypes.MarshalAny(localRateLimitConfig)\n\tif err != nil {\n\t\tlogger.LoggerOasparser.Error(\"Error while generating the local rate limit filter.\", err)\n\t}\n\tlocalRateLimitFilter := &hcmv3.HttpFilter{\n\t\tName: localRatelimitFilterName,\n\t\tConfigType: &hcmv3.HttpFilter_TypedConfig{\n\t\t\tTypedConfig: marshalledRateLimitConfig,\n\t\t},\n\t}\n\treturn localRateLimitFilter\n}", "func (s *Setup) RateLimit(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tip, _, err := net.SplitHostPort(r.RemoteAddr)\n\t\tif err != nil {\n\t\t\terrhandler.DecodeError(w, r, s.logger, errInternal, http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tlimiter := ratelimit.GetVisitor(ip)\n\t\tif !limiter.Allow() {\n\t\t\terrhandler.DecodeError(\n\t\t\t\tw,\n\t\t\t\tr,\n\t\t\t\ts.logger,\n\t\t\t\thttp.StatusText(http.StatusTooManyRequests),\n\t\t\t\thttp.StatusTooManyRequests,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (l *GoLimiter) getRateLimiter(keyName string) *rate.Limiter {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\t_, exists := l.visitors[keyName]\n\tif !exists {\n\t\tburst, _ := strconv.Atoi(os.Getenv(environment.BurstLimit))\n\t\tlimit, _ := strconv.Atoi(os.Getenv(environment.RateLimit))\n\t\tlimiter := rate.NewLimiter(rate.Limit(limit), burst)\n\t\tl.visitors[keyName] = &visitor{limiter, time.Now()}\n\t} else {\n\t\tl.visitors[keyName].lastSeen = time.Now()\n\t}\n\n\treturn l.visitors[keyName].limiter\n}", "func (c *Client) RateLimitStatus(ctx context.Context, resources []string) (*RateLimitStatusResponse, error) {\n\tvalues := url.Values{}\n\tif len(resources) > 0 {\n\t\tvalues.Set(\"resources\", strings.Join(resources, \",\"))\n\t}\n\tresp, err := c.do(ctx, \"GET\", \"https://api.twitter.com/1.1/application/rate_limit_status.json\", values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif err = checkResponse(resp); err != nil {\n\t\treturn nil, err\n\t}\n\tvar res RateLimitsRes\n\terr = json.NewDecoder(resp.Body).Decode(&res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RateLimitStatusResponse{\n\t\tRateLimitsRes: res,\n\t\tRateLimit: getRateLimit(resp.Header),\n\t}, nil\n}", "func (cl *ConnectLimiter) Get(r *http.Request) (int64, error) {\r\n\tvar ok bool\r\n\tvar v interface{}\r\n\tvar tokenBucket *Bucket\r\n\r\n\tvar available int64 = cl.maxConnection - 1\r\n\t\r\n\tv, ok = cl.tokenBuckets.Load(remoteIp(r))\r\n\r\n\tif !ok {\r\n\t\treturn 0, errs.ERR_GET_TOKEN_BUCKET_FAIL\r\n\t}\r\n\r\n\tif tokenBucket, ok = v.(*Bucket); !ok {\r\n\t\treturn 0, errs.ERR_GET_TOKEN_BUCKET_FAIL\r\n\t}\r\n\tif available = tokenBucket.Get(); available <= 0 {\r\n\t\treturn 0, errs.ERR_NO_ENOUGH_TOKEN_BUCKET\r\n\t}\r\n\tlog.Println(\"Get available:\", available)\r\n\treturn available, nil\r\n}", "func (_m *IGithub) GetRateLimitInfo() (*github.RateLimits, error) {\n\tret := _m.Called()\n\n\tvar r0 *github.RateLimits\n\tif rf, ok := ret.Get(0).(func() *github.RateLimits); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*github.RateLimits)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func NewRateLimiter(h cachemanager.Handler) RateLimiter {\n\treturn &rateLimiter{\n\t\tbuckets: make(map[time.Duration]int),\n\t\thandler: h,\n\t}\n}", "func (b *Bucket) Consume(amt int) (limit.State, error) {\n\t// Leverage redis optimistic transactions to protect\n\t// from concurrent writes.\n\terr := b.rdb.Watch(func(tx *redis.Tx) error {\n\t\tn, err := tx.Get(b.key).Int()\n\t\tif err != nil {\n\t\t\tif err == redis.Nil {\n\t\t\t\t// set key:\n\t\t\t\tb.rdb.Set(b.key, 0, b.rate)\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif n >= b.capacity {\n\t\t\tb.drain() // attempt drain on exit.\n\t\t\treturn limit.ErrToManyRequests\n\t\t}\n\n\t\tvar count int64\n\t\t_, err = tx.TxPipelined(func(pipe redis.Pipeliner) error {\n\t\t\tcount, err = tx.IncrBy(b.key, int64(amt)).Result()\n\t\t\treturn err\n\t\t})\n\n\t\t// check for bucket overflow.\n\t\tif int(count) > b.capacity {\n\t\t\tb.drain() // attempt drain on exit.\n\t\t\treturn limit.ErrToManyRequests\n\t\t}\n\n\t\tb.Lock()\n\t\tb.space = b.capacity - int(count)\n\t\tb.Unlock()\n\n\t\tb.drain()\n\n\t\treturn nil\n\t}, b.key)\n\n\treturn b.state(), err\n}", "func (rl *redisRateLimiter) RateLimit(ctx gocontext.Context, name string, maxCalls uint64, per time.Duration) (bool, error) {\n\tif trace.FromContext(ctx) != nil {\n\t\tvar span *trace.Span\n\t\tctx, span = trace.StartSpan(ctx, \"Redis.RateLimit\")\n\t\tdefer span.End()\n\t}\n\n\tpoolCheckoutStart := time.Now()\n\n\tconn := rl.pool.Get()\n\tdefer conn.Close()\n\n\tcontext.TimeSince(ctx, \"rate_limit_redis_pool_wait\", poolCheckoutStart)\n\n\tif trace.FromContext(ctx) != nil {\n\t\tvar span *trace.Span\n\t\tctx, span = trace.StartSpan(ctx, \"Redis.RateLimit.WithPool\")\n\t\tdefer span.End()\n\t}\n\n\tif rl.dynamicConfig {\n\t\terr := rl.loadDynamicConfig(ctx, conn, name, &maxCalls, &per)\n\t\tif err != nil && err != redis.ErrNil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tnow := time.Now()\n\ttimestamp := now.Unix() - (now.Unix() % int64(per.Seconds()))\n\n\tkey := fmt.Sprintf(\"%s:%s:%d\", rl.prefix, name, timestamp)\n\n\tcur, err := redis.Int64(conn.Do(\"GET\", key))\n\tif err != nil && err != redis.ErrNil {\n\t\treturn false, err\n\t}\n\n\tif err != redis.ErrNil && uint64(cur) >= maxCalls {\n\t\treturn false, nil\n\t}\n\n\t_, err = conn.Do(\"WATCH\", key)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tconnSend := func(commandName string, args ...interface{}) {\n\t\tif err != nil && err != redis.ErrNil {\n\t\t\treturn\n\t\t}\n\t\terr = conn.Send(commandName, args...)\n\t}\n\tconnSend(\"MULTI\")\n\tconnSend(\"INCR\", key)\n\tconnSend(\"EXPIRE\", key, int64(per.Seconds()))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treply, err := conn.Do(\"EXEC\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif reply == nil {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}", "func (o *LimitRate) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (s *MultipassServer) GetResourceLimiter(ctx context.Context, request *apigrpc.CloudProviderServiceRequest) (*apigrpc.ResourceLimiterReply, error) {\n\tglog.V(5).Infof(\"Call server GetResourceLimiter: %v\", request)\n\n\tif request.GetProviderID() != s.Configuration.ProviderID {\n\t\tglog.Errorf(errMismatchingProvider)\n\t\treturn nil, fmt.Errorf(errMismatchingProvider)\n\t}\n\n\treturn &apigrpc.ResourceLimiterReply{\n\t\tResponse: &apigrpc.ResourceLimiterReply_ResourceLimiter{\n\t\t\tResourceLimiter: &apigrpc.ResourceLimiter{\n\t\t\t\tMinLimits: s.ResourceLimiter.MinLimits,\n\t\t\t\tMaxLimits: s.ResourceLimiter.MaxLimits,\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func RateLimiterFor(_ context.Context, c *Config) (limiter.Store, error) {\n\tswitch c.Type {\n\tcase RateLimiterTypeNoop:\n\t\treturn noopstore.New()\n\tcase RateLimiterTypeMemory:\n\t\treturn memorystore.New(&memorystore.Config{\n\t\t\tTokens: c.Tokens,\n\t\t\tInterval: c.Interval,\n\t\t})\n\tcase RateLimiterTypeRedis:\n\t\taddr := c.RedisHost + \":\" + c.RedisPort\n\n\t\tfailureMode := redisstore.FailClosed\n\t\tif strings.ToLower(c.FailureMode) == \"open\" {\n\t\t\tfailureMode = redisstore.FailOpen\n\t\t}\n\n\t\treturn redisstore.New(&redisstore.Config{\n\t\t\tTokens: c.Tokens,\n\t\t\tInterval: c.Interval,\n\t\t\tInitialPoolSize: c.RedisMinPool,\n\t\t\tMaxPoolSize: c.RedisMaxPool,\n\t\t\tDialFunc: func() (net.Conn, error) {\n\t\t\t\treturn net.Dial(\"tcp\", addr)\n\t\t\t},\n\t\t\tAuthUsername: c.RedisUsername,\n\t\t\tAuthPassword: c.RedisPassword,\n\t\t\tFailureMode: failureMode,\n\t\t})\n\t}\n\n\treturn nil, fmt.Errorf(\"unknown rate limiter type: %v\", c.Type)\n}", "func (provider *cloudStackCloudProvider) GetResourceLimiter() (*cloudprovider.ResourceLimiter, error) {\n\treturn provider.resourceLimiter, nil\n}", "func NewRateLimiter(limit int64) *limiter {\n\treturn &limiter{\n\t\tstart: time.Now(),\n\t\tlimit: limit,\n\t\tdelay: 0.5,\n\t}\n}", "func NewTokenBucketRateLimiter(qps float32, burst int) RateLimiter {\n\tlimiter := rate.NewLimiter(rate.Limit(qps), burst)\n\treturn newTokenBucketRateLimiter(limiter, realClock{}, qps)\n}", "func (l *RateLimiter) Limit(now time.Time, tenantID string) float64 {\n\treturn float64(l.getTenantLimiter(now, tenantID).Limit())\n}", "func (tencentcloud *tencentCloudProvider) GetResourceLimiter() (*cloudprovider.ResourceLimiter, error) {\n\tresourceLimiter, err := tencentcloud.tencentcloudManager.GetResourceLimiter()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resourceLimiter != nil {\n\t\treturn resourceLimiter, nil\n\t}\n\treturn tencentcloud.resourceLimiter, nil\n}", "func NewRateLimiter(r float64, b int) *RateLimiter {\n\treturn &RateLimiter{limiter: rate.NewLimiter(rate.Limit(r), b)}\n}", "func Get(instanceType string) (limit ipamTypes.Limits, ok bool) {\n\tlimitsOnce.Do(populateStaticENILimits)\n\n\tlimits.RLock()\n\tlimit, ok = limits.m[instanceType]\n\tlimits.RUnlock()\n\treturn\n}", "func RateLimit(d time.Duration) Tick {\n\tvar last *time.Time\n\treturn func(children []Node) (Status, error) {\n\t\tnow := time.Now()\n\t\tif last != nil && now.Add(-d).Before(*last) {\n\t\t\treturn Failure, nil\n\t\t}\n\t\tlast = &now\n\t\treturn Success, nil\n\t}\n}", "func (o SecurityPolicyRuleOutput) RateLimitOptions() SecurityPolicyRuleRateLimitOptionsPtrOutput {\n\treturn o.ApplyT(func(v SecurityPolicyRule) *SecurityPolicyRuleRateLimitOptions { return v.RateLimitOptions }).(SecurityPolicyRuleRateLimitOptionsPtrOutput)\n}", "func (m *InstancesManager) GetPoolQuota() (quota ipamTypes.PoolQuotaMap) {\n\tm.mutex.RLock()\n\tpool := ipamTypes.PoolQuotaMap{}\n\tfor subnetID, subnet := range m.subnets {\n\t\tpool[ipamTypes.PoolID(subnetID)] = ipamTypes.PoolQuota{\n\t\t\tAvailableIPs: subnet.AvailableAddresses,\n\t\t}\n\t}\n\tm.mutex.RUnlock()\n\treturn pool\n}", "func NewGetLimitsTooManyRequests() *GetLimitsTooManyRequests {\n\treturn &GetLimitsTooManyRequests{}\n}", "func (h *handlerState) Quota(ctx context.Context, tracker attribute.Tracker, request *mixerpb.QuotaRequest, response *mixerpb.QuotaResponse) {\n\tresponse.RequestIndex = request.RequestIndex\n\tstatus := h.execute(ctx, tracker, request.AttributeUpdate, config.QuotaMethod)\n\n\tif status.Code == int32(code.Code_OK) {\n\t\tresponse.Amount = 1\n\t}\n}", "func NewRateLimiter(r rate.Limit, b int) *RateLimiter {\n\treturn NewRateLimiterWithValue(r, b, 0)\n}", "func NewRateLimiter(freq time.Duration, burstSize int) *Limiter {\n\treturn &Limiter{\n\t\tconnectionFreq: freq,\n\t\tconnectionBurstSize: burstSize,\n\t}\n}", "func NewGetQuotaQuotaDefault(code int) *GetQuotaQuotaDefault {\n\treturn &GetQuotaQuotaDefault{\n\t\t_statusCode: code,\n\t}\n}", "func (lim Limit) Name() string { return \"limit\" }", "func rateLimitHandler(limit int, within int) gin.HandlerFunc {\n\treturn throttle.Policy(&throttle.Quota{\n\t\tLimit: uint64(limit),\n\t\tWithin: time.Duration(within) * time.Second,\n\t})\n}", "func (client IotHubResourceClient) GetQuotaMetricsSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (m Message) GetBidSpotRate(f *field.BidSpotRateField) quickfix.MessageRejectError {\n\treturn m.Body.Get(f)\n}", "func (d *HetznerCloudProvider) GetResourceLimiter() (*cloudprovider.ResourceLimiter, error) {\n\treturn d.resourceLimiter, nil\n}", "func (n *Globals) RateLimit(url string) {\n\tif rateLimiter, ok := n.rateLimiters[url]; ok {\n\t\trateLimiter.Wait()\n\t}\n}", "func getProjectQuota(backingFsBlockDev string, projectID quotaID) (*types.DiskQuotaSize, error) {\n\tvar d C.fs_disk_quota_t\n\n\tvar cs = C.CString(backingFsBlockDev)\n\tdefer C.free(unsafe.Pointer(cs))\n\n\t_, _, errno := unix.Syscall6(unix.SYS_QUOTACTL, C.Q_XGETPQUOTA,\n\t\tuintptr(unsafe.Pointer(cs)), uintptr(C.__u32(projectID)),\n\t\tuintptr(unsafe.Pointer(&d)), 0, 0)\n\tif errno != 0 {\n\t\treturn nil, fmt.Errorf(\"failed to get quota limit for projid %d on %s: %v\",\n\t\t\tprojectID, backingFsBlockDev, errno)\n\t}\n\n\treturn &types.DiskQuotaSize{\n\t\tQuota: uint64(d.d_blk_hardlimit) * 512,\n\t\tInodes: uint64(d.d_ino_hardlimit),\n\t\tQuotaUsed: uint64(d.d_bcount) * 512,\n\t\tInodesUsed: uint64(d.d_icount),\n\t}, nil\n}", "func getPquotaState() *pquotaState {\n\tpquotaStateOnce.Do(func() {\n\t\tpquotaStateInst = &pquotaState{\n\t\t\tnextProjectID: 1,\n\t\t}\n\t})\n\treturn pquotaStateInst\n}", "func NewRateLimiter(config *config.RuntimeSecurityConfig, client statsd.ClientInterface) *RateLimiter {\n\trl := &RateLimiter{\n\t\tlimiters: make(map[string]Limiter),\n\t\tstatsdClient: client,\n\t\tconfig: config,\n\t}\n\n\treturn rl\n}", "func (aws *awsCloudProvider) GetResourceLimiter() (*cloudprovider.ResourceLimiter, error) {\n\treturn aws.resourceLimiter, nil\n}" ]
[ "0.63732344", "0.61184627", "0.6054561", "0.5927608", "0.59067774", "0.5875768", "0.5850694", "0.5722346", "0.5709863", "0.57009006", "0.55981433", "0.55607927", "0.5511379", "0.5488253", "0.545794", "0.545549", "0.5450386", "0.5448698", "0.54485756", "0.5434681", "0.5430217", "0.541487", "0.5414481", "0.53985214", "0.5395766", "0.53810453", "0.5378772", "0.53596234", "0.5343917", "0.53393495", "0.53345245", "0.5322293", "0.5316352", "0.5304166", "0.5300177", "0.5293588", "0.52773184", "0.5214147", "0.5207509", "0.518691", "0.5185628", "0.51569366", "0.5144939", "0.513743", "0.51227045", "0.51092523", "0.5101368", "0.50985885", "0.5084231", "0.5076194", "0.50729686", "0.50702614", "0.50605136", "0.50569695", "0.5045966", "0.50383854", "0.50143075", "0.49982396", "0.4981968", "0.49667802", "0.49583632", "0.49386352", "0.49281165", "0.49028945", "0.48910087", "0.4886435", "0.48854217", "0.48820052", "0.48675779", "0.48451728", "0.4837788", "0.48238525", "0.47971144", "0.47902706", "0.478985", "0.47837695", "0.47824752", "0.47794443", "0.47773927", "0.47772107", "0.47678143", "0.47566542", "0.4751774", "0.4735468", "0.47221726", "0.47194692", "0.4713273", "0.4712627", "0.47018328", "0.46799853", "0.4672755", "0.46642125", "0.4662446", "0.4661927", "0.46598762", "0.46506965", "0.46450126", "0.46373338", "0.46315324", "0.46311885" ]
0.7855245
0
If set, when a client reaches a rate limit threshold, the client will be prohibited from any further requests until after the 'block_interval' in seconds has elapsed.
func (o QuotaRateLimitOutput) BlockInterval() pulumi.IntPtrOutput { return o.ApplyT(func(v *QuotaRateLimit) pulumi.IntPtrOutput { return v.BlockInterval }).(pulumi.IntPtrOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) RateLimit() int {\n\treturn c.rateLimit\n}", "func (l *LimitRate) Allow() bool {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tif l.count >= l.rate - 1 {\n\t\tnow := time.Now()\n\t\tif now.Sub(l.begin) >= l.cycle {\n\t\t\tl.Reset(now)\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tl.count++\n\t\treturn true\n\t}\n}", "func (ob *Observable) RateLimit(timeframeMS int, notifyWhenChangesStop ...bool) {\n\tmethod := \"notifyAtFixedRate\"\n\tif len(notifyWhenChangesStop) >= 1 && notifyWhenChangesStop[0] {\n\t\tmethod = \"notifyWhenChangesStop\"\n\t}\n\tob.Extend(js.M{\n\t\t\"rateLimit\": js.M{\n\t\t\t\"timeout\": timeframeMS,\n\t\t\t\"method\": method,\n\t\t},\n\t})\n}", "func (ob *Observable) RateLimit(timeframeMS int, notifyWhenChangesStop ...bool) {\n\tmethod := \"notifyAtFixedRate\"\n\tif len(notifyWhenChangesStop) >= 1 && notifyWhenChangesStop[0] {\n\t\tmethod = \"notifyWhenChangesStop\"\n\t}\n\tob.Extend(js.M{\n\t\t\"rateLimit\": js.M{\n\t\t\t\"timeout\": timeframeMS,\n\t\t\t\"method\": method,\n\t\t},\n\t})\n}", "func (c *Client) AllowBlocking(request *quotaservice.AllowRequest) error {\n\tresponse, err := c.qsClient.Allow(context.Background(), request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.Status != quotaservice.AllowResponse_OK {\n\t\t// A REJECT response. Return an error.\n\t\treturn errors.New(quotaservice.AllowResponse_Status_name[int32(response.Status)])\n\t}\n\n\tif response.WaitMillis > 0 {\n\t\ttime.Sleep(time.Millisecond * time.Duration(response.WaitMillis))\n\t}\n\n\treturn nil\n}", "func rateLimitHandler(limit int, within int) gin.HandlerFunc {\n\treturn throttle.Policy(&throttle.Quota{\n\t\tLimit: uint64(limit),\n\t\tWithin: time.Duration(within) * time.Second,\n\t})\n}", "func rateLimit(rw http.ResponseWriter, req *http.Request, app *App) bool {\n\tif app.Config.Rate_Limit.Enable {\n\t\tduration := time.Now().Unix() - app.Config.Rate_Limit.Seconds\n\t\tip, err := relevantIpBytes(req.RemoteAddr)\n\t\terrors := map[string]string{\"overall\": \"Rate limit reached.\"}\n\n\t\tif err != nil {\n\t\t\trenderErrors(rw, errors, 429)\n\t\t\treturn true\n\t\t}\n\n\t\tvar count int64\n\t\trow := app.Db.QueryRow(\"select count(*) from comments where ClientIp=? and Created>?\", ip, duration)\n\t\terr = row.Scan(&count)\n\n\t\tif err != nil || count >= app.Config.Rate_Limit.Max_Comments {\n\t\t\trenderErrors(rw, errors, 429)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (l *Limiter) Allow(now time.Time) (isAllowed bool, sleep time.Duration) {\n\telapsed := now.Sub(l.last)\n\n\t// \"rate * elapsed.Seconds()\" mean newly obtain tokens in the past elapsed time.\n\tl.tokens = l.tokens + l.rate*elapsed.Seconds()\n\tl.last = now\n\n\tif l.tokens > l.burst {\n\t\tl.tokens = l.burst\n\t}\n\n\t// Consume one token.\n\tl.tokens = l.tokens - 1\n\n\tif l.tokens < 0 {\n\t\t// \"-l.tokens / l.rate\" mean how many seconds can obtain these tokens.\n\t\treturn false, time.Duration(-l.tokens / l.rate * float64(time.Second))\n\t} else {\n\t\treturn true, 0\n\t}\n}", "func (c *V3Client) RateLimitMonitor() *ratelimit.Monitor {\n\treturn c.rateLimitMonitor\n}", "func (l *Limiter) Allow(ctx context.Context) (func(rate.Op), error) {\n\tvar (\n\t\tdone func(time.Time, rate.Op)\n\t\terr error\n\t\tok bool\n\t)\n\tif done, ok = l.rate.Acquire(); !ok {\n\t\t// NOTE exceed max inflight, use queue\n\t\tif err = l.queue.Push(ctx); err != nil {\n\t\t\tdone(time.Time{}, rate.Ignore)\n\t\t\treturn func(rate.Op) {}, err\n\t\t}\n\t}\n\tstart := time.Now()\n\treturn func(op rate.Op) {\n\t\tdone(start, op)\n\t\tl.queue.Pop()\n\t}, nil\n}", "func (rater *RateLimiter) Limit() {\n\t<-rater.semaphore\n}", "func throttled(threshold int64, h http.Handler) http.Handler {\n\tvar active int64\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tcurrent := atomic.AddInt64(&active, 1)\n\t\tdefer atomic.AddInt64(&active, -1)\n\n\t\tif current-1 >= threshold {\n\t\t\tlog.Warnf(\"Reached threshold of %d concurrent active clients\", threshold)\n\t\t\thttp.Error(w, \"429 Too Many Requests\", http.StatusTooManyRequests)\n\t\t\treturn\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func (l *RateLimiter) Allow() bool {\n\treturn l.AllowN(1)\n}", "func (l *RateLimiter) Allow() bool {\n\treturn l.AllowN(1)\n}", "func (c *Client) SetLimiter(rateLimit float64, burst int) {\n\tc.modifyLock.RLock()\n\tdefer c.modifyLock.RUnlock()\n\tc.config.modifyLock.Lock()\n\tdefer c.config.modifyLock.Unlock()\n\n\tc.config.Limiter = rate.NewLimiter(rate.Limit(rateLimit), burst)\n}", "func (l *IntLimiter) Allow(key int) bool {\n\tl.m.Lock()\n\n\tif _, ok := l.l[key]; !ok {\n\t\tl.l[key] = rate.NewLimiter(l.n, l.b)\n\t}\n\tok := l.l[key].Allow()\n\n\tl.m.Unlock()\n\n\treturn ok\n}", "func (s *Setup) RateLimit(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tip, _, err := net.SplitHostPort(r.RemoteAddr)\n\t\tif err != nil {\n\t\t\terrhandler.DecodeError(w, r, s.logger, errInternal, http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tlimiter := ratelimit.GetVisitor(ip)\n\t\tif !limiter.Allow() {\n\t\t\terrhandler.DecodeError(\n\t\t\t\tw,\n\t\t\t\tr,\n\t\t\t\ts.logger,\n\t\t\t\thttp.StatusText(http.StatusTooManyRequests),\n\t\t\t\thttp.StatusTooManyRequests,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (rl *ChannelBasedRateLimiter) Allow() bool {\n\t_, ok := <-rl.t.C\n\treturn ok\n}", "func (n *Globals) RateLimit(url string) {\n\tif rateLimiter, ok := n.rateLimiters[url]; ok {\n\t\trateLimiter.Wait()\n\t}\n}", "func (c *Client) RateLimit() RateLimit {\n\tif c.limit != nil {\n\t\treturn *c.limit\n\t}\n\taccount, err := c.Account.Get()\n\tif err != nil {\n\t\treturn RateLimit{}\n\t}\n\tc.limit = &RateLimit{}\n\tfor _, metric := range account.Metrics {\n\t\tif metric.PlanLevel > 0 {\n\t\t\tc.limit.Limit = metric.PlanLevel\n\t\t\tc.limit.Remaining = metric.Remaining\n\t\t}\n\t}\n\treturn *c.limit\n}", "func (b *RateBarrier) Allow() bool {\n\treturn b.source[int(atomic.AddUint64(&b.op, 1))%b.base] < b.rate\n}", "func RateLimit(max float64) gin.HandlerFunc {\n\n\tlmt := tollbooth.NewLimiter(max, nil)\n\n\treturn func(c *gin.Context) {\n\t\thttpError := tollbooth.LimitByRequest(lmt, c.Writer, c.Request)\n\t\tif httpError != nil {\n\t\t\tc.Data(httpError.StatusCode, lmt.GetMessageContentType(), []byte(httpError.Message))\n\t\t\tc.Abort()\n\t\t} else {\n\t\t\tc.Next()\n\t\t}\n\t}\n}", "func (a *AQM) Limit() bm.HandlerFunc {\n\treturn func(c *bm.Context) {\n\t\tdone, err := a.limiter.Allow(c)\n\t\tif err != nil {\n\t\t\tstats.Incr(_family, c.Request.URL.Path[1:])\n\t\t\t// TODO: priority request.\n\t\t\t// c.JSON(nil, err)\n\t\t\t// c.Abort()\n\t\t\treturn\n\t\t}\n\t\tdefer func() {\n\t\t\tif c.Error != nil && !ecode.Deadline.Equal(c.Error) && c.Err() != context.DeadlineExceeded {\n\t\t\t\tdone(rate.Ignore)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdone(rate.Success)\n\t\t}()\n\t\tc.Next()\n\t}\n}", "func (l *GoLimiter) Limit(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the IP address for the current user.\n\t\tip, _, err := net.SplitHostPort(r.RemoteAddr)\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\thttp.Error(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tkeyName := utils.NewKeyName(r.Method, r.RequestURI, ip)\n\n\t\t// Call the getRateLimiter function to retreive the rate limiter for the current user.\n\t\trateLimiter := l.getRateLimiter(keyName)\n\n\t\tif rateLimiter.Allow() == false {\n\t\t\thttp.Error(w, http.StatusText(429), http.StatusTooManyRequests)\n\t\t\treturn\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func (c *LimitedConnection) rateLimitLoop(notBefore *time.Time,\n\tdeadline *time.Time, innerAct func([]byte) (int, error),\n\tb []byte) (cntr int, err error) {\n\tif len(b) == 0 {\n\t\treturn\n\t}\n\n\tnow := time.Now()\n\tvar until time.Time\n\n\t// Grab the limiter and abortwait until end of operation.\n\tc.limiterMu.RLock()\n\tlimiter := c.limiter\n\tabortWait := c.abortWait\n\tif now.Before(*notBefore) {\n\t\tuntil = *notBefore\n\t\tif !deadline.IsZero() && deadline.Before(until) {\n\t\t\tuntil = *deadline\n\t\t}\n\t}\n\tc.limiterMu.RUnlock()\n\n\tif !until.IsZero() {\n\t\tif c.waitUntil(abortWait, until) {\n\t\t\terr = io.ErrClosedPipe\n\t\t\treturn\n\t\t}\n\t}\n\n\tburst := limiter.Burst()\n\tfor cntr < len(b) && err == nil {\n\t\tvar n int\n\t\tif burst > len(b)-cntr {\n\t\t\tburst = len(b) - cntr\n\t\t}\n\t\tn, err = innerAct(b[cntr:][:burst])\n\t\tif n == 0 {\n\t\t\treturn\n\t\t}\n\n\t\tcntr += n\n\t\tuntil = time.Time{}\n\n\t\tnow = time.Now()\n\t\tr := limiter.ReserveN(now, n)\n\t\tact := now.Add(r.DelayFrom(now))\n\t\tif now.Before(act) {\n\t\t\tif !deadline.IsZero() && deadline.Before(act) {\n\t\t\t\tc.limiterMu.RLock()\n\t\t\t\t// What I want to avoid here is the case when limiter got updated and\n\t\t\t\t// \"Not before\"s got reset during limiter update, but we don't know\n\t\t\t\t// about it and are going to write outdated value to notBefore.\n\t\t\t\t// A good test for this is checking if our cached abortWait is closed\n\t\t\t\tselect {\n\t\t\t\tcase <-abortWait:\n\t\t\t\t\t// Do nothing, our limits are no longer valid\n\t\t\t\tdefault:\n\t\t\t\t\t*notBefore = act\n\t\t\t\t}\n\t\t\t\tc.limiterMu.RUnlock()\n\t\t\t\terr = timeoutError{}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tuntil = act\n\t\t}\n\t\tif !until.IsZero() {\n\t\t\tif c.waitUntil(abortWait, act) {\n\t\t\t\terr = io.ErrClosedPipe\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (l *FixedLimiter) Allow() bool {\n\treturn l.AllowN(1)\n}", "func (cb *CircuitBreaker) Allow() bool {\n\t// force open the circuit, link is break so this is not allowed.\n\tif cb.forceOpen {\n\t\treturn false\n\t}\n\t// force close the circuit, link is not break so this is allowed.\n\tif cb.forceClose {\n\t\treturn true\n\t}\n\n\tvar now_ms int64\n\tnow_ms = NowInMs()\n\tcb.CalcStat(now_ms)\n\n\tif cb.circuitStatus == kCircuitClose {\n\t\treturn true\n\t} else {\n\t\tif cb.IsAfterSleepWindow(now_ms) {\n\t\t\tcb.lastCircuitOpenTime = now_ms\n\t\t\tcb.circuitStatus = kCircuitHalfOpen\n\t\t\t// sleep so long time, try ones, and set status to half-open\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func TestLimiter_Burst(t *testing.T) {\n\trate := ratelimiter.Frequency(20)\n\tburst := uint64(10)\n\tlimiter, err := ratelimiter.NewLimiter(rate, burst)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error creating limiter for testing: %s\", err.Error())\n\t}\n\t// Allow limiter token bucket to fill\n\ttime.Sleep(time.Millisecond * 500)\n\tfor i := uint64(0); i < burst; i++ {\n\t\tif !limiter.Allow() {\n\t\t\tt.Errorf(\"Expected limiter to return true for Allow() but returned false.\")\n\t\t}\n\t}\n\tif limiter.Allow() {\n\t\tt.Errorf(\"Expected limiter to return false after having Allow() called the maximum burst number of times\")\n\t}\n}", "func RateLimit(d time.Duration) Tick {\n\tvar last *time.Time\n\treturn func(children []Node) (Status, error) {\n\t\tnow := time.Now()\n\t\tif last != nil && now.Add(-d).Before(*last) {\n\t\t\treturn Failure, nil\n\t\t}\n\t\tlast = &now\n\t\treturn Success, nil\n\t}\n}", "func TestRateLimiterBroke(t *testing.T) {\n\treq, err := http.NewRequest(\"GET\", \"/stuff\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treq.RemoteAddr = \"zip.zap.zot\"\n\trl := NewRateLimiter(1, time.Minute)\n\n\tConvey(\"When many requests are made, and there is a ratelimiter, the appropriate number of requests are allowed and denied\", t, func() {\n\t\ttestHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\t})\n\n\t\thandler := rl.Handler(testHandler)\n\n\t\tvar (\n\t\t\tfourtwentynines = 0\n\t\t\ttwohundreds = 0\n\t\t)\n\n\t\tfor i := 0; i < 100; i++ {\n\t\t\trr := httptest.NewRecorder()\n\t\t\thandler.ServeHTTP(rr, req)\n\n\t\t\tif rr.Code == 429 {\n\t\t\t\tfourtwentynines++\n\t\t\t} else if rr.Code == 200 {\n\t\t\t\ttwohundreds++\n\t\t\t} else {\n\t\t\t\tt.Errorf(\"handler returned wrong status code: got %v want 200 or 429\\n\",\n\t\t\t\t\trr.Code)\n\t\t\t}\n\t\t}\n\t\t// Check the status code is what we expect.\n\t\tSo(twohundreds, ShouldBeLessThanOrEqualTo, 1)\n\t})\n}", "func (l *StdLimiter) Allow(_ Event) bool {\n\tif l.rateLimiter.Allow() {\n\t\tl.allowed.Inc()\n\t\treturn true\n\t}\n\tl.dropped.Inc()\n\n\treturn false\n}", "func (c *client) rateRequest() {\n\tc.rateMu.Lock()\n\tdefer c.rateMu.Unlock()\n\n\tif time.Now().After(c.nextReq) {\n\t\tc.nextReq = time.Now().Add(rateLimit)\n\t\treturn\n\t}\n\n\tcurrentReq := c.nextReq\n\tc.nextReq = currentReq.Add(rateLimit)\n\t<-time.After(currentReq.Sub(time.Now()))\n}", "func (h *handler) RateLimitTest(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"status\": 200,\n\t\t\"message\": \"Success\",\n\t})\n}", "func (m *RateLimitedMux) rateLimit(c web.C, w http.ResponseWriter, r *http.Request, limits []int, handler web.Handler) {\n\tif m.limiter == nil || r.Header.Get(IsAdminHeader) == IsAdminHeaderValue {\n\t\thandler.ServeHTTPC(c, w, r)\n\t\treturn\n\t}\n\n\tlimit := 0\n\tfor _, v := range limits {\n\t\tlimit += v\n\t}\n\n\tif limit == 0 {\n\t\thandler.ServeHTTPC(c, w, r)\n\t\treturn\n\t}\n\n\tkey := r.Header.Get(signcontrol.PublicKeyHeader)\n\n\tlimited, context, err := m.limiter.RateLimit(key, limit)\n\n\tif err != nil {\n\t\tlog.WithField(\"service\", \"rate-limiter\").WithError(err).Error(\"failed to rate limit\")\n\t\thandler.ServeHTTPC(c, w, r)\n\t\treturn\n\t}\n\n\tif v := context.Limit; v >= 0 {\n\t\tw.Header().Add(\"X-RateLimit-Limit\", strconv.Itoa(v))\n\t}\n\n\tif v := context.Remaining; v >= 0 {\n\t\tw.Header().Add(\"X-RateLimit-Remaining\", strconv.Itoa(v))\n\t}\n\n\tif v := context.ResetAfter; v >= 0 {\n\t\tvi := int(math.Ceil(v.Seconds()))\n\t\tw.Header().Add(\"X-RateLimit-Reset\", strconv.Itoa(vi))\n\t}\n\n\tif v := context.RetryAfter; v >= 0 {\n\t\tvi := int(math.Ceil(v.Seconds()))\n\t\tw.Header().Add(\"Retry-After\", strconv.Itoa(vi))\n\t}\n\n\tif !limited {\n\t\thandler.ServeHTTPC(c, w, r)\n\t} else {\n\t\tproblem.Render(nil, w, &problem.RateLimitExceeded)\n\t\treturn\n\t}\n\n}", "func (r *ringBufferRateLimiter) allowed() bool {\n\tif len(r.ring) == 0 {\n\t\treturn false\n\t}\n\tif time.Since(r.ring[r.cursor]) > r.window {\n\t\tr.reserve()\n\t\treturn true\n\t}\n\treturn false\n}", "func (r *rateLimiter) Block(key string) {\n\tnow := time.Now()\n\n\tr.Lock()\n\n\t// if there's nothing in the map we can\n\t// return straight away\n\tif _, ok := r.ops[key]; !ok {\n\t\tr.ops[key] = now\n\t\tr.Unlock()\n\t\treturn\n\t}\n\n\t// if time is up we can return straight away\n\tt := r.ops[key]\n\tdeadline := t.Add(r.delay)\n\tif now.After(deadline) {\n\t\tr.ops[key] = now\n\t\tr.Unlock()\n\t\treturn\n\t}\n\n\tremaining := deadline.Sub(now)\n\n\t// Set the time of the operation\n\tr.ops[key] = now.Add(remaining)\n\tr.Unlock()\n\n\t// Block for the remaining time\n\t<-time.After(remaining)\n}", "func (adminAPIOp) BypassInteractionIPRateLimit() bool { return true }", "func (cs *Server) rateLimit(keyID, claimedIP string) (isSpammer bool) {\n\tcs.whiteListMu.Lock()\n\tif _, ok := cs.whiteList[keyID+\"-\"+claimedIP]; ok {\n\t\tcs.whiteListMu.Unlock()\n\t\treturn false\n\t}\n\tcs.whiteListMu.Unlock()\n\t// If they haven't successfully challenged us before, they look suspicious.\n\tcs.keyIDSeenMu.Lock()\n\tlastSeen, ok := cs.keyIDSeen[keyID]\n\t// always keep track of the last time we saw them\n\tcs.keyIDSeen[keyID] = time.Now()\n\tcs.keyIDSeenMu.Unlock()\n\ttime.AfterFunc(forgetSeen, func() {\n\t\t// but everyone get a clean slate after a minute of being quiet\n\t\tcs.keyIDSeenMu.Lock()\n\t\tdelete(cs.keyIDSeen, keyID)\n\t\tcs.keyIDSeenMu.Unlock()\n\t})\n\tif ok {\n\t\t// if we've seen their keyID before, they look even more suspicious, so investigate.\n\t\tif lastSeen.Add(spamDelay).After(time.Now()) {\n\t\t\t// we kick them out if we saw them less than 5 seconds ago.\n\t\t\treturn true\n\t\t}\n\t}\n\tcs.IPSeenMu.Lock()\n\tlastSeen, ok = cs.IPSeen[claimedIP]\n\t// always keep track of the last time we saw them\n\tcs.IPSeen[claimedIP] = time.Now()\n\tcs.IPSeenMu.Unlock()\n\ttime.AfterFunc(forgetSeen, func() {\n\t\t// but everyone get a clean slate after a minute of being quiet\n\t\tcs.IPSeenMu.Lock()\n\t\tdelete(cs.IPSeen, claimedIP)\n\t\tcs.IPSeenMu.Unlock()\n\t})\n\tif ok {\n\t\t// if we've seen their IP before, they look even more suspicious, so investigate.\n\t\tif lastSeen.Add(spamDelay).After(time.Now()) {\n\t\t\t// we kick them out if we saw them less than 5 seconds ago.\n\t\t\treturn true\n\t\t}\n\t}\n\t// global rate limit that applies to all strangers at the same time\n\tcs.limiter.Wait(context.Background())\n\treturn false\n}", "func RateLimited(w http.ResponseWriter, r *http.Request) {\n\tlogs.WriteError(\"IP address is rate limited.\")\n\tr.URL.Path = config.RateLimitedScript\n\n\tHandle(w, r)\n\n\tlogs.WriteError(\"IP address is rate limited.\")\n\n}", "func (ctx *Context) RateLimitHandler(parent http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t<-ctx.rateLimit\n\t\tdefer func() {\n\t\t\tctx.rateLimit <- struct{}{}\n\t\t}()\n\t\tparent.ServeHTTP(w, r)\n\t})\n}", "func (a *Application) Limit() int64 {\n\tif a.InProduction {\n\t\treturn rateLimitProduction\n\t}\n\n\treturn rateLimitStaging\n}", "func (l *LimitRate) Allow2() bool {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tif l.count >= l.rate - 1 {\n\t\tfor {\n\t\t\tnow := time.Now()\n\t\t\tif now.Sub(l.begin) >= l.cycle {\n\t\t\t\tl.Reset(now)\n\t\t\t\treturn true\n\t\t\t} else {\n\t\t\t\t//do nothing to wait\n\t\t\t}\n\t\t}\n\t} else {\n\t\tl.count++\n\t\treturn true\n\t}\n}", "func (c *APIClient) RateLimitStrategySleep() {\n\tc.RateLimitFunc = func(rl RateLimit) {\n\t\tremaining := rl.WaitTimeRemaining()\n\t\tif c.debug {\n\t\t\tlog.Printf(\"Rate limiting - Limit %d Remaining %d in period %d: Sleeping %dns\", rl.Limit, rl.Remaining, rl.Period, remaining)\n\t\t}\n\t\ttime.Sleep(remaining)\n\t}\n}", "func (e *Opener) Prevent(now time.Time) (shouldAllow bool) {\n\treturn false\n}", "func RateLimit(r rate.Limit, b, cap int) Allow {\n\tcap /= 2\n\tfront := make(map[string]*rate.Limiter, cap)\n\tback := make(map[string]*rate.Limiter, cap)\n\n\treturn func(conn net.Conn) (error, Cleanup) {\n\t\tremoteAddr := \"\"\n\t\tif tcpAddr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {\n\t\t\tremoteAddr = tcpAddr.IP.String()\n\t\t} else {\n\t\t\tremoteAddr = conn.RemoteAddr().String()\n\t\t}\n\n\t\tallow := func(limiter *rate.Limiter) (error, func()) {\n\t\t\tif limiter.Allow() {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t\treturn ErrRateLimited, nil\n\t\t}\n\n\t\tlimiter := front[remoteAddr]\n\t\tif limiter != nil {\n\t\t\treturn allow(limiter)\n\t\t}\n\n\t\tlimiter = back[remoteAddr]\n\t\tif limiter != nil {\n\t\t\treturn allow(limiter)\n\t\t}\n\n\t\tif len(front) == cap {\n\t\t\tback = front\n\t\t\tfront = make(map[string]*rate.Limiter, cap)\n\t\t}\n\n\t\tlimiter = rate.NewLimiter(r, b)\n\t\tfront[remoteAddr] = limiter\n\t\treturn allow(limiter)\n\t}\n}", "func (rl *RateLimiter) AllowRequest(id string) (bool, error) {\n\tnow := time.Now().UnixNano() / 1000 //microseconds\n\tclearBefore := now - (rl.intervalInMillis * 1000) //microseconds\n\tlog.Debug(\"clearBefore \", clearBefore)\n\n\telement, err := uuid()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tlog.Debug(\"new element \", element)\n\n\tnewZSetExpireTime := rl.intervalInMillis/1000\n\n\tcmd := rl.client.Eval(concurrent_requests_limiter_lua, []string{id},rl.maxInInterval, now,element, clearBefore, newZSetExpireTime)\n\tif cmd.Err() != nil {\n\t\tlog.Warn(\"script execution error\", cmd.Err().Error())\n\t\treturn false, cmd.Err()\n\t}\n\n\tcmdOutput := cmd.Val()\n\tlog.Debug(\"script output \", cmdOutput)\n\toutputSlice, ok := cmdOutput.([]interface{})\n\tif !ok {\n\t\treturn false, errors.New(\"Unexcepted result type from Redis script execution\")\n\t}\n\n\treturn outputSlice[0] != nil, nil\n}", "func (c Client) RateLimit() ratelimit.Client {\n\treturn ratelimit.NewClient(c...)\n}", "func (m *MemLimiter) Limit(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"X-RateLimit-Limit\", strconv.Itoa(int(m.cfg.IpLimit)))\n\n\t\tip, _, _ := net.SplitHostPort(r.RemoteAddr)\n\t\turl := r.RequestURI\n\t\tipl := m.getLimiter(IpAddress, ip)\n\t\tpathl := m.getLimiter(URL, url)\n\n\t\tif ipl.Allow() == false || pathl.Allow() == false {\n\t\t\tw.Header().Set(\"X-RateLimit-Limit\", strconv.Itoa(int(m.cfg.IpLimit)))\n\t\t\thttp.Error(w, \"API rate limit exceeded\", http.StatusTooManyRequests)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func Block(c *blocker.Client, h http.Handler) http.Handler {\n\treturn BlockWithCode(c, h, http.StatusForbidden)\n}", "func (l *RateLimiter) AllowN(n int) bool {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tnow := time.Now()\n\treturn l.limiter.AllowN(now, n)\n}", "func (al *AnomalyDetectionLimiter) Allow(event Event) bool {\n\treturn al.limiter.Allow(event.GetWorkloadID())\n}", "func (l *RateLimiter) Limit(now time.Time, tenantID string) float64 {\n\treturn float64(l.getTenantLimiter(now, tenantID).Limit())\n}", "func RateLimit(dur time.Duration) func(*Dispatcher) {\n\treturn func(d *Dispatcher) {\n\t\td.startTicker(dur)\n\t}\n}", "func (s ServiceLimiter) LimitRequest(r *request.Request) {\n\tif ol, ok := s.matchRequest(r); ok {\n\t\t_ = ol.Wait(r)\n\t}\n}", "func (c *ReadOnlyRedditClient) Throttle(interval time.Duration) {\n\tif interval == 0 {\n\t\tc.throttle = nil\n\t} else {\n\t\tc.throttle = rate.New(1, interval)\n\t}\n}", "func (l *Limiter) Wait() {\n\tisAllowed, sleep := l.Allow(time.Now())\n\tif !isAllowed {\n\t\ttime.Sleep(sleep)\n\t}\n}", "func (l *RateLimiter) Limit() rate.Limit {\n\treturn l.limiter.Limit()\n}", "func (t *myTransport) block(ctx context.Context, parsedRequests []ModifiedRequest) (int, interface{}) {\n\tvar union *blockRange\n\tfor _, parsedRequest := range parsedRequests {\n\t\tctx = gotils.With(ctx, \"ip\", parsedRequest.RemoteAddr)\n\t\tif allowed, _ := t.AllowVisitor(parsedRequest); !allowed {\n\t\t\tgotils.L(ctx).Info().Print(\"Request blocked: Rate limited\")\n\t\t\treturn http.StatusTooManyRequests, jsonRPCLimit(parsedRequest.ID)\n\t\t} //else if added {\n\t\t// gotils.L(ctx).Debug().Printf(\"Added new visitor, ip: %v\", parsedRequest.RemoteAddr)\n\t\t// }\n\n\t\tif !t.MatchAnyRule(parsedRequest.Path) {\n\t\t\t// gotils.L(ctx).Debug().Print(\"Request blocked: Method not allowed\")\n\t\t\treturn http.StatusMethodNotAllowed, jsonRPCUnauthorized(parsedRequest.ID, parsedRequest.Path)\n\t\t}\n\t\tif t.blockRangeLimit > 0 && parsedRequest.Path == \"eth_getLogs\" {\n\t\t\tr, invalid, err := t.parseRange(ctx, parsedRequest)\n\t\t\tif err != nil {\n\t\t\t\treturn http.StatusInternalServerError, jsonRPCError(parsedRequest.ID, jsonRPCInternal, err.Error())\n\t\t\t} else if invalid != nil {\n\t\t\t\tgotils.L(ctx).Info().Printf(\"Request blocked: Invalid params: %v\", invalid)\n\t\t\t\treturn http.StatusBadRequest, jsonRPCError(parsedRequest.ID, jsonRPCInvalidParams, invalid.Error())\n\t\t\t}\n\t\t\tif r != nil {\n\t\t\t\tif l := r.len(); l > t.blockRangeLimit {\n\t\t\t\t\tgotils.L(ctx).Info().Println(\"Request blocked: Exceeds block range limit, range:\", l, \"limit:\", t.blockRangeLimit)\n\t\t\t\t\treturn http.StatusBadRequest, jsonRPCBlockRangeLimit(parsedRequest.ID, l, t.blockRangeLimit)\n\t\t\t\t}\n\t\t\t\tif union == nil {\n\t\t\t\t\tunion = r\n\t\t\t\t} else {\n\t\t\t\t\tunion.extend(r)\n\t\t\t\t\tif l := union.len(); l > t.blockRangeLimit {\n\t\t\t\t\t\tgotils.L(ctx).Info().Println(\"Request blocked: Exceeds block range limit, range:\", l, \"limit:\", t.blockRangeLimit)\n\t\t\t\t\t\treturn http.StatusBadRequest, jsonRPCBlockRangeLimit(parsedRequest.ID, l, t.blockRangeLimit)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0, nil\n}", "func (bas *BaseService) CheckRateLimit() {\n\tbas.rlock.Lock()\n\trlimit := bas.rlimit\n\tbas.rlock.Unlock()\n\n\tif rlimit != nil {\n\t\trlimit.Take()\n\t}\n}", "func RateLimit(w http.ResponseWriter, r *http.Request) {\n\tvar tc *http.Client\n\n\tc := cloudpkgs.NewContext(w, r)\n\tctx := context.Background()\n\n\tt := c.Request.Header.Get(\"Authorization\")\n\tif t != \"\" {\n\t\tts := oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: t},\n\t\t)\n\t\ttc = oauth2.NewClient(ctx, ts)\n\t}\n\n\tclient := cloudapi.NewAPIClient(tc)\n\n\trate, _, err := client.Client.RateLimits(ctx)\n\tif err != nil {\n\t\tc.WriteJSON(http.StatusRequestTimeout, cloudpkgs.H{\"status\": http.StatusRequestTimeout})\n\t\treturn\n\t}\n\n\tc.WriteJSON(http.StatusOK, cloudpkgs.H{\"status\": http.StatusOK, \"rate\": rate})\n}", "func (_m *Factory) SetClientBurst(_a0 int) {\n\t_m.Called(_a0)\n}", "func Limit(config *Config, limiterMap *LimitMap) gin.HandlerFunc {\r\n\tignoreMethods := config.IgnoreMethods\r\n\ttimeLimitPerAct := config.TimeLimitPerAct\r\n\tper := perOption(config.Per)\r\n\tmaxSlack := slackOption(config.MaxSlack)\r\n\tif ignoreMethods != nil {\r\n\t\tdefaultNegelectMethods = ignoreMethods\r\n\t}\r\n\tif timeLimitPerAct != 0 {\r\n\t\tdefaultTimeLimitPerAct = timeLimitPerAct\r\n\t}\r\n\tif per != 0 {\r\n\t\tdefaultPer = per\r\n\t}\r\n\tif maxSlack != 0 {\r\n\t\tdefaultMaxSlack = maxSlack\r\n\t}\r\n\treturn func(c *gin.Context) {\r\n\t\tlimiter := limiterMap.get(c.ClientIP())\r\n\t\tif limiter != nil {\r\n\t\t\tlimiter.Take()\r\n\t\t} else {\r\n\t\t\tlimiterMap.add(c.ClientIP())\r\n\t\t}\r\n\t\tc.Next()\r\n\t}\r\n}", "func (l *ConLimiter) Limit(s *http.Server) {\n\ts.ConnState = func(c net.Conn, state http.ConnState) {\n\t\tswitch state {\n\t\tcase http.StateNew:\n\t\t\tatomic.AddInt32(&l.current, 1)\n\t\t\tif l.Max < atomic.LoadInt32(&l.current) {\n\t\t\t\tc.Close()\n\t\t\t}\n\t\tcase http.StateHijacked:\n\t\t\tatomic.AddInt32(&l.current, -1)\n\t\tcase http.StateClosed:\n\t\t\tatomic.AddInt32(&l.current, -1)\n\t\t}\n\t}\n}", "func lockLimitConnections() {\n\tsemaphoreMaxConnections <- struct{}{}\n}", "func (t *threadThrottler) setMaxRate(newRate int64) {\n\tt.maxRate.Store(newRate)\n}", "func retryWhenRateLimited(cb func() error) error {\n\tretries := 0\n\tfor {\n\t\tif retries > 5 {\n\t\t\treturn errors.New(\"To many retries, stopping\")\n\t\t}\n\t\tretries++\n\n\t\terr := cb()\n\t\tif err != nil {\n\t\t\trerr, ok := err.(*github.RateLimitError)\n\t\t\tif ok {\n\t\t\t\tvar d = time.Until(rerr.Rate.Reset.Time)\n\t\t\t\tlog.Warnf(\"Hit rate limit, sleeping for %.0f min\", d.Minutes())\n\t\t\t\ttime.Sleep(d)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taerr, ok := err.(*github.AbuseRateLimitError)\n\t\t\tif ok {\n\t\t\t\tvar d = aerr.GetRetryAfter()\n\t\t\t\tlog.Warnf(\"Hit abuse mechanism, sleeping for %.f min\", d.Minutes())\n\t\t\t\ttime.Sleep(d)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn errors.Wrap(err, \"Error calling github web-api\")\n\t\t}\n\t\treturn nil\n\t}\n}", "func RatelimitUser(msg util.IncomingSlackMessage) bool {\n\tif _, in := ratelimitMap[msg.User]; !in {\n\t\tratelimitMap[msg.User] = time.Tick(3 * time.Second)\n\t\ttime.Sleep(3 * time.Second)\n\t}\n\tselect {\n\tcase <-ratelimitMap[msg.User]:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func throttled() bool {\n\tif disableRateLimiter {\n\t\treturn false\n\t}\n\treturn !lim.Allow()\n}", "func (at *Onlinesim) SetRateLimit(customRateLimit int) {\n\tat.rateLimiter = time.Tick(time.Second / time.Duration(customRateLimit))\n}", "func (s *Server) Limit(limiter Limiter) grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {\n\t\tif limiter.Allow(info.FullMethod) {\n\t\t\tif s.Proba.TrueOrNot() {\n\t\t\t\ts.Logger.Error(\"Limit exceed\", zap.String(\"method\", info.FullMethod))\n\t\t\t}\n\t\t\t//在触发RPC调用前就return了,所以其他需要捕获错误的中间件需要设置在limiter之前\n\t\t\t//return nil, status.Errorf(codes.ResourceExhausted, \"%s is rejected by ratelimit middleware\", info.FullMethod)\n\t\t\t//for short metrics:atreusns_atreusss_server_counter_total{code=\"ErrRatelimit\",method=\"/proto.GreeterService/SayHello\",type=\"unary\"} 2\n\t\t\treturn nil, status.Error(codes.ResourceExhausted, pyerrors.RatelimiterServiceReject)\n\t\t}\n\n\t\treturn handler(ctx, req)\n\t}\n}", "func (h *HandleHelper) RateLimitExceede() {\n\terrResponse(http.StatusTooManyRequests,\n\t\t\"rate limit exceeded\",\n\t)(h.w, h.r)\n}", "func (l *Limiter) limit(w http.ResponseWriter, r *http.Request, h http.Handler) {\n\tavailable := l.bucket.TakeAvailable(1)\n\n\theaders := w.Header()\n\theaders.Set(\"X-RateLimit-Limit\", strconv.Itoa(l.capacity()))\n\theaders.Set(\"X-RateLimit-Remaining\", strconv.Itoa(l.remaining()))\n\n\t// If tokens are not available, reply with error, usually with 429\n\tif available == 0 {\n\t\tl.responder(w, r)\n\t\treturn\n\t}\n\n\t// Otherwise track time and forward the request\n\th.ServeHTTP(w, r)\n}", "func rateLimit(limit int) func(next http.Handler) http.Handler {\n\tlimiter := rate.NewLimiter(rate.Every(time.Second/time.Duration(limit)), limit*2)\n\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tif !limiter.Allow() {\n\t\t\t\terrRateLimitExceeded.Write(w)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func (r *Ratelimit) Limited(key string, max int64) (bool, error) {\n\t// TODO make it possible to use a prate limit per minute, hour or day\n\t// minute is 04\n\thour := time.Now().Format(\"15\")\n\tk := key + \":\" + hour\n\n\ts, err := r.redis.GetInt64(k)\n\tif err != nil {\n\t\t// fail closed so if redis is down we don't run without rate limit enforcement\n\t\treturn true, err\n\t}\n\n\tif s == -1 {\n\t\tr.log.Printf(\"%s is not set\", k)\n\t} else {\n\t\tr.log.Printf(\"%s is %d\", k, s)\n\t\tif s > max {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\ti, err := r.redis.Incr(k)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tok, err := r.redis.Expire(k, time.Minute)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif !ok {\n\t\tr.log.Printf(\"failed to set expiration on %s\", k)\n\t}\n\n\treturn i <= max, nil\n}", "func RateLimiting() {\n\n\t// First we’ll look at basic rate limiting.\n\t// Suppose we want to limit our handling of incoming requests.\n\t// We’ll serve these requests off a channel of the same name.\n\trequests := make(chan int, 5)\n\tfor i := 1; i <= 5; i++ {\n\t\trequests <- i\n\t}\n\tclose(requests)\n\n\t// This limiter channel will receive a value every 200 milliseconds.\n\t// This is the regulator in our rate limiting scheme.\n\tlimiter := time.Tick(200 * time.Millisecond)\n\n\t// By blocking on a receive from the limiter channel before serving each request,\n\t// we limit ourselves to 1 request every 200 milliseconds.\n\tfor req := range requests {\n\t\t<-limiter\n\t\tfmt.Println(\"request\", req, time.Now())\n\t}\n\t// We may want to allow short bursts of requests in our rate limiting\n\t// scheme while preserving the overall rate limit.\n\t//We can accomplish this by buffering our limiter channel.\n\t//This burstyLimiter channel will allow bursts of up to 3 events.\n\tburstyLimiter := make(chan time.Time, 3)\n\n\t// Fill up the channel to represent allowed bursting.\n\tfor i := 0; i < 3; i++ {\n\t\tburstyLimiter <- time.Now()\n\t}\n\n\t// Every 200 milliseconds we’ll try to add a new value to burstyLimiter, up to its limit of 3.\n\tgo func() {\n\t\tfor t := range time.Tick(200 * time.Millisecond) {\n\t\t\tburstyLimiter <- t\n\t\t}\n\t}()\n\n\t// Now simulate 5 more incoming requests.\n\t// The first 3 of these will benefit from the burst capability of burstyLimiter.\n\tburstyRequests := make(chan int, 5)\n\n\tfor i := 1; i <= 5; i++ {\n\t\tburstyRequests <- i\n\t}\n\tclose(burstyRequests)\n\tfor req := range burstyRequests {\n\t\t<-burstyLimiter\n\t\tfmt.Println(\"request\", req, time.Now())\n\t}\n\t// Running our program we see the first batch of requests handled once every ~200 milliseconds as desired.\n\t// For the second batch of requests we serve the first 3 immediately\n\t// because of the burstable rate limiting, then serve the remaining 2 with ~200ms delays each.\n\n}", "func (c *Controller) enqueueLadonPolicy(obj interface{}) {\n\tc.workqueue.AddRateLimited(obj)\n}", "func (r *RateLimit) Limit(ctx context.Context, f request.EndpointLimit) error {\n\tswitch f {\n\t// TODO: Add futures and swap functionality\n\tcase huobiFuturesAuth:\n\t\treturn r.FuturesAuth.Wait(ctx)\n\tcase huobiFuturesUnAuth:\n\t\treturn r.FuturesUnauth.Wait(ctx)\n\tcase huobiFuturesTransfer:\n\t\treturn r.FuturesXfer.Wait(ctx)\n\tcase huobiSwapAuth:\n\t\treturn r.SwapAuth.Wait(ctx)\n\tcase huobiSwapUnauth:\n\t\treturn r.SwapUnauth.Wait(ctx)\n\tdefault:\n\t\t// Spot calls\n\t\treturn r.Spot.Wait(ctx)\n\t}\n}", "func (prl *PeerRateLimiter) ExtendLimit(id identity.ID, val int) {\n\tif err := prl.doExtendLimit(id, val); err != nil {\n\t\tprl.log.Warnw(\"Rate limiter failed to extend peer activity limit\",\n\t\t\t\"peerId\", id)\n\t}\n}", "func Test_Limiter_Fixed_Window_Skip_Successful_Requests(t *testing.T) {\n\tt.Parallel()\n\t// Test concurrency using a default store\n\n\tapp := fiber.New()\n\n\tapp.Use(New(Config{\n\t\tMax: 1,\n\t\tExpiration: 2 * time.Second,\n\t\tSkipSuccessfulRequests: true,\n\t\tLimiterMiddleware: FixedWindow{},\n\t}))\n\n\tapp.Get(\"/:status\", func(c *fiber.Ctx) error {\n\t\tif c.Params(\"status\") == \"fail\" {\n\t\t\treturn c.SendStatus(400)\n\t\t}\n\t\treturn c.SendStatus(200)\n\t})\n\n\tresp, err := app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 200, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 429, resp.StatusCode)\n\n\ttime.Sleep(3 * time.Second)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n}", "func IBMCloudSDKBackoffPolicy(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {\n\t// Check for a Retry-After header.\n\tif resp != nil {\n\t\tif s, ok := resp.Header[\"Retry-After\"]; ok {\n\t\t\t// First, try to parse the value as an integer (number of seconds to wait)\n\t\t\tif sleep, err := strconv.ParseInt(s[0], 10, 64); err == nil {\n\t\t\t\treturn time.Second * time.Duration(sleep)\n\t\t\t}\n\n\t\t\t// Otherwise, try to parse the value as an HTTP Time value.\n\t\t\tif retryTime, err := http.ParseTime(s[0]); err == nil {\n\t\t\t\tsleep := time.Until(retryTime)\n\t\t\t\tif sleep > max {\n\t\t\t\t\tsleep = max\n\t\t\t\t}\n\t\t\t\treturn sleep\n\t\t\t}\n\n\t\t}\n\t}\n\n\t// If no header-based wait time can be determined, then ask DefaultBackoff()\n\t// to compute an exponential backoff.\n\treturn retryablehttp.DefaultBackoff(min, max, attemptNum, resp)\n}", "func SetRateLimit(perSec int) ClientOptionFunc {\n\treturn func(c *TogglHttpClient) error {\n\t\tstore, err := memstore.New(65536)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tquota := throttled.RateQuota{throttled.PerSec(perSec), 1}\n\t\tc.rateLimiter, err = throttled.NewGCRARateLimiter(store, quota)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.perSec = perSec\n\t\treturn nil\n\t}\n}", "func rateLimited(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\trerr, ok := err.(*github.RateLimitError)\n\tif ok {\n\t\tvar d = time.Until(rerr.Rate.Reset.Time)\n\t\tlog.Warnf(\"hit rate limit, sleeping for %.0f min\", d.Minutes())\n\t\ttime.Sleep(d)\n\t\treturn true\n\t}\n\taerr, ok := err.(*github.AbuseRateLimitError)\n\tif ok {\n\t\tvar d = aerr.GetRetryAfter()\n\t\tlog.Warnf(\"hit abuse mechanism, sleeping for %.f min\", d.Minutes())\n\t\ttime.Sleep(d)\n\t\treturn true\n\t}\n\treturn false\n}", "func TestRateLimitHandler(t *testing.T) {\n\t// save the global Max connections\n\tsaveGlobalMaxConn := globalMaxConn\n\n\tglobalMaxConn = 1\n\ttestHandler := func(w http.ResponseWriter, r *http.Request) {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tfmt.Fprintln(w, \"Hello client!\")\n\t}\n\trlh := setRateLimitHandler(http.HandlerFunc(testHandler))\n\tts := httptest.NewServer(rlh)\n\trespCh := make(chan int)\n\tstartTime := time.Now()\n\tfor i := 0; i < 6; i++ {\n\t\tgo func(ch chan<- int) {\n\t\t\tresp, err := http.Get(ts.URL)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\n\t\t\t\t\t\"Got error requesting test server - %v\\n\",\n\t\t\t\t\terr,\n\t\t\t\t)\n\t\t\t}\n\t\t\trespCh <- resp.StatusCode\n\t\t}(respCh)\n\t}\n\n\ttooManyReqErrCount := 0\n\tfor i := 0; i < 6; i++ {\n\t\tcode := <-respCh\n\t\tif code == 429 {\n\t\t\ttooManyReqErrCount++\n\t\t} else if code != 200 {\n\t\t\tt.Errorf(\"Got non-200 resp code - %d\\n\", code)\n\t\t}\n\t}\n\tduration := time.Since(startTime)\n\tif duration < time.Duration(500*time.Millisecond) {\n\t\t// as globalMaxConn is 1, only 1 request will execute\n\t\t// at a time, and the five allowed requested will take\n\t\t// at least 500 ms.\n\t\tt.Errorf(\"Expected all requests to take at least 500ms, but it was done in %v\\n\",\n\t\t\tduration)\n\t}\n\tif tooManyReqErrCount != 1 {\n\t\tt.Errorf(\"Expected to get 1 error, but got %d\",\n\t\t\ttooManyReqErrCount)\n\t}\n\tts.Close()\n\n\t// restore the global Max connections\n\tglobalMaxConn = saveGlobalMaxConn\n}", "func Test_Limiter_Sliding_Window_Skip_Successful_Requests(t *testing.T) {\n\tt.Parallel()\n\t// Test concurrency using a default store\n\n\tapp := fiber.New()\n\n\tapp.Use(New(Config{\n\t\tMax: 1,\n\t\tExpiration: 2 * time.Second,\n\t\tSkipSuccessfulRequests: true,\n\t\tLimiterMiddleware: SlidingWindow{},\n\t}))\n\n\tapp.Get(\"/:status\", func(c *fiber.Ctx) error {\n\t\tif c.Params(\"status\") == \"fail\" {\n\t\t\treturn c.SendStatus(400)\n\t\t}\n\t\treturn c.SendStatus(200)\n\t})\n\n\tresp, err := app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 200, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 429, resp.StatusCode)\n\n\ttime.Sleep(4 * time.Second)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n}", "func (s *RateLimitSuite) TestRequestInvalidConfig(c *C) {\n\t// Given\n\trl, _ := FromOther(\n\t\tRateLimit{\n\t\t\tPeriodSeconds: 1,\n\t\t\tRequests: 1,\n\t\t\tBurst: 1,\n\t\t\tVariable: \"client.ip\",\n\t\t\tRateVar: \"request.header.X-Rates\",\n\t\t\tclock: s.clock,\n\t\t})\n\n\trli, _ := rl.NewMiddleware()\n\n\trequest := &request.BaseRequest{\n\t\tHttpRequest: &http.Request{\n\t\t\tRemoteAddr: \"1.2.3.4\",\n\t\t\tHeader: http.Header(map[string][]string{\n\t\t\t\t\"X-Rates\": []string{`[{\"PeriodSeconds\": -1, \"Requests\": 10}]`}}),\n\t\t},\n\t}\n\n\t// When/Then: The default rate of 1 request/second is used.\n\tresponse, err := rli.ProcessRequest(request) // Processed\n\tc.Assert(response, IsNil)\n\tc.Assert(err, IsNil)\n\tresponse, err = rli.ProcessRequest(request) // Rejected\n\tc.Assert(response, NotNil)\n\tc.Assert(err, IsNil)\n\n\ts.clock.Sleep(time.Second)\n\tresponse, err = rli.ProcessRequest(request) // Processed\n\tc.Assert(response, IsNil)\n\tc.Assert(err, IsNil)\n}", "func TestRateLimiterClear(t *testing.T) {\n\treq, err := http.NewRequest(\"GET\", \"/stuff\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treq.RemoteAddr = \"zip.zap.zot\"\n\trl := NewRateLimiter(1, 0)\n\n\tConvey(\"When a request is made, and there is a ratelimiter, if the request rate is under the limit, the request is ok\", t, func() {\n\t\ttestHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\t})\n\n\t\trr := httptest.NewRecorder()\n\n\t\thandler := rl.Handler(testHandler)\n\n\t\thandler.ServeHTTP(rr, req)\n\n\t\tSo(rr.Code, ShouldEqual, http.StatusOK)\n\t})\n}", "func (rl *redisRateLimiter) RateLimit(ctx gocontext.Context, name string, maxCalls uint64, per time.Duration) (bool, error) {\n\tif trace.FromContext(ctx) != nil {\n\t\tvar span *trace.Span\n\t\tctx, span = trace.StartSpan(ctx, \"Redis.RateLimit\")\n\t\tdefer span.End()\n\t}\n\n\tpoolCheckoutStart := time.Now()\n\n\tconn := rl.pool.Get()\n\tdefer conn.Close()\n\n\tcontext.TimeSince(ctx, \"rate_limit_redis_pool_wait\", poolCheckoutStart)\n\n\tif trace.FromContext(ctx) != nil {\n\t\tvar span *trace.Span\n\t\tctx, span = trace.StartSpan(ctx, \"Redis.RateLimit.WithPool\")\n\t\tdefer span.End()\n\t}\n\n\tif rl.dynamicConfig {\n\t\terr := rl.loadDynamicConfig(ctx, conn, name, &maxCalls, &per)\n\t\tif err != nil && err != redis.ErrNil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tnow := time.Now()\n\ttimestamp := now.Unix() - (now.Unix() % int64(per.Seconds()))\n\n\tkey := fmt.Sprintf(\"%s:%s:%d\", rl.prefix, name, timestamp)\n\n\tcur, err := redis.Int64(conn.Do(\"GET\", key))\n\tif err != nil && err != redis.ErrNil {\n\t\treturn false, err\n\t}\n\n\tif err != redis.ErrNil && uint64(cur) >= maxCalls {\n\t\treturn false, nil\n\t}\n\n\t_, err = conn.Do(\"WATCH\", key)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tconnSend := func(commandName string, args ...interface{}) {\n\t\tif err != nil && err != redis.ErrNil {\n\t\t\treturn\n\t\t}\n\t\terr = conn.Send(commandName, args...)\n\t}\n\tconnSend(\"MULTI\")\n\tconnSend(\"INCR\", key)\n\tconnSend(\"EXPIRE\", key, int64(per.Seconds()))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treply, err := conn.Do(\"EXEC\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif reply == nil {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}", "func (bas *BaseService) SetRateLimit(persec int) {\n\tbas.rlock.Lock()\n\tdefer bas.rlock.Unlock()\n\n\tif persec == 0 {\n\t\tbas.rlimit = nil\n\t\treturn\n\t}\n\n\tbas.rlimit = ratelimit.New(persec, ratelimit.WithoutSlack)\n}", "func LimitRate(timeFun func(time.Time) time.Time, limit int) pipes.Middleware {\n\tvar rateWindow string\n\tentry := &rateEntry{\n\t\tIPs: map[string]int{},\n\t}\n\n\treturn func(ctx context.Context, w http.ResponseWriter, r *http.Request, next pipes.Next) {\n\t\tip := r.RemoteAddr\n\t\tcurrentWindow := timeFun(getNow()).String()\n\n\t\tif currentWindow != rateWindow {\n\t\t\trateWindow = currentWindow\n\t\t\tentry = &rateEntry{\n\t\t\t\tIPs: map[string]int{\n\t\t\t\t\tip: 1,\n\t\t\t\t},\n\t\t\t}\n\t\t} else if entry.IPs[ip] > limit {\n\t\t\tw.WriteHeader(http.StatusTooManyRequests)\n\t\t\treturn\n\t\t} else {\n\t\t\tentry.IPs[ip]++\n\t\t}\n\t\tnext(ctx)\n\t}\n}", "func (r *Reader) setRate(lim rate.Limit) bool {\n\tmin := rate.Every(r.starvationLatency)\n\tmax := r.globalLimit.Limit()\n\n\tif lim < min {\n\t\tlim = min\n\t} else if lim > max {\n\t\tlim = max\n\t}\n\n\tprev := r.adaptiveLimit.Limit()\n\n\tif lim != prev {\n\t\tr.adaptiveLimit.SetLimit(lim)\n\t\treturn true\n\t}\n\n\treturn false\n}", "func Test_Limiter_Fixed_Window_No_Skip_Choices(t *testing.T) {\n\tt.Parallel()\n\tapp := fiber.New()\n\n\tapp.Use(New(Config{\n\t\tMax: 2,\n\t\tExpiration: 2 * time.Second,\n\t\tSkipFailedRequests: false,\n\t\tSkipSuccessfulRequests: false,\n\t\tLimiterMiddleware: FixedWindow{},\n\t}))\n\n\tapp.Get(\"/:status\", func(c *fiber.Ctx) error {\n\t\tif c.Params(\"status\") == \"fail\" { //nolint:goconst // False positive\n\t\t\treturn c.SendStatus(400)\n\t\t}\n\t\treturn c.SendStatus(200)\n\t})\n\n\tresp, err := app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 200, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 429, resp.StatusCode)\n\n\ttime.Sleep(3 * time.Second)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 200, resp.StatusCode)\n}", "func WithLimit(l int) Opts {\n\treturn func(r *retryable) {\n\t\tif l > 0 {\n\t\t\tr.limit = l\n\t\t}\n\t}\n}", "func (c *AuditClient) SetRateLimit(perSecondLimit uint32, wm WaitMode) error {\n\tstatus := AuditStatus{\n\t\tMask: AuditStatusRateLimit,\n\t\tRateLimit: perSecondLimit,\n\t}\n\treturn c.set(status, wm)\n}", "func (conn *Conn) rateLimit(chars int) time.Duration {\n\t// Hybrid's algorithm allows for 2 seconds per line and an additional\n\t// 1/120 of a second per character on that line.\n\tlinetime := 2*time.Second + time.Duration(chars)*time.Second/120\n\telapsed := time.Now().Sub(conn.lastsent)\n\tif conn.badness += linetime - elapsed; conn.badness < 0 {\n\t\t// negative badness times are badness...\n\t\tconn.badness = 0\n\t}\n\tconn.lastsent = time.Now()\n\t// If we've sent more than 10 second's worth of lines according to the\n\t// calculation above, then we're at risk of \"Excess Flood\".\n\tif conn.badness > 10*time.Second {\n\t\treturn linetime\n\t}\n\treturn 0\n}", "func (conn *Conn) rateLimit(chars int) time.Duration {\n\t// Hybrid's algorithm allows for 2 seconds per line and an additional\n\t// 1/120 of a second per character on that line.\n\tlinetime := 2*time.Second + time.Duration(chars)*time.Second/120\n\telapsed := time.Now().Sub(conn.lastsent)\n\tif conn.badness += linetime - elapsed; conn.badness < 0 {\n\t\t// negative badness times are badness...\n\t\tconn.badness = 0\n\t}\n\tconn.lastsent = time.Now()\n\t// If we've sent more than 10 second's worth of lines according to the\n\t// calculation above, then we're at risk of \"Excess Flood\".\n\tif conn.badness > 10*time.Second {\n\t\treturn linetime\n\t}\n\treturn 0\n}", "func newLimiter() *limiter.Limiter {\n\n\tlmt := tollbooth.NewLimiter(2, &limiter.ExpirableOptions{DefaultExpirationTTL: time.Hour})\n\n\tlmt.SetIPLookups([]string{\"X-Forwarded-For\", \"RemoteAddr\", \"X-Real-IP\"})\n\tlmt.SetOnLimitReached(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"request limit reached\")\n\t})\n\n\treturn lmt\n\n}", "func DefaultRetryPolicy(req *http.Request, res *http.Response, err error) bool {\n\tretry := false\n\n\t// retry if there is a temporary network error.\n\tif neterr, ok := err.(net.Error); ok {\n\t\tif neterr.Temporary() {\n\t\t\tretry = true\n\t\t}\n\t}\n\n\t// retry if we get a 5xx series error.\n\tif res != nil {\n\t\tif res.StatusCode >= 500 && res.StatusCode < 600 {\n\t\t\tretry = true\n\t\t}\n\t}\n\n\treturn retry\n}", "func SendForbid(c *gin.Context, message string) {\n\tSendHTML(http.StatusForbidden, c, \"forbid\", gin.H{\n\t\t\"message\": message,\n\t})\n}", "func Test_Limiter_Sliding_Window_No_Skip_Choices(t *testing.T) {\n\tt.Parallel()\n\tapp := fiber.New()\n\n\tapp.Use(New(Config{\n\t\tMax: 2,\n\t\tExpiration: 2 * time.Second,\n\t\tSkipFailedRequests: false,\n\t\tSkipSuccessfulRequests: false,\n\t\tLimiterMiddleware: SlidingWindow{},\n\t}))\n\n\tapp.Get(\"/:status\", func(c *fiber.Ctx) error {\n\t\tif c.Params(\"status\") == \"fail\" {\n\t\t\treturn c.SendStatus(400)\n\t\t}\n\t\treturn c.SendStatus(200)\n\t})\n\n\tresp, err := app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 200, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 429, resp.StatusCode)\n\n\ttime.Sleep(4 * time.Second)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 200, resp.StatusCode)\n}", "func Test_Limiter_Fixed_Window_Custom_Storage_Skip_Successful_Requests(t *testing.T) {\n\tt.Parallel()\n\t// Test concurrency using a default store\n\n\tapp := fiber.New()\n\n\tapp.Use(New(Config{\n\t\tMax: 1,\n\t\tExpiration: 2 * time.Second,\n\t\tStorage: memory.New(),\n\t\tSkipSuccessfulRequests: true,\n\t\tLimiterMiddleware: FixedWindow{},\n\t}))\n\n\tapp.Get(\"/:status\", func(c *fiber.Ctx) error {\n\t\tif c.Params(\"status\") == \"fail\" {\n\t\t\treturn c.SendStatus(400)\n\t\t}\n\t\treturn c.SendStatus(200)\n\t})\n\n\tresp, err := app.Test(httptest.NewRequest(fiber.MethodGet, \"/success\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 200, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 429, resp.StatusCode)\n\n\ttime.Sleep(3 * time.Second)\n\n\tresp, err = app.Test(httptest.NewRequest(fiber.MethodGet, \"/fail\", nil))\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, 400, resp.StatusCode)\n}", "func (v *priorityClientPool) setLimitsNow(count int, totalCap uint64) {\n\tif v.priorityCount > count || v.totalConnectedCap > totalCap {\n\t\tfor id, c := range v.clients {\n\t\t\tif c.connected {\n\t\t\t\tv.logger.Event(fmt.Sprintf(\"priorityClientPool: setLimitsNow kicked out, %x\", id.Bytes()))\n\t\t\t\tc.connected = false\n\t\t\t\tv.totalConnectedCap -= c.cap\n\t\t\t\tv.logTotalPriConn.Update(float64(v.totalConnectedCap))\n\t\t\t\tv.priorityCount--\n\t\t\t\tv.clients[id] = c\n\t\t\t\tgo v.ps.Unregister(c.peer.id)\n\t\t\t\tif v.priorityCount <= count && v.totalConnectedCap <= totalCap {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tv.maxPeers = count\n\tv.totalCap = totalCap\n\tif v.child != nil {\n\t\tv.child.setLimits(v.maxPeers-v.priorityCount, v.totalCap-v.totalConnectedCap)\n\t}\n}" ]
[ "0.6464643", "0.6186411", "0.61332136", "0.61332136", "0.6096705", "0.6049228", "0.59636146", "0.59079874", "0.5905041", "0.5904702", "0.59023535", "0.58886683", "0.5838211", "0.5838211", "0.5836824", "0.58216697", "0.58089036", "0.57796854", "0.5758372", "0.5756072", "0.5754223", "0.5753521", "0.5738698", "0.57271916", "0.56936455", "0.56787074", "0.5677977", "0.56746095", "0.56256473", "0.5619944", "0.5619199", "0.5618044", "0.5614791", "0.56077963", "0.5605701", "0.5593109", "0.55898666", "0.55870956", "0.5586567", "0.5559718", "0.55458796", "0.552942", "0.5528856", "0.5523979", "0.5518698", "0.5509903", "0.5494492", "0.54748726", "0.5460302", "0.5449242", "0.5429217", "0.5424677", "0.5424163", "0.5419596", "0.53789383", "0.5378711", "0.5377253", "0.5370446", "0.5367589", "0.5366727", "0.53577876", "0.535296", "0.53514564", "0.5349014", "0.5342447", "0.5341016", "0.5334842", "0.5302813", "0.5291568", "0.5282698", "0.5281092", "0.52673", "0.5243641", "0.5226694", "0.5224277", "0.5223247", "0.52178454", "0.5213822", "0.52058583", "0.52040035", "0.5190939", "0.5187411", "0.5186247", "0.51833385", "0.5183209", "0.5179989", "0.51796746", "0.51783866", "0.5177567", "0.5163916", "0.51552796", "0.51538324", "0.514555", "0.5135887", "0.5135887", "0.5135341", "0.51274735", "0.5127283", "0.5127145", "0.51267374", "0.51135063" ]
0.0
-1
The duration in seconds to enforce rate limiting for.
func (o QuotaRateLimitOutput) Interval() pulumi.IntOutput { return o.ApplyT(func(v *QuotaRateLimit) pulumi.IntOutput { return v.Interval }).(pulumi.IntOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RateLimit(d time.Duration) Tick {\n\tvar last *time.Time\n\treturn func(children []Node) (Status, error) {\n\t\tnow := time.Now()\n\t\tif last != nil && now.Add(-d).Before(*last) {\n\t\t\treturn Failure, nil\n\t\t}\n\t\tlast = &now\n\t\treturn Success, nil\n\t}\n}", "func (b *ConstantBackoff) Duration() time.Duration {\n\tb.retry++\n\treturn time.Duration(b.Time) * b.TimeUnit\n}", "func (zr *ZRequest) Duration() time.Duration {\n\tif zr.endTime.IsZero() {\n\t\treturn 0\n\t}\n\treturn zr.endTime.Sub(zr.startTime)\n}", "func (a API) GraceDuration() time.Duration {\n\tduration := a.readTimeout + a.processTimeout + a.writeTimeout\n\n\tif a.disableWebhook {\n\t\treturn duration\n\t}\n\n\tfor i := 0; i < a.webhookMaxRetry; i++ {\n\t\t// Yep... Golang does not allow int * time.Duration.\n\t\tduration += a.webhookRetryMaxWait\n\t}\n\n\treturn duration\n}", "func (tr *customTransport) Duration() time.Duration {\n\treturn tr.reqEnd.Sub(tr.reqStart)\n}", "func (b *backoff) Duration() time.Duration {\n\tbackoff := float64(b.n) + 1\n\td := math.Min(b.InitialDelay.Seconds()*backoff, b.MaxDelay.Seconds())\n\tb.n++\n\treturn time.Duration(d) * time.Second\n}", "func (r *Radio) Duration() int {\n\tr.Lock()\n\tdefer r.Unlock()\n\tif r.Dispatcher != nil {\n\t\treturn int(r.Dispatcher.Duration.Seconds())\n\t}\n\treturn 0\n}", "func (t *limiter) Delay() time.Duration {\n\tif t.limit > 0 {\n\n\t\tdelta := time.Now().Sub(t.start).Seconds()\n\t\trate := int64(float64(t.count) / delta)\n\n\t\t// Determine how far off from the max rate we are\n\t\tdelayAdj := float64((t.limit - rate)) / float64(t.limit)\n\n\t\t// Don't adjust by more than 1 second at a time\n\t\tdelayAdj = t.clamp(delayAdj, -1, 1)\n\n\t\tt.delay -= delayAdj\n\t\tif t.delay < 0 {\n\t\t\tt.delay = 0\n\t\t}\n\n\t\treturn time.Duration(t.delay) * time.Second\n\t}\n\treturn time.Duration(0)\n}", "func (rl RateLimit) WaitTime() time.Duration {\n\treturn (time.Second * time.Duration(rl.Period)) / time.Duration(rl.Limit)\n}", "func RefreshDuration(expiration time.Time) time.Duration {\n\tcalledAt := now()\n\tif expiration.Before(calledAt) {\n\t\treturn time.Duration(0)\n\t}\n\td := expiration.Sub(calledAt)\n\tif d > 4*time.Second {\n\t\td = time.Duration(float64(d) * .75)\n\t} else {\n\t\td -= time.Second\n\t\tif d < time.Duration(0) {\n\t\t\td = time.Duration(0) // Force immediate refresh.\n\t\t}\n\t}\n\n\treturn d\n}", "func (b *Bucket) DurabilityTimeout() time.Duration {\n\treturn b.duraTimeout\n}", "func (p mockProvider) ThrottleDuration() time.Duration {\n\treturn p.throttleDuration\n}", "func RateLimit(dur time.Duration) func(*Dispatcher) {\n\treturn func(d *Dispatcher) {\n\t\td.startTicker(dur)\n\t}\n}", "func (p *Provider) backoffDuration() time.Duration {\n\t// Use the default backoff\n\tbackoff := DefaultBackoff\n\n\t// Check for a server specified backoff\n\tp.backoffLock.Lock()\n\tif p.backoff != 0 {\n\t\tbackoff = p.backoff\n\t}\n\tif p.noRetry {\n\t\tbackoff = 0\n\t}\n\tp.backoffLock.Unlock()\n\n\treturn backoff\n}", "func (conn *Conn) rateLimit(chars int) time.Duration {\n\t// Hybrid's algorithm allows for 2 seconds per line and an additional\n\t// 1/120 of a second per character on that line.\n\tlinetime := 2*time.Second + time.Duration(chars)*time.Second/120\n\telapsed := time.Now().Sub(conn.lastsent)\n\tif conn.badness += linetime - elapsed; conn.badness < 0 {\n\t\t// negative badness times are badness...\n\t\tconn.badness = 0\n\t}\n\tconn.lastsent = time.Now()\n\t// If we've sent more than 10 second's worth of lines according to the\n\t// calculation above, then we're at risk of \"Excess Flood\".\n\tif conn.badness > 10*time.Second {\n\t\treturn linetime\n\t}\n\treturn 0\n}", "func (conn *Conn) rateLimit(chars int) time.Duration {\n\t// Hybrid's algorithm allows for 2 seconds per line and an additional\n\t// 1/120 of a second per character on that line.\n\tlinetime := 2*time.Second + time.Duration(chars)*time.Second/120\n\telapsed := time.Now().Sub(conn.lastsent)\n\tif conn.badness += linetime - elapsed; conn.badness < 0 {\n\t\t// negative badness times are badness...\n\t\tconn.badness = 0\n\t}\n\tconn.lastsent = time.Now()\n\t// If we've sent more than 10 second's worth of lines according to the\n\t// calculation above, then we're at risk of \"Excess Flood\".\n\tif conn.badness > 10*time.Second {\n\t\treturn linetime\n\t}\n\treturn 0\n}", "func (b *Backoff) duration(n uint64) (t time.Duration) {\n\t// Saturate pow\n\tpow := time.Duration(math.MaxInt64)\n\tif n < 63 {\n\t\tpow = 1 << n\n\t}\n\n\tt = b.interval * pow\n\tif t/pow != b.interval || t > b.maxDuration {\n\t\tt = b.maxDuration\n\t}\n\n\treturn\n}", "func (o QuotaLimitResponseOutput) Duration() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QuotaLimitResponse) string { return v.Duration }).(pulumi.StringOutput)\n}", "func (b *Backoff) Duration() time.Duration {\n\tbase := b.Min + b.delta\n\tpause := base\n\tif b.Jitter { // Add a number in the range [0, pause).\n\t\tpause += time.Duration(rand.Int63n(int64(pause)))\n\t}\n\n\tnextPause := time.Duration(float64(base) * b.Factor)\n\tif nextPause > b.Max || nextPause < b.Min { // Multiplication could overflow.\n\t\tnextPause = b.Max\n\t}\n\tb.delta = nextPause - b.Min\n\n\treturn pause\n}", "func (timeout *Timeout) Duration() time.Duration {\n\treturn timeout.d\n}", "func (b *Backoff) Duration() time.Duration {\n\tb.setup()\n\n\tb.decayN()\n\n\tt := b.duration(b.n)\n\n\tif b.n < math.MaxUint64 {\n\t\tb.n++\n\t}\n\n\tif !b.noJitter {\n\t\tprngMu.Lock()\n\t\tt = time.Duration(prng.Int63n(int64(t)))\n\t\tprngMu.Unlock()\n\t}\n\n\treturn t\n}", "func timeout(req *http.Request) time.Duration {\n\tto := req.Header.Get(_httpHeaderTimeout)\n\ttimeout, err := strconv.ParseInt(to, 10, 64)\n\tif err == nil && timeout > 20 {\n\t\ttimeout -= 20 // reduce 20ms every time.\n\t}\n\treturn time.Duration(timeout) * time.Millisecond\n}", "func (v *Validator) Duration() time.Duration {\n\treturn v.EndTime().Sub(v.StartTime())\n}", "func (r RecordTTL) Duration() time.Duration {\n\treturn (time.Second * time.Duration(int(r)))\n}", "func (br *BandwidthMeter) Duration() (duration time.Duration) {\n duration = br.lastRead.Sub(br.start)\n return\n}", "func (c *CRLConfig) TickerDuration() time.Duration {\n\tif !c.IsEnabled() {\n\t\treturn 0\n\t}\n\n\tif c.RenewPeriod != nil && c.RenewPeriod.Duration > 0 {\n\t\treturn c.RenewPeriod.Duration\n\t}\n\n\treturn (c.CacheDuration.Duration / 3) * 2\n}", "func (b *Bucket) DurabilityPollTimeout() time.Duration {\n\treturn b.duraPollTimeout\n}", "func (v RxDelay) Duration() time.Duration {\n\tswitch v {\n\tcase RX_DELAY_0, RX_DELAY_1:\n\t\treturn time.Second\n\tdefault:\n\t\treturn time.Duration(v) * time.Second\n\t}\n}", "func (m *RequestValidator) calculateMaxAccessDuration(req types.AccessRequest) (time.Duration, error) {\n\t// Check if the maxDuration time is set.\n\tmaxDurationTime := req.GetMaxDuration()\n\tif maxDurationTime.IsZero() {\n\t\treturn 0, nil\n\t}\n\n\tmaxDuration := maxDurationTime.Sub(req.GetCreationTime())\n\n\t// For dry run requests, the max_duration is set to 7 days.\n\t// This prevents the time drift that can occur as the value is set on the client side.\n\t// TODO(jakule): Replace with MaxAccessDuration that is a duration (5h, 4d etc), and not a point in time.\n\tif req.GetDryRun() {\n\t\tmaxDuration = maxAccessDuration\n\t} else if maxDuration < 0 {\n\t\treturn 0, trace.BadParameter(\"invalid maxDuration: must be greater than creation time\")\n\t}\n\n\tif maxDuration > maxAccessDuration {\n\t\treturn 0, trace.BadParameter(\"max_duration must be less or equal 7 days\")\n\t}\n\n\tminAdjDuration := maxDuration\n\t// Adjust the expiration time if the max_duration value is set on the request role.\n\tfor _, roleName := range req.GetRoles() {\n\t\tvar maxDurationForRole time.Duration\n\t\tfor _, tms := range m.MaxDurationMatchers {\n\t\t\tfor _, matcher := range tms.Matchers {\n\t\t\t\tif matcher.Match(roleName) {\n\t\t\t\t\tif tms.MaxDuration > maxDurationForRole {\n\t\t\t\t\t\tmaxDurationForRole = tms.MaxDuration\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif maxDurationForRole < minAdjDuration {\n\t\t\tminAdjDuration = maxDurationForRole\n\t\t}\n\t}\n\n\treturn minAdjDuration, nil\n}", "func throttleDelay(s *status.Status) time.Duration {\n\tfor _, detail := range s.Details() {\n\t\tif t, ok := detail.(*errdetails.RetryInfo); ok {\n\t\t\treturn t.RetryDelay.AsDuration()\n\t\t}\n\t}\n\treturn 0\n}", "func rateLimitHandler(limit int, within int) gin.HandlerFunc {\n\treturn throttle.Policy(&throttle.Quota{\n\t\tLimit: uint64(limit),\n\t\tWithin: time.Duration(within) * time.Second,\n\t})\n}", "func (l *RateLimiter) Limit(now time.Time, tenantID string) float64 {\n\treturn float64(l.getTenantLimiter(now, tenantID).Limit())\n}", "func (s *Server) Rate() rate.Limit {\n\tr := time.Duration(s.rate) * time.Second\n\treturn rate.Every(r)\n}", "func (s *NamespaceWebhook) TimeoutSeconds() int32 { return 2 }", "func (o QuotaLimitOutput) Duration() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v QuotaLimit) *string { return v.Duration }).(pulumi.StringPtrOutput)\n}", "func (s *prometheusruleWebhook) TimeoutSeconds() int32 {\n\treturn timeout\n}", "func (c *MockedHTTPContext) Duration() time.Duration {\n\tif c.MockedDuration != nil {\n\t\treturn c.MockedDuration()\n\t}\n\treturn 0\n}", "func (c *Client) Duration(stat string, duration time.Duration, rate float64) error {\n\treturn c.send(stat, rate, \"%d|ms\", millisecond(duration))\n}", "func (rl RateLimit) WaitTimeRemaining() time.Duration {\n\treturn (time.Second * time.Duration(rl.Period)) / time.Duration(rl.Remaining)\n}", "func (limiter *redisPeriodRateLimiterImpl) Request(ctx context.Context, key string, cost float64) (float64, time.Time, error) {\n\tredisKey := fmt.Sprintf(\"%s:period-rate-limit:%s\", limiter.prefix, key)\n\tscript := redis.NewScript(redisPeriodRateLimiterScript)\n\tr, err := script.Run(ctx, limiter.redis, []string{redisKey}, cost, limiter.quota, int64(limiter.resetPeriod.Milliseconds())).Result()\n\tif err != nil {\n\t\treturn 0, time.Time{}, fmt.Errorf(\"redis error: %v\", err)\n\t}\n\n\t// parse the response\n\tresultsObject, ok := r.([]interface{})\n\tif !ok {\n\t\treturn 0, time.Time{}, ErrRedisPeriodRateLimiterUnknown\n\t}\n\tquota, err := redis.NewCmdResult(resultsObject[0], nil).Float64()\n\tif err != nil {\n\t\treturn 0, time.Time{}, ErrRedisPeriodRateLimiterUnknown\n\t}\n\tpttl, err := redis.NewCmdResult(resultsObject[1], nil).Int64()\n\tif err != nil {\n\t\treturn quota, time.Time{}, ErrRedisPeriodRateLimiterUnknown\n\t}\n\tisEnough, err := redis.NewCmdResult(resultsObject[2], nil).Bool()\n\tif err != nil {\n\t\treturn 0, time.Now().Add(time.Duration(pttl) * time.Millisecond), ErrRedisPeriodRateLimiterUnknown\n\t}\n\n\tif !isEnough {\n\t\treturn quota, time.Now().Add(time.Duration(pttl) * time.Millisecond), ErrRateLimiterQuotaNotEnough\n\t}\n\treturn quota, time.Now().Add(time.Duration(pttl) * time.Millisecond), nil\n}", "func (d *Delay) TimeDuration() time.Duration {\n\treturn time.Duration(d.Duration*1000) * time.Millisecond\n}", "func (c *client) rateRequest() {\n\tc.rateMu.Lock()\n\tdefer c.rateMu.Unlock()\n\n\tif time.Now().After(c.nextReq) {\n\t\tc.nextReq = time.Now().Add(rateLimit)\n\t\treturn\n\t}\n\n\tcurrentReq := c.nextReq\n\tc.nextReq = currentReq.Add(rateLimit)\n\t<-time.After(currentReq.Sub(time.Now()))\n}", "func (c *Client) RateLimit() int {\n\treturn c.rateLimit\n}", "func getDrainTimeout(ctx thrift.Context) time.Duration {\n\tif ctx != nil {\n\t\tif deadline, ok := ctx.Deadline(); ok {\n\t\t\treturn deadline.Sub(time.Now())\n\t\t}\n\t}\n\treturn defaultDrainTimeout\n}", "func (r RateLimit) HitsPerDuration() float64 {\n\treturn r.R.HitsPerDuration(time.Since(r.T0))\n}", "func Duration(start time.Time) time.Duration {\n\treturn time.Since(start)\n}", "func (c Certificate) Duration() time.Duration {\n\treturn c.ExpiresAt.Sub(c.IssuedAt)\n}", "func (r *Resolver) Timeout() time.Duration {\n\treturn time.Duration(30) * time.Second\n}", "func (rs *Restake) Duration() uint32 { return rs.duration }", "func (ac *authConfig) AccessTokenDuration() time.Duration {\n\tvar key = \"auth.accessTokenDuration\"\n\tif ac.accessTokenDuration != nil {\n\t\treturn *ac.accessTokenDuration\n\t}\n\n\td, err := time.ParseDuration(viper.GetString(key))\n\tif err != nil {\n\t\tviper.Set(key, defaultAccessTokenDuration.String())\n\t\td = defaultAccessTokenDuration\n\t}\n\n\tac.accessTokenDuration = &d\n\treturn *ac.accessTokenDuration\n}", "func (fs *FlowStats) Duration() float64 {\n\tendTime := fs.ReadTime(EndTime)\n\tif endTime.Equal(time.Time{}) {\n\t\tendTime = time.Now()\n\t}\n\tduration := endTime.Sub(fs.ReadTime(StartTime))\n\treturn float64(duration) / float64(time.Second)\n}", "func properTimeDuration(state int) time.Duration {\n\tif state == LEADER {\n\t\treturn time.Millisecond * HEARTBEAT_INTERVAL\n\t}\n\treturn time.Millisecond * time.Duration(\n\t\tMIN_ELECTION_INTERVAL+rand.Intn(MAX_ELECTION_INTERVAL-MIN_ELECTION_INTERVAL))\n}", "func (o *Options) DelayDuration() time.Duration {\n\treturn time.Second * time.Duration(o.Delay)\n}", "func getDelay() time.Duration {\n\tDelaySeconds := 7200\n\n\tif utils.DebugMode() {\n\t\tDelaySeconds = 20\n\t}\n\n\treturn time.Duration(DelaySeconds)\n}", "func (del Delegation) LockDuration() (hexutil.Uint64, error) {\n\tlock, err := del.DelegationLock()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif lock == nil || 0 <= zeroInt.Cmp(lock.LockedAmount.ToInt()) {\n\t\treturn hexutil.Uint64(0), nil\n\t}\n\treturn lock.Duration, nil\n}", "func (a *Application) Limit() int64 {\n\tif a.InProduction {\n\t\treturn rateLimitProduction\n\t}\n\n\treturn rateLimitStaging\n}", "func (l *Limiter) Allow(now time.Time) (isAllowed bool, sleep time.Duration) {\n\telapsed := now.Sub(l.last)\n\n\t// \"rate * elapsed.Seconds()\" mean newly obtain tokens in the past elapsed time.\n\tl.tokens = l.tokens + l.rate*elapsed.Seconds()\n\tl.last = now\n\n\tif l.tokens > l.burst {\n\t\tl.tokens = l.burst\n\t}\n\n\t// Consume one token.\n\tl.tokens = l.tokens - 1\n\n\tif l.tokens < 0 {\n\t\t// \"-l.tokens / l.rate\" mean how many seconds can obtain these tokens.\n\t\treturn false, time.Duration(-l.tokens / l.rate * float64(time.Second))\n\t} else {\n\t\treturn true, 0\n\t}\n}", "func (o ApplicationSpecSyncPolicyRetryBackoffOutput) Duration() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecSyncPolicyRetryBackoff) *string { return v.Duration }).(pulumi.StringPtrOutput)\n}", "func (c GraphQLCost) RetryAfterSeconds() float64 {\n\tvar diff float64\n\n\tif c.ActualQueryCost != nil {\n\t\tdiff = c.ThrottleStatus.CurrentlyAvailable - float64(*c.ActualQueryCost)\n\t} else {\n\t\tdiff = c.ThrottleStatus.CurrentlyAvailable - float64(c.RequestedQueryCost)\n\t}\n\n\tif diff < 0 {\n\t\treturn -diff / c.ThrottleStatus.RestoreRate\n\t}\n\n\treturn 0\n}", "func (c *Config) FrequencyDur() time.Duration {\n\tconfigLock.RLock()\n\tdefer configLock.RUnlock()\n\n\tif c.Frequency == 0 {\n\t\treturn callhomeCycleDefault\n\t}\n\n\treturn c.Frequency\n}", "func getDuration(seconds int) time.Duration {\n\treturn time.Duration(seconds) * time.Second\n}", "func (c *Client) Duration() (float64, error) {\n\treturn c.GetFloatProperty(\"duration\")\n}", "func (o SecurityPolicyRuleRateLimitOptionsResponseOutput) BanDurationSec() pulumi.IntOutput {\n\treturn o.ApplyT(func(v SecurityPolicyRuleRateLimitOptionsResponse) int { return v.BanDurationSec }).(pulumi.IntOutput)\n}", "func (zap ChZap) Duration(provided *ChZap) time.Duration { //added *!\n\t//TODO write this method (1p)\n//\t\tmy_duration := zap.Time //- provided.Time\n\t//\tfmt.Println(my_duration)\n\tduration := zap.Time.Sub(provided.Time)\n\tif duration < 0 {\n\t\treturn provided.Time.Sub(zap.Time)\n\t}\n\treturn duration\n\n}", "func getTimeout(config *SidecarConfig) (time.Duration, error) {\n\tif config.Timeout == \"\" {\n\t\treturn defaultTimeout, nil\n\t}\n\n\tt, err := time.ParseDuration(config.Timeout)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn t, nil\n}", "func (t *task) Duration() time.Duration {\n\treturn t.duration\n}", "func (c config) HttpRequestTimeoutSec() time.Duration {\n\treturn time.Duration(c.HTTPRequestTimeoutSec) * time.Second\n}", "func (n *Globals) RateLimit(url string) {\n\tif rateLimiter, ok := n.rateLimiters[url]; ok {\n\t\trateLimiter.Wait()\n\t}\n}", "func GetDuration(key string) time.Duration {\n\tswitch key {\n\tcase keyMongoConnTimeout:\n\t\treturn time.Duration(base.m.Mongo.ConnectionTimeout)\n\tcase keyRedisIdelTimeout:\n\t\treturn time.Duration(base.m.Redis.IdelTimeout)\n\t}\n\treturn 0\n}", "func (r *Response) Duration() *Number {\n\topChain := r.chain.enter(\"Duration()\")\n\tdefer opChain.leave()\n\n\tif opChain.failed() {\n\t\treturn newNumber(opChain, 0)\n\t}\n\n\tif r.rtt == nil {\n\t\treturn newNumber(opChain, 0)\n\t}\n\n\treturn newNumber(opChain, float64(*r.rtt))\n}", "func (i *Limited) Next(ctx context.Context, _ error) time.Duration {\n\tswitch {\n\tcase i.Retries == 0:\n\t\treturn Stop\n\tcase i.Retries > 0:\n\t\ti.Retries--\n\t}\n\n\t// If there is a maximum total time, enforce it.\n\tif i.MaxTotal > 0 {\n\t\tnow := clock.Now(ctx)\n\t\tif i.startTime.IsZero() {\n\t\t\ti.startTime = now\n\t\t}\n\n\t\tvar elapsed time.Duration\n\t\tif now.After(i.startTime) {\n\t\t\telapsed = now.Sub(i.startTime)\n\t\t}\n\n\t\t// Remaining time is the difference between total allowed time and elapsed\n\t\t// time.\n\t\tremaining := i.MaxTotal - elapsed\n\t\tif remaining <= 0 {\n\t\t\t// No more time!\n\t\t\ti.Retries = 0\n\t\t\treturn Stop\n\t\t}\n\t}\n\n\treturn i.Delay\n}", "func (c *HTTPClient) ThrottleDeadline() time.Time {\n\tc.l.Lock()\n\tdefer c.l.Unlock()\n\n\treturn c.throttleDeadline\n}", "func taskDuration(t *swarming_api.SwarmingRpcsTaskRequestMetadata) (int64, error) {\n\tcompletedTime, err := swarming.Completed(t)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\tstartTime, err := swarming.Started(t)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\treturn int64(completedTime.Sub(startTime).Seconds() * float64(1000.0)), nil\n}", "func (o *Gojwt) GetNumHoursDuration()(time.Duration){\n return o.numHoursDuration\n}", "func (jl *JobLimiter) GetRequestRatePerSec() int {\n\treturn jl.currentJobCounter.getJobCountWithoutLock()\n}", "func now() time.Duration { return time.Since(startTime) }", "func (t *Timer) Duration(ctx context.Context, n time.Duration, ts ...Tags) {\n\ttags := getStatsTags(ctx, ts...)\n\twarnIfError(ctx, currentBackend.Distribution(ctx, t.Name, n.Seconds()*1000, tags, t.Rate.Rate()))\n}", "func (t *Timing) Duration(ctx context.Context, n time.Duration, ts ...Tags) {\n\ttags := getStatsTags(ctx, ts...)\n\twarnIfError(ctx, currentBackend.Timing(ctx, t.Name, n, tags, t.Rate.Rate()))\n}", "func (attendant *Attendant) Throttle() time.Duration {\n\treturn attendant.throttle\n}", "func (s *ServerStatistics) duration(count uint32) time.Duration {\n\treturn time.Second * time.Duration(math.Exp2(float64(count)))\n}", "func (r *RandomLib) Duration(min, max int) time.Duration {\n\treturn time.Duration(r.Int(min, max))\n}", "func samlRequestTimeout(schemeData map[string]string) int {\n\tp := schemeData[\"request_timeout\"]\n\ttimeout, _ := strconv.Atoi(p)\n\treturn timeout\n}", "func (this *cyclingActivityStruct) Duration() time.Duration {\n\tdur := this.duration\n\treturn dur\n}", "func rate(read int64, t time.Duration) float64 {\n\treturn float64(read) / (1024 * 1024) / t.Seconds()\n}", "func ShortRateTime() {\n\tfor {\n\t\tselect {\n\t\tdefault:\n\t\t\ttime.Sleep(2050 * time.Millisecond)\n\t\t\tCSRs = 0\n\t\tcase <-StopRateLimit:\n\t\t\tCSRs = 0\n\t\t\tRateLimitingActive = false\n\t\t\treturn\n\t\t}\n\t}\n}", "func (td *jsonDuration) Duration() time.Duration {\r\n\treturn time.Duration(*td)\r\n}", "func (s *SlidingWindow) Limit(ctx context.Context) (time.Duration, error) {\n\tnow := s.clock.Now()\n\tcurrWindow := now.Truncate(s.rate)\n\tprevWindow := currWindow.Add(-s.rate)\n\tttl := s.rate - now.Sub(currWindow)\n\tprev, curr, err := s.backend.Increment(ctx, prevWindow, currWindow, ttl+s.rate)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\ttotal := float64(prev*int64(ttl))/float64(s.rate) + float64(curr)\n\tif total-float64(s.capacity) >= s.epsilon {\n\t\tvar wait time.Duration\n\t\tif curr <= s.capacity-1 && prev > 0 {\n\t\t\twait = ttl - time.Duration(float64(s.capacity-1-curr)/float64(prev)*float64(s.rate))\n\t\t} else {\n\t\t\t// If prev == 0.\n\t\t\twait = ttl + time.Duration((1-float64(s.capacity-1)/float64(curr))*float64(s.rate))\n\t\t}\n\t\treturn wait, ErrLimitExhausted\n\t}\n\treturn 0, nil\n}", "func rateLimit(rw http.ResponseWriter, req *http.Request, app *App) bool {\n\tif app.Config.Rate_Limit.Enable {\n\t\tduration := time.Now().Unix() - app.Config.Rate_Limit.Seconds\n\t\tip, err := relevantIpBytes(req.RemoteAddr)\n\t\terrors := map[string]string{\"overall\": \"Rate limit reached.\"}\n\n\t\tif err != nil {\n\t\t\trenderErrors(rw, errors, 429)\n\t\t\treturn true\n\t\t}\n\n\t\tvar count int64\n\t\trow := app.Db.QueryRow(\"select count(*) from comments where ClientIp=? and Created>?\", ip, duration)\n\t\terr = row.Scan(&count)\n\n\t\tif err != nil || count >= app.Config.Rate_Limit.Max_Comments {\n\t\t\trenderErrors(rw, errors, 429)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (c *connAttrs) Timeout() time.Duration { c.mu.RLock(); defer c.mu.RUnlock(); return c._timeout }", "func (r Rest) Duration(measure time.Duration) time.Duration {\n\tif Duration(r) == None {\n\t\treturn 0\n\t}\n\t//the fraction of the measure the note takes\n\tfraq := 1. / math.Pow(2., float64(r))\n\n\treturn time.Duration(float64(measure) * fraq)\n}", "func RetryDuration(d time.Duration) Option {\n\treturn func(rc *RetryConfig) {\n\t\trc.retryDuration = d\n\t}\n}", "func Duration(v int) predicate.QueueItem {\n\treturn predicate.QueueItem(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldDuration), v))\n\t})\n}", "func Duration(d time.Duration, err error) time.Duration {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\treturn d\n}", "func remainingTime(t *testing.T) time.Duration {\n\tdeadline, hasDeadline := t.Deadline()\n\tif hasDeadline {\n\t\treturn time.Until(deadline) - time.Second // give us 1 second to clean up\n\t}\n\n\treturn DefaultResourceTimeout\n}", "func (o ApplicationStatusOperationStateOperationRetryBackoffOutput) Duration() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateOperationRetryBackoff) *string { return v.Duration }).(pulumi.StringPtrOutput)\n}", "func (d *DDL) Timeout() time.Duration {\n\tif d.Metadata.Timeout == 0 {\n\t\treturn time.Duration(10 * time.Second)\n\t}\n\n\treturn time.Duration(time.Second * time.Duration(d.Metadata.Timeout))\n}", "func (d *DDL) Timeout() time.Duration {\n\tif d.Metadata.Timeout == 0 {\n\t\treturn 10 * time.Second\n\t}\n\n\treturn time.Second * time.Duration(d.Metadata.Timeout)\n}", "func (o ApplicationSpecSyncPolicyRetryBackoffPtrOutput) Duration() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecSyncPolicyRetryBackoff) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Duration\n\t}).(pulumi.StringPtrOutput)\n}", "func (l *LimitRate) Allow() bool {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tif l.count >= l.rate - 1 {\n\t\tnow := time.Now()\n\t\tif now.Sub(l.begin) >= l.cycle {\n\t\t\tl.Reset(now)\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tl.count++\n\t\treturn true\n\t}\n}", "func (j *DSGitHub) CalculateTimeToReset(ctx *Ctx, rateLimit, rateLimitReset int) (seconds int) {\n\tseconds = rateLimitReset\n\treturn\n}", "func requestTimeoutOverride(ctx reqContext.Context, timeoutType fab.TimeoutType) time.Duration {\n\ttimeoutOverrides, ok := ctx.Value(ReqContextTimeoutOverrides).(map[fab.TimeoutType]time.Duration)\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn timeoutOverrides[timeoutType]\n}" ]
[ "0.63258153", "0.6316328", "0.62990874", "0.62531835", "0.6245212", "0.61934334", "0.6176212", "0.6137821", "0.612628", "0.6084323", "0.60666955", "0.6006405", "0.5984351", "0.5980985", "0.5972619", "0.5972619", "0.59549665", "0.5950877", "0.5944542", "0.5939932", "0.59288466", "0.5898464", "0.58316046", "0.58244985", "0.5822533", "0.5822391", "0.5820956", "0.58155525", "0.57812405", "0.57700264", "0.5746189", "0.5732963", "0.56947213", "0.56872696", "0.56845987", "0.56807786", "0.568055", "0.56737256", "0.5668248", "0.56561327", "0.56470805", "0.5636578", "0.5621346", "0.56139684", "0.56097", "0.5604905", "0.5592525", "0.5580263", "0.556766", "0.5565041", "0.55564094", "0.5546379", "0.55421805", "0.55296", "0.55291677", "0.55273575", "0.55130273", "0.5487242", "0.54857904", "0.5478748", "0.54775584", "0.54774326", "0.5476908", "0.54717344", "0.54528224", "0.5427021", "0.5419634", "0.54106694", "0.5395547", "0.5370315", "0.5365542", "0.5360762", "0.5350893", "0.53485924", "0.5347894", "0.53402877", "0.53394467", "0.53359145", "0.53352034", "0.53345305", "0.5333697", "0.53328425", "0.53321314", "0.5325692", "0.5323934", "0.5318213", "0.53144693", "0.5299209", "0.52966255", "0.528457", "0.5277982", "0.5275746", "0.5273713", "0.5268895", "0.52640456", "0.52635753", "0.52627885", "0.525842", "0.5254859", "0.5254383", "0.5250738" ]
0.0
-1
Name of the rate limit quota
func (o QuotaRateLimitOutput) Name() pulumi.StringOutput { return o.ApplyT(func(v *QuotaRateLimit) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (lim Limit) Name() string { return \"limit\" }", "func (h *RateLimit) GetName() string {\n\treturn \"rate_limit\"\n}", "func (rl *RateLimit) Name() string {\n\treturn \"ratelimit\"\n}", "func (o QuotaLimitOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v QuotaLimit) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (o QuotaLimitResponseOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QuotaLimitResponse) string { return v.Name }).(pulumi.StringOutput)\n}", "func (*MetricLimit) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_quota_quota_proto_rawDescGZIP(), []int{1}\n}", "func (f RateLimitingFilter) Name() string {\r\n\treturn FilterRateLimiting\r\n}", "func TenantResourceQuota(tenant string) string {\n\treturn tenant\n}", "func (rl RateLimit) String() string {\n\treturn fmt.Sprintf(\"%d per %s\", rl.Limit, rl.Interval)\n}", "func RateLimit(w http.ResponseWriter, r *http.Request) {\n\tvar tc *http.Client\n\n\tc := cloudpkgs.NewContext(w, r)\n\tctx := context.Background()\n\n\tt := c.Request.Header.Get(\"Authorization\")\n\tif t != \"\" {\n\t\tts := oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: t},\n\t\t)\n\t\ttc = oauth2.NewClient(ctx, ts)\n\t}\n\n\tclient := cloudapi.NewAPIClient(tc)\n\n\trate, _, err := client.Client.RateLimits(ctx)\n\tif err != nil {\n\t\tc.WriteJSON(http.StatusRequestTimeout, cloudpkgs.H{\"status\": http.StatusRequestTimeout})\n\t\treturn\n\t}\n\n\tc.WriteJSON(http.StatusOK, cloudpkgs.H{\"status\": http.StatusOK, \"rate\": rate})\n}", "func (o *LimitRate) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (m *Drive) GetQuota()(Quotaable) {\n return m.quota\n}", "func (h *handlerState) Quota(ctx context.Context, tracker attribute.Tracker, request *mixerpb.QuotaRequest, response *mixerpb.QuotaResponse) {\n\tresponse.RequestIndex = request.RequestIndex\n\tstatus := h.execute(ctx, tracker, request.AttributeUpdate, config.QuotaMethod)\n\n\tif status.Code == int32(code.Code_OK) {\n\t\tresponse.Amount = 1\n\t}\n}", "func (j *JuiceFSEngine) getQuota(v string) (int64, error) {\n\tq, err := resource.ParseQuantity(v)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"invalid quota %s: %v\", v, err)\n\t}\n\tqs := q.Value() / 1024 / 1024 / 1024\n\tif qs <= 0 {\n\t\treturn 0, fmt.Errorf(\"quota %s is too small, at least 1GiB for quota\", v)\n\t}\n\n\treturn qs, nil\n}", "func (a *Application) Limit() int64 {\n\tif a.InProduction {\n\t\treturn rateLimitProduction\n\t}\n\n\treturn rateLimitStaging\n}", "func (limit RateLimit) String() string {\n\treturn fmt.Sprintf(\"%d remaining of %d\", limit.Remaining, limit.Limit)\n}", "func NewQuotaRateLimit(ctx *pulumi.Context,\n\tname string, args *QuotaRateLimitArgs, opts ...pulumi.ResourceOption) (*QuotaRateLimit, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Rate == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Rate'\")\n\t}\n\tvar resource QuotaRateLimit\n\terr := ctx.RegisterResource(\"vault:index/quotaRateLimit:QuotaRateLimit\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (m *Drive) SetQuota(value Quotaable)() {\n m.quota = value\n}", "func (l *RateLimiter) Limit(now time.Time, tenantID string) float64 {\n\treturn float64(l.getTenantLimiter(now, tenantID).Limit())\n}", "func (m *Manager) StoreRateLimit(ctx context.Context, name string, conf ratelimit.Config) error {\n\treturn component.ErrInvalidType(\"rate_limit\", conf.Type)\n}", "func Quota(path string, size ...string) string {\n\tif len(size) > 0 && len(size[0]) > 0 {\n\t\tout, err := exec.Command(\"btrfs\", \"qgroup\", \"limit\", size[0]+\"G\", config.Agent.LxcPrefix+path).CombinedOutput()\n\t\tlog.Check(log.ErrorLevel, \"Limiting BTRFS subvolume \"+config.Agent.LxcPrefix+path+\" \"+string(out), err)\n\t\texec.Command(\"btrfs\", \"quota\", \"rescan\", \"-w\", config.Agent.LxcPrefix).Run()\n\t}\n\treturn Stat(path, \"quota\", false)\n}", "func (o QuotaRateLimitOutput) Rate() pulumi.Float64Output {\n\treturn o.ApplyT(func(v *QuotaRateLimit) pulumi.Float64Output { return v.Rate }).(pulumi.Float64Output)\n}", "func (o UsagePlanQuotaSettingsOutput) Limit() pulumi.IntOutput {\n\treturn o.ApplyT(func(v UsagePlanQuotaSettings) int { return v.Limit }).(pulumi.IntOutput)\n}", "func (*QuotaMetric) Descriptor() ([]byte, []int) {\n\treturn file_yandex_cloud_quota_quota_proto_rawDescGZIP(), []int{0}\n}", "func RateLimit(nic string, rate string) string {\n\tif rate != \"\" {\n\t\tburst, _ := strconv.Atoi(rate)\n\t\tburst = burst / 10\n\n\t\texec.Command(\"ovs-vsctl\", \"set\", \"interface\", nic,\n\t\t\t\"ingress_policing_rate=\"+rate).Run()\n\n\t\texec.Command(\"ovs-vsctl\", \"set\", \"interface\", nic,\n\t\t\t\"ingress_policing_burst=\"+strconv.Itoa(burst)).Run()\n\t}\n\n\tout, _ := exec.Command(\"ovs-vsctl\", \"list\", \"interface\", nic).Output()\n\n\tscanner := bufio.NewScanner(bytes.NewReader(out))\n\tfor scanner.Scan() {\n\t\tline := strings.Fields(scanner.Text())\n\t\tif len(line) > 0 {\n\t\t\tif line[0] == \"ingress_policing_rate:\" {\n\t\t\t\treturn line[1]\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}", "func calculateQuotaPerUnit(descriptor *microservicev1alpha2.SmartLimitDescriptor) (quota int, unit string, err error) {\n\tquota, err = strconv.Atoi(descriptor.Action.Quota)\n\tif err != nil {\n\t\treturn quota, unit, err\n\t}\n\tseconds := descriptor.Action.FillInterval.Seconds\n\tswitch seconds {\n\tcase 60 * 60 * 24:\n\t\tunit = \"DAY\"\n\tcase 60 * 60:\n\t\tunit = \"HOUR\"\n\tcase 60:\n\t\tunit = \"MINUTE\"\n\tcase 1:\n\t\tunit = \"SECOND\"\n\tdefault:\n\t\treturn quota, unit, fmt.Errorf(\"invalid time in global rate limit\")\n\t}\n\treturn quota, unit, nil\n}", "func newQuota() *catalogue.Quota {\n\treturn &catalogue.Quota{\n\t\tCores: 99999,\n\t\tFloatingIPs: 99999,\n\t\tInstances: 99999,\n\t\tKeyPairs: 99999,\n\t\tRAM: 99999,\n\t\tTenant: \"test-tenant\",\n\t}\n}", "func limitPrjQuota(prj, quota string) error {\n\tlimitQuotaCmd := fmt.Sprintf(\"xfs_quota -x -c 'limit -p bsoft=%s bhard=%s %s' %s\", quota, quota, prj, conf.WORKSPACE)\n\tlog.WithFields(log.Fields{\n\t\t\"project\": prj,\n\t\t\"quota\": quota,\n\t\t\"command\": limitQuotaCmd,\n\t}).Info(\"Limit project quota\")\n\n\tlimitQuotaExecCmd := exec.Command(\"sh\", \"-c\", limitQuotaCmd)\n\tif err := limitQuotaExecCmd.Run(); err != nil {\n\t\treturn errors.Wrap(err, \"limit project quota\")\n\t}\n\n\treturn nil\n}", "func (e ResourceQuotaValidationError) Reason() string { return e.reason }", "func (c *Client) RateLimit() RateLimit {\n\tif c.limit != nil {\n\t\treturn *c.limit\n\t}\n\taccount, err := c.Account.Get()\n\tif err != nil {\n\t\treturn RateLimit{}\n\t}\n\tc.limit = &RateLimit{}\n\tfor _, metric := range account.Metrics {\n\t\tif metric.PlanLevel > 0 {\n\t\t\tc.limit.Limit = metric.PlanLevel\n\t\t\tc.limit.Remaining = metric.Remaining\n\t\t}\n\t}\n\treturn *c.limit\n}", "func (pl *NoMaxResourceCount) Name() string {\n\treturn Name\n}", "func (e ResourceQuotaValidationError) Field() string { return e.field }", "func (e ListNamespaceQuotaReqValidationError) Reason() string { return e.reason }", "func (e GetNamespaceQuotaReqValidationError) Reason() string { return e.reason }", "func getResourceQuota(cpu, memory int) *v1.ResourceQuota {\n\t// Don's use \"MustParse\" it might panic at runtime , have some validation\n\thard := v1.ResourceList{\n\t\tv1.ResourceCPU: resource.MustParse(getCPUMilli(cpu)),\n\t\tv1.ResourceMemory: resource.MustParse(getMemoryMI(memory)),\n\t}\n\n\treturn &v1.ResourceQuota{\n\t\tSpec: v1.ResourceQuotaSpec{\n\t\t\tHard: hard,\n\t\t},\n\t}\n}", "func (s *Strava) GetRateLimits() (requestTime time.Time, limitShort, limitLong, usageShort, usageLong int) {\n\trateLimiting := strava.RateLimiting\n\treturn rateLimiting.RequestTime, rateLimiting.LimitShort, rateLimiting.LimitLong, rateLimiting.UsageShort, rateLimiting.UsageLong\n}", "func computeQuotaNames(quotaList []metav1.PartialObjectMetadata) sets.String {\n\tnames := sets.NewString()\n\n\tfor _, quota := range quotaList {\n\t\tnames.Insert(quota.Name)\n\t}\n\n\treturn names\n}", "func LimitName_Values() []string {\n\treturn []string{\n\t\tLimitNameProductsperaccount,\n\t\tLimitNameDatasetsperaccount,\n\t\tLimitNameDatasetsperproduct,\n\t\tLimitNameRevisionsperdataset,\n\t\tLimitNameAssetsperrevision,\n\t\tLimitNameAssetsperimportjobfromAmazonS3,\n\t\tLimitNameAssetperexportjobfromAmazonS3,\n\t\tLimitNameAssetsizeinGb,\n\t\tLimitNameConcurrentinprogressjobstoexportassetstoAmazonS3,\n\t\tLimitNameConcurrentinprogressjobstoexportassetstoasignedUrl,\n\t\tLimitNameConcurrentinprogressjobstoimportassetsfromAmazonS3,\n\t\tLimitNameConcurrentinprogressjobstoimportassetsfromasignedUrl,\n\t\tLimitNameConcurrentinprogressjobstoexportrevisionstoAmazonS3,\n\t\tLimitNameEventactionsperaccount,\n\t\tLimitNameAutoexporteventactionsperdataset,\n\t\tLimitNameAmazonRedshiftdatashareassetsperimportjobfromRedshift,\n\t\tLimitNameConcurrentinprogressjobstoimportassetsfromAmazonRedshiftdatashares,\n\t\tLimitNameRevisionsperAmazonRedshiftdatasharedataset,\n\t\tLimitNameAmazonRedshiftdatashareassetsperrevision,\n\t\tLimitNameConcurrentinprogressjobstoimportassetsfromanApigatewayApi,\n\t\tLimitNameAmazonApigatewayApiassetsperrevision,\n\t\tLimitNameRevisionsperAmazonApigatewayApidataset,\n\t\tLimitNameConcurrentinprogressjobstoimportassetsfromanAwslakeFormationtagpolicy,\n\t\tLimitNameAwslakeFormationdatapermissionassetsperrevision,\n\t\tLimitNameRevisionsperAwslakeFormationdatapermissiondataset,\n\t\tLimitNameRevisionsperAmazonS3dataaccessdataset,\n\t\tLimitNameAmazonS3dataaccessassetsperrevision,\n\t\tLimitNameConcurrentinprogressjobstocreateAmazonS3dataaccessassetsfromS3buckets,\n\t}\n}", "func (c *Client) RateLimit() int {\n\treturn c.rateLimit\n}", "func getDiskLimit(typeURL string) string {\n\tswitch getNameFromURL(\"diskTypes\", typeURL) {\n\tcase \"pd-balanced\", \"pd-ssd\":\n\t\treturn \"ssd_total_storage\"\n\tcase \"pd-standard\":\n\t\treturn \"disks_total_storage\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}", "func ProjectQuotaRequirements() []google.Quota {\n\treturn []google.Quota{\n\t\t{Name: \"NETWORKS\", Limit: 2.0},\n\t\t{Name: \"FIREWALLS\", Limit: 7.0},\n\t\t{Name: \"IMAGES\", Limit: 15.0},\n\t\t{Name: \"STATIC_ADDRESSES\", Limit: 1.0},\n\t\t{Name: \"ROUTES\", Limit: 20.0},\n\t\t{Name: \"FORWARDING_RULES\", Limit: 4.0},\n\t\t{Name: \"TARGET_POOLS\", Limit: 2.0},\n\t\t{Name: \"HEALTH_CHECKS\", Limit: 3.0},\n\t\t{Name: \"IN_USE_ADDRESSES\", Limit: 4.0},\n\t\t{Name: \"TARGET_HTTP_PROXIES\", Limit: 1.0},\n\t\t{Name: \"URL_MAPS\", Limit: 2.0},\n\t\t{Name: \"BACKEND_SERVICES\", Limit: 4.0},\n\t\t{Name: \"TARGET_HTTPS_PROXIES\", Limit: 1.0},\n\t\t{Name: \"SSL_CERTIFICATES\", Limit: 1.0},\n\t\t{Name: \"SUBNETWORKS\", Limit: 15.0},\n\t}\n}", "func (e CreateNamespaceQuotaReqValidationError) Reason() string { return e.reason }", "func DiskQuota(path string, size ...string) string {\n\tparent := id(path)\n\texec.Command(\"btrfs\", \"qgroup\", \"create\", \"1/\"+parent, config.Agent.LxcPrefix+path).Run()\n\texec.Command(\"btrfs\", \"qgroup\", \"assign\", \"0/\"+id(path+\"/opt\"), \"1/\"+parent, config.Agent.LxcPrefix+path).Run()\n\texec.Command(\"btrfs\", \"qgroup\", \"assign\", \"0/\"+id(path+\"/var\"), \"1/\"+parent, config.Agent.LxcPrefix+path).Run()\n\texec.Command(\"btrfs\", \"qgroup\", \"assign\", \"0/\"+id(path+\"/home\"), \"1/\"+parent, config.Agent.LxcPrefix+path).Run()\n\texec.Command(\"btrfs\", \"qgroup\", \"assign\", \"0/\"+id(path+\"/rootfs\"), \"1/\"+parent, config.Agent.LxcPrefix+path).Run()\n\n\tif len(size) > 0 && len(size[0]) > 0 {\n\t\tout, err := exec.Command(\"btrfs\", \"qgroup\", \"limit\", size[0]+\"G\", \"1/\"+parent, config.Agent.LxcPrefix+path).CombinedOutput()\n\t\tlog.Check(log.ErrorLevel, \"Limiting BTRFS group 1/\"+parent+\" \"+string(out), err)\n\t\texec.Command(\"btrfs\", \"quota\", \"rescan\", \"-w\", config.Agent.LxcPrefix).Run()\n\t}\n\treturn Stat(path, \"quota\", false)\n}", "func (q quotaID) String() string {\n\treturn fmt.Sprintf(\"%d\", q)\n}", "func GetQuotaRateLimit(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *QuotaRateLimitState, opts ...pulumi.ResourceOption) (*QuotaRateLimit, error) {\n\tvar resource QuotaRateLimit\n\terr := ctx.ReadResource(\"vault:index/quotaRateLimit:QuotaRateLimit\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s *grpcServer) Quota(stream mixerpb.Mixer_QuotaServer) error {\n\treturn s.dispatcher(stream, \"/istio.mixer.v1.Mixer/Quota\",\n\t\tfunc() (proto.Message, proto.Message, *mixerpb.Attributes, *mixerpb.Attributes, *rpc.Status) {\n\t\t\trequest := &mixerpb.QuotaRequest{}\n\t\t\tresponse := &mixerpb.QuotaResponse{}\n\t\t\tresponse.AttributeUpdate = &mixerpb.Attributes{}\n\t\t\treturn request, response, &request.AttributeUpdate, response.AttributeUpdate, &response.Result\n\t\t},\n\t\tfunc(ctx context.Context, requestBag *attribute.MutableBag, responseBag *attribute.MutableBag, request proto.Message, response proto.Message) {\n\t\t\ts.handlers.Quota(ctx, requestBag, responseBag, request.(*mixerpb.QuotaRequest), response.(*mixerpb.QuotaResponse))\n\t\t})\n}", "func (q *Control) GetQuota(targetPath string, quota *Quota) error {\n\tq.RLock()\n\tprojectID, ok := q.quotas[targetPath]\n\tq.RUnlock()\n\tif !ok {\n\t\treturn errors.Errorf(\"quota not found for path: %s\", targetPath)\n\t}\n\n\t//\n\t// get the quota limit for the container's project id\n\t//\n\tvar d C.fs_disk_quota_t\n\n\tcs := C.CString(q.backingFsBlockDev)\n\tdefer C.free(unsafe.Pointer(cs))\n\n\t_, _, errno := unix.Syscall6(unix.SYS_QUOTACTL, C.Q_XGETPQUOTA,\n\t\tuintptr(unsafe.Pointer(cs)), uintptr(C.__u32(projectID)),\n\t\tuintptr(unsafe.Pointer(&d)), 0, 0)\n\tif errno != 0 {\n\t\treturn errors.Wrapf(errno, \"Failed to get quota limit for projid %d on %s\",\n\t\t\tprojectID, q.backingFsBlockDev)\n\t}\n\tquota.Size = uint64(d.d_blk_hardlimit) * 512\n\n\treturn nil\n}", "func (e CreateNamespaceWithQuotaReqValidationError) Reason() string { return e.reason }", "func (o QuotaRateLimitOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *QuotaRateLimit) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (*TokenBucketRateLimitCF) Descriptor() ([]byte, []int) {\n\treturn file_pkg_kascfg_kascfg_proto_rawDescGZIP(), []int{16}\n}", "func NewRateLimit(client curator.CuratorFramework, username string,\n\ttotalAllowedQuota, baseQuota int64, lockTimeout time.Duration, refreshWindow time.Duration,\n\tenableOptimization bool, optimizationPctAsk float64, optimizationPctLeft float64) (*RateLimit, error) {\n\tvar err error\n\trl := &RateLimit{\n\t\tusername: username,\n\t\ttotalAllowedQuota: totalAllowedQuota,\n\t\tusableQuotaLeft: totalAllowedQuota,\n\t\tbaseQuota: baseQuota,\n\t\tlockTimeout: lockTimeout,\n\t\trefreshWindow: refreshWindow,\n\t\tclient: client,\n\t\tbaseQuotaPath: prefix + \"/\" + username + baseSuffix,\n\t\tusableQuotaPath: prefix + \"/\" + username + usableSuffix,\n\t\ttotalQuotaPath: prefix + \"/\" + username + totalSuffix,\n\t\trefreshQuotaPath: prefix + \"/\" + username + refreshSuffix,\n\t\toptimizationPctAsk: optimizationPctAsk,\n\t\toptimizationPctLeft: optimizationPctLeft,\n\t\tenableOptimization: enableOptimization,\n\t}\n\n\t// initialize the lock to be used and inject it wherever required.\n\trl.lock, err = recipe.NewInterProcessMutex(rl.client, lockPath+username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(prefix, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(prefix+\"/\"+rl.username, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.baseQuotaPath, []byte(strconv.FormatInt(rl.baseQuota, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.totalQuotaPath, []byte(strconv.FormatInt(rl.totalAllowedQuota, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.usableQuotaPath, []byte(strconv.FormatInt(rl.usableQuotaLeft, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.refreshQuotaPath, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.addWatch()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// concurrently look to refresh quota\n\tgo rl.refreshQuota()\n\t// mimic user requests being processed with random size\n\tgo rl.startRequests()\n\t// just in case there is skewness observed through loadbalancer and\n\t// quota gets concentrated on a single rate limit node\n\tgo rl.relinquish()\n\n\treturn rl, nil\n}", "func (e ListNamespaceQuotaRespValidationError) Reason() string { return e.reason }", "func (e ListNamespaceQuotaReqValidationError) Field() string { return e.field }", "func UpdateQuota(c context.Context, limit, usage float64, metric, project, region string) {\n\tquotaLimit.Set(c, limit, metric, project, region)\n\tquotaRemaining.Set(c, limit-usage, metric, project, region)\n\tquotaUsage.Set(c, usage, metric, project, region)\n}", "func RateLimit(r *http.Response) int {\n\treturn intResponseHeaderOrNegOne(r, \"X-RateLimit-Limit\")\n}", "func (e UpdateNamespaceQuotaReqValidationError) Reason() string { return e.reason }", "func (scheduler *SchedulerFair) UpdateQuota() {\r\n\tscheduler.queuesMu.Lock()\r\n\tdefer scheduler.queuesMu.Unlock()\r\n\tscheduler.queuesQuotaMu.Lock()\r\n\tdefer scheduler.queuesQuotaMu.Unlock()\r\n\t//log.Info(\"Updating queues quota~\")\r\n\r\n\t/* phase 1: DRF */\r\n\tusingGPU := 0\r\n\tusingCPU := 0\r\n\tusingMemory := 0\r\n\tallocatedGPU := 0\r\n\tallocatedCPU := 0\r\n\tallocatedMemory := 0\r\n\tscheduler.resourceAllocationsMu.Lock()\r\n\tfor _, quota := range scheduler.resourceAllocations {\r\n\t\tusingGPU += quota.NumberGPU\r\n\t\tusingCPU += quota.CPU\r\n\t\tusingMemory += quota.Memory\r\n\t}\r\n\tscheduler.resourceAllocationsMu.Unlock()\r\n\r\n\tfor _, quota := range scheduler.queuesQuota {\r\n\t\tallocatedGPU += quota.NumberGPU\r\n\t\tallocatedCPU += quota.CPU\r\n\t\tallocatedMemory += quota.Memory\r\n\t}\r\n\r\n\tpool := InstanceOfResourcePool()\r\n\r\n\tavailableGPU := pool.TotalGPU*1000 - usingGPU*1000 - allocatedGPU\r\n\tavailableCPU := pool.TotalCPU*1000 - usingCPU*1000 - allocatedCPU\r\n\t//availableMemory := pool.TotalMemory - usingMemory - allocatedMemory\r\n\t/* <0 means some nodes exited */\r\n\t//log.Info(availableGPU)\r\n\tif availableGPU <= 0 {\r\n\t\treturn\r\n\t}\r\n\r\n\tvar candidates []string\r\n\trequests := map[string]ResourceCount{}\r\n\tweights := 0\r\n\r\n\tfor queue, jobs := range scheduler.queues {\r\n\t\tif len(jobs) == 0 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tweights += InstanceOfGroupManager().groups[queue].Weight\r\n\t\trequest := ResourceCount{}\r\n\t\tfor i, job := range jobs {\r\n\t\t\tGPU := 0\r\n\t\t\tCPU := 0\r\n\t\t\tMemory := 0\r\n\t\t\tfor _, task := range job.Tasks {\r\n\t\t\t\tGPU += task.NumberGPU\r\n\t\t\t\tCPU += task.NumberCPU\r\n\t\t\t\tMemory += task.Memory\r\n\t\t\t}\r\n\t\t\trequest.NumberGPU += GPU\r\n\t\t\trequest.CPU += CPU\r\n\t\t\trequest.Memory += Memory\r\n\t\t\t/* increase priority at most 10 jobs, to avoid small jobs always goes first in a batch */\r\n\t\t\tif job.Priority == jobs[0].Priority && i < 10 {\r\n\t\t\t\tscheduler.queues[queue][i].BasePriority += 1.0\r\n\t\t\t}\r\n\t\t}\r\n\t\tsort.Sort(sort.Reverse(scheduler.queues[queue]))\r\n\r\n\t\t/* minimum is 1, to avoid divide by zero error following */\r\n\t\tif request.NumberGPU == 0 {\r\n\t\t\trequest.NumberGPU = 1\r\n\t\t}\r\n\t\tif quota, ok := scheduler.queuesQuota[queue]; ok && quota.NumberGPU >= request.NumberGPU*1000 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\trequests[queue] = request\r\n\t\tcandidates = append(candidates, queue)\r\n\t}\r\n\r\n\tif len(candidates) == 0 {\r\n\t\treturn\r\n\t}\r\n\tlog.Debug(\"Can allocate \", availableGPU)\r\n\tlog.Debug(\"Before \")\r\n\tfor queue, quota := range scheduler.queuesQuota {\r\n\t\tlog.Debug(\"Queue<->\", queue)\r\n\t\tlog.Debug(\"GPU:\", quota.NumberGPU)\r\n\t\tlog.Debug(\"CPU:\", quota.CPU)\r\n\t\tlog.Debug(\"Memory:\", quota.Memory)\r\n\t}\r\n\r\n\tper := availableGPU / weights\r\n\tfor _, queue := range candidates {\r\n\t\tif _, ok := scheduler.queuesQuota[queue]; !ok {\r\n\t\t\tscheduler.queuesQuota[queue] = &ResourceCount{}\r\n\t\t}\r\n\t\tweight := InstanceOfGroupManager().groups[queue].Weight\r\n\t\tquota := scheduler.queuesQuota[queue]\r\n\r\n\t\t/* if allocate is more than request, reduce weight */\r\n\t\tlog.Info(quota.NumberGPU, per, weight, requests[queue].NumberGPU)\r\n\t\tbase := per * weight\r\n\t\tif quota.NumberGPU+base > requests[queue].NumberGPU*1000 {\r\n\t\t\tbase = requests[queue].NumberGPU*1000 - quota.NumberGPU\r\n\t\t}\r\n\r\n\t\tquota.NumberGPU += base\r\n\t\tavailableGPU -= base\r\n\r\n\t\tquota.CPU += (requests[queue].CPU * base) / requests[queue].NumberGPU\r\n\t\tavailableCPU -= (requests[queue].CPU * base) / requests[queue].NumberGPU\r\n\t\tquota.Memory += ((requests[queue].Memory * base) / requests[queue].NumberGPU) / 1000\r\n\t}\r\n\t/* avoid resource leak, and reserve full */\r\n\tavailableGPU = availableGPU % 1000\r\n\tif availableGPU > 0 {\r\n\t\tfor _, queue := range candidates {\r\n\t\t\tquota := scheduler.queuesQuota[queue]\r\n\t\t\tquota.NumberGPU += availableGPU\r\n\t\t\tquota.CPU += (requests[queue].CPU * availableGPU) / requests[queue].NumberGPU\r\n\t\t\tquota.Memory += ((requests[queue].Memory * availableGPU) / requests[queue].NumberGPU) / 1000\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\tlog.Debug(\"After \")\r\n\tfor queue, quota := range scheduler.queuesQuota {\r\n\t\tlog.Debug(\"Queue<->\", queue)\r\n\t\tlog.Debug(\"GPU:\", quota.NumberGPU)\r\n\t\tlog.Debug(\"CPU:\", quota.CPU)\r\n\t\tlog.Debug(\"Memory:\", quota.Memory)\r\n\t}\r\n\r\n\t/* Phase 2: clear IOUs */\r\n\tfor queue, IOUs := range scheduler.IOUs {\r\n\t\t/* no IOU, skip */\r\n\t\tif t, ok := scheduler.IOUs[queue]; !ok || len(t) == 0 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\t/* nothing to pay */\r\n\t\tif tmp, ok := scheduler.queuesQuota[queue]; !ok || tmp.NumberGPU == 0 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tminIOU := 0\r\n\t\ttotalIOU := 0\r\n\t\tfor _, IOU := range IOUs {\r\n\t\t\tif IOU.NumberGPU > minIOU && IOU.NumberGPU != 0 {\r\n\t\t\t\tminIOU = IOU.NumberGPU\r\n\t\t\t\ttotalIOU += IOU.NumberGPU\r\n\t\t\t}\r\n\t\t}\r\n\t\tquota := scheduler.queuesQuota[queue]\r\n\t\tif quota.NumberGPU >= totalIOU {\r\n\t\t\t/* can clear all */\r\n\t\t\tminIOU = totalIOU\r\n\t\t}\r\n\t\tif quota.NumberGPU < minIOU*len(IOUs) {\r\n\t\t\tminIOU = quota.NumberGPU / len(IOUs)\r\n\t\t}\r\n\r\n\t\tfor q, IOU := range IOUs {\r\n\t\t\tif IOU.NumberGPU <= minIOU {\r\n\t\t\t\tquota.NumberGPU -= IOU.NumberGPU\r\n\t\t\t\tscheduler.queuesQuota[q].NumberGPU += IOU.NumberGPU\r\n\t\t\t\tIOU.NumberGPU = 0\r\n\t\t\t} else {\r\n\t\t\t\tquota.NumberGPU -= minIOU\r\n\t\t\t\tscheduler.queuesQuota[q].NumberGPU += minIOU\r\n\t\t\t\tIOU.NumberGPU -= minIOU\r\n\t\t\t}\r\n\t\t\tlog.Info(queue, \" pay IOU to \", q, \" now \", IOU.NumberGPU)\r\n\t\t\t/* clear */\r\n\t\t\tif IOU.NumberGPU == 0 {\r\n\t\t\t\tdelete(scheduler.IOUs[queue], q)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif minIOU == 0 {\r\n\t\t\tfor q, IOU := range IOUs {\r\n\t\t\t\tquota.NumberGPU -= 1\r\n\t\t\t\tscheduler.queuesQuota[q].NumberGPU += 1\r\n\t\t\t\tIOU.NumberGPU -= 1\r\n\t\t\t\tlog.Info(queue, \" pay IOU to \", q, \" now \", IOU.NumberGPU)\r\n\t\t\t\t/* clear */\r\n\t\t\t\tif IOU.NumberGPU == 0 {\r\n\t\t\t\t\tdelete(scheduler.IOUs[queue], q)\r\n\t\t\t\t}\r\n\t\t\t\tif quota.NumberGPU == 0 {\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func GetQuotaUpdateProvider() string {\n\treturn DefaultMgr().Get(backgroundCtx, common.QuotaUpdateProvider).GetString()\n}", "func (l *RateLimiter) Limit() rate.Limit {\n\treturn l.limiter.Limit()\n}", "func (o *NamedUlimitOpt) Name() string {\n\treturn o.name\n}", "func (e GetNamespaceQuotaRespValidationError) Reason() string { return e.reason }", "func (e CreateNamespaceQuotaRespValidationError) Reason() string { return e.reason }", "func (e CreateNamespaceQuotaReqValidationError) Field() string { return e.field }", "func (o UsageLimitOutput) LimitType() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *UsageLimit) pulumi.StringOutput { return v.LimitType }).(pulumi.StringOutput)\n}", "func (r *RateLimit) Limit(ctx context.Context, f request.EndpointLimit) error {\n\tswitch f {\n\t// TODO: Add futures and swap functionality\n\tcase huobiFuturesAuth:\n\t\treturn r.FuturesAuth.Wait(ctx)\n\tcase huobiFuturesUnAuth:\n\t\treturn r.FuturesUnauth.Wait(ctx)\n\tcase huobiFuturesTransfer:\n\t\treturn r.FuturesXfer.Wait(ctx)\n\tcase huobiSwapAuth:\n\t\treturn r.SwapAuth.Wait(ctx)\n\tcase huobiSwapUnauth:\n\t\treturn r.SwapUnauth.Wait(ctx)\n\tdefault:\n\t\t// Spot calls\n\t\treturn r.Spot.Wait(ctx)\n\t}\n}", "func ResourceQuotaForPriorityClassScope(name, namespace string, priorityClasses []string) *corev1.ResourceQuota {\n\treturn &corev1.ResourceQuota{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"v1\",\n\t\t\tKind: \"ResourceQuota\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tName: name,\n\t\t},\n\t\tSpec: corev1.ResourceQuotaSpec{\n\t\t\tScopeSelector: &corev1.ScopeSelector{\n\t\t\t\tMatchExpressions: []corev1.ScopedResourceSelectorRequirement{\n\t\t\t\t\t{\n\t\t\t\t\t\tScopeName: corev1.ResourceQuotaScopePriorityClass,\n\t\t\t\t\t\tOperator: corev1.ScopeSelectorOpIn,\n\t\t\t\t\t\tValues: priorityClasses,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (*APIQuota) Descriptor() ([]byte, []int) {\n\treturn file_Notify_proto_rawDescGZIP(), []int{5}\n}", "func (*ContractQuota) Descriptor() ([]byte, []int) {\n\treturn file_contract_proto_rawDescGZIP(), []int{2}\n}", "func reportQuota(c context.Context, payload proto.Message) error {\n\ttask, ok := payload.(*tasks.ReportQuota)\n\tswitch {\n\tcase !ok:\n\t\treturn errors.Reason(\"unexpected payload type %T\", payload).Err()\n\tcase task.GetId() == \"\":\n\t\treturn errors.Reason(\"ID is required\").Err()\n\t}\n\tp := &model.Project{\n\t\tID: task.Id,\n\t}\n\tif err := datastore.Get(c, p); err != nil {\n\t\treturn errors.Annotate(err, \"failed to fetch project\").Err()\n\t}\n\tmets := stringset.NewFromSlice(p.Config.Metric...)\n\tregs := stringset.NewFromSlice(p.Config.Region...)\n\trsp, err := getCompute(c).Regions.List(p.Config.Project).Context(c).Do()\n\tif err != nil {\n\t\tif gerr, ok := err.(*googleapi.Error); ok {\n\t\t\tlogErrors(c, task.Id, gerr)\n\t\t}\n\t\treturn errors.Annotate(err, \"failed to fetch quota\").Err()\n\t}\n\tfor _, r := range rsp.Items {\n\t\tif regs.Has(r.Name) {\n\t\t\tfor _, q := range r.Quotas {\n\t\t\t\tif mets.Has(q.Metric) {\n\t\t\t\t\tmetrics.UpdateQuota(c, q.Limit, q.Usage, q.Metric, p.Config.Project, r.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (o UsagePlanOutput) Quota() UsagePlanQuotaSettingsPtrOutput {\n\treturn o.ApplyT(func(v *UsagePlan) UsagePlanQuotaSettingsPtrOutput { return v.Quota }).(UsagePlanQuotaSettingsPtrOutput)\n}", "func (e ListNamespaceQuotaRespValidationError) Field() string { return e.field }", "func (*WatchLimitRequest) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_limit_service_proto_rawDescGZIP(), []int{5}\n}", "func (e GetNamespaceQuotaReqValidationError) Field() string { return e.field }", "func (acn *Account) Limit() int {\n\treturn acn.limit\n}", "func (n *Globals) RateLimit(url string) {\n\tif rateLimiter, ok := n.rateLimiters[url]; ok {\n\t\trateLimiter.Wait()\n\t}\n}", "func (o UsagePlanThrottleSettingsOutput) RateLimit() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v UsagePlanThrottleSettings) *float64 { return v.RateLimit }).(pulumi.Float64PtrOutput)\n}", "func (o QuotaLimitOutput) DisplayName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v QuotaLimit) *string { return v.DisplayName }).(pulumi.StringPtrOutput)\n}", "func (*GetQuotaRequest) Descriptor() ([]byte, []int) {\n\treturn file_contract_proto_rawDescGZIP(), []int{12}\n}", "func (e CreateNamespaceWithQuotaRespValidationError) Reason() string { return e.reason }", "func ratelimiter(args map[string]interface{}) *ratelimit.Ratelimiter {\n\trate, err := strconv.Atoi(args[\"--ratelimit-max-rate\"].(string))\n\tif err != nil {\n\t\tlog.Fatalf(\"error parsing --ratelimit-max-rate: %s\", err)\n\t}\n\n\tif rate <= 0 {\n\t\treturn nil\n\t}\n\n\tkeys, err := strconv.Atoi(args[\"--ratelimit-max-keys\"].(string))\n\tif err != nil {\n\t\tlog.Fatalf(\"error parsing --ratelimit-max-keys: %s\", err)\n\t}\n\n\treturn ratelimit.New(rate, keys)\n}", "func (o QuotaRateLimitOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *QuotaRateLimit) pulumi.StringPtrOutput { return v.Path }).(pulumi.StringPtrOutput)\n}", "func SetRateLimit() *RateLimit {\n\treturn &RateLimit{\n\t\tSpot: request.NewRateLimit(huobiSpotRateInterval, huobiSpotRequestRate),\n\t\tFuturesAuth: request.NewRateLimit(huobiFuturesRateInterval, huobiFuturesAuthRequestRate),\n\t\tFuturesUnauth: request.NewRateLimit(huobiFuturesRateInterval, huobiFuturesUnAuthRequestRate),\n\t\tSwapAuth: request.NewRateLimit(huobiSwapRateInterval, huobiSwapAuthRequestRate),\n\t\tSwapUnauth: request.NewRateLimit(huobiSwapRateInterval, huobiSwapUnauthRequestRate),\n\t\tFuturesXfer: request.NewRateLimit(huobiFuturesTransferRateInterval, huobiFuturesTransferReqRate),\n\t}\n}", "func (o AccountThrottleSettingOutput) RateLimit() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v AccountThrottleSetting) *float64 { return v.RateLimit }).(pulumi.Float64PtrOutput)\n}", "func (o OpenZfsVolumeOutput) StorageCapacityQuotaGib() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *OpenZfsVolume) pulumi.IntOutput { return v.StorageCapacityQuotaGib }).(pulumi.IntOutput)\n}", "func (*WatchLimitsRequest) Descriptor() ([]byte, []int) {\n\treturn edgelq_limits_proto_v1alpha2_limit_service_proto_rawDescGZIP(), []int{7}\n}", "func rateLimitHandler(limit int, within int) gin.HandlerFunc {\n\treturn throttle.Policy(&throttle.Quota{\n\t\tLimit: uint64(limit),\n\t\tWithin: time.Duration(within) * time.Second,\n\t})\n}", "func (q QuotaLimit) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]interface{})\n\tpopulate(objectMap, \"count\", q.Count)\n\tpopulate(objectMap, \"renewalPeriod\", q.RenewalPeriod)\n\tpopulate(objectMap, \"rules\", q.Rules)\n\treturn json.Marshal(objectMap)\n}", "func (q *Control) GetQuota(targetPath string, quota *Quota) error {\n\treturn ErrQuotaNotSupported\n}", "func (e DeleteNamespaceQuotaReqValidationError) Reason() string { return e.reason }", "func (e CreateNamespaceQuotaRespValidationError) Field() string { return e.field }", "func (e UpdateNamespaceQuotaReqValidationError) Field() string { return e.field }", "func (e UpdateNamespaceQuotaRespValidationError) Reason() string { return e.reason }", "func NewLimitRate(name string, options LimitRateOptions) *LimitRate {\n\tthis := LimitRate{}\n\tthis.Name = name\n\tthis.Options = options\n\treturn &this\n}", "func (b *ClusterBuilder) StorageQuota(value *ValueBuilder) *ClusterBuilder {\n\tb.storageQuota = value\n\tif value != nil {\n\t\tb.bitmap_ |= 1099511627776\n\t} else {\n\t\tb.bitmap_ &^= 1099511627776\n\t}\n\treturn b\n}", "func (q QuotaLimit) MarshalJSON() ([]byte, error) {\n\tobjectMap := make(map[string]any)\n\tpopulate(objectMap, \"count\", q.Count)\n\tpopulate(objectMap, \"renewalPeriod\", q.RenewalPeriod)\n\tpopulate(objectMap, \"rules\", q.Rules)\n\treturn json.Marshal(objectMap)\n}", "func TestRealisClient_Quota(t *testing.T) {\n\tvar resp *aurora.Response\n\tvar err error\n\n\tcpu := 3.5\n\tram := int64(20480)\n\tdisk := int64(10240)\n\n\tt.Run(\"Set\", func(t *testing.T) {\n\t\tresp, err = r.SetQuota(\"vagrant\", &cpu, &ram, &disk)\n\t\tassert.NoError(t, err)\n\t})\n\n\tt.Run(\"Get\", func(t *testing.T) {\n\t\t// Test GetQuota based on previously set values\n\t\tvar result *aurora.GetQuotaResult_\n\t\tresp, err = r.GetQuota(\"vagrant\")\n\t\tif resp.GetResult_() != nil {\n\t\t\tresult = resp.GetResult_().GetQuotaResult_\n\t\t}\n\t\tassert.NoError(t, err)\n\n\t\tfor _, res := range result.Quota.GetResources() {\n\t\t\tswitch true {\n\t\t\tcase res.DiskMb != nil:\n\t\t\t\tassert.Equal(t, disk, *res.DiskMb)\n\t\t\tcase res.NumCpus != nil:\n\t\t\t\tassert.Equal(t, cpu, *res.NumCpus)\n\t\t\tcase res.RamMb != nil:\n\t\t\t\tassert.Equal(t, ram, *res.RamMb)\n\t\t\t}\n\t\t}\n\t})\n}", "func UlimitName_Values() []string {\n\treturn []string{\n\t\tUlimitNameCore,\n\t\tUlimitNameCpu,\n\t\tUlimitNameData,\n\t\tUlimitNameFsize,\n\t\tUlimitNameLocks,\n\t\tUlimitNameMemlock,\n\t\tUlimitNameMsgqueue,\n\t\tUlimitNameNice,\n\t\tUlimitNameNofile,\n\t\tUlimitNameNproc,\n\t\tUlimitNameRss,\n\t\tUlimitNameRtprio,\n\t\tUlimitNameRttime,\n\t\tUlimitNameSigpending,\n\t\tUlimitNameStack,\n\t}\n}", "func (*Quota) Descriptor() ([]byte, []int) {\n\treturn file_msgType_proto_rawDescGZIP(), []int{6}\n}", "func (o UsagePlanQuotaSettingsPtrOutput) Limit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *UsagePlanQuotaSettings) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Limit\n\t}).(pulumi.IntPtrOutput)\n}", "func (*UpdateQuotaRequest) Descriptor() ([]byte, []int) {\n\treturn file_contract_proto_rawDescGZIP(), []int{3}\n}" ]
[ "0.71486855", "0.71433467", "0.6957979", "0.6637102", "0.6455906", "0.62078303", "0.6179772", "0.61182237", "0.6091988", "0.6065175", "0.60613954", "0.5995879", "0.5939857", "0.59250367", "0.5830743", "0.582435", "0.5771794", "0.5765177", "0.57648367", "0.5748305", "0.57268643", "0.5660169", "0.56572676", "0.56557", "0.56489456", "0.5646381", "0.56444323", "0.5643373", "0.56414497", "0.5609908", "0.5588103", "0.556931", "0.5567645", "0.55461395", "0.55333495", "0.55322117", "0.55188113", "0.54970145", "0.54939634", "0.54861486", "0.54850984", "0.5483067", "0.5482532", "0.5477181", "0.5439161", "0.5433969", "0.5418885", "0.5399797", "0.5396285", "0.5387967", "0.5373173", "0.5364955", "0.5358046", "0.5338923", "0.5323728", "0.5320701", "0.5314641", "0.53145075", "0.5300717", "0.52997285", "0.52773094", "0.52706724", "0.5270014", "0.52670205", "0.5263787", "0.5263039", "0.5260064", "0.52463704", "0.52311045", "0.52297264", "0.52288866", "0.5226312", "0.52133965", "0.5210603", "0.52064836", "0.5196295", "0.5188686", "0.5173725", "0.51665133", "0.5158933", "0.51539874", "0.5149579", "0.51426435", "0.51425886", "0.51414657", "0.5137022", "0.5131959", "0.5131628", "0.5121366", "0.51207817", "0.51137865", "0.51050377", "0.5103368", "0.509987", "0.5093041", "0.50892127", "0.50775737", "0.5072824", "0.50727516", "0.5072503" ]
0.71177906
2
The namespace to provision the resource in. The value should not contain leading or trailing forward slashes. The `namespace` is always relative to the provider's configured namespace. Available only for Vault Enterprise.
func (o QuotaRateLimitOutput) Namespace() pulumi.StringPtrOutput { return o.ApplyT(func(v *QuotaRateLimit) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o MachineInstanceSpecResourceRefOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MachineInstanceSpecResourceRef) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o SecretBackendV2Output) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SecretBackendV2) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func Namespace(ctx context.Context) string {\n\tv := ctx.Value(ContextKey(\"namespace\"))\n\tif v == nil {\n\t\treturn \"\"\n\t} else {\n\t\treturn v.(string)\n\t}\n}", "func (o ParamRefPatchOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ParamRefPatch) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o MrScalarTaskScalingUpPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingUpPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o ApplicationSpecRolloutplanCanarymetricTemplaterefOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecRolloutplanCanarymetricTemplateref) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o MrScalarCoreScalingUpPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarCoreScalingUpPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o SecretBackendRoleOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SecretBackendRole) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o SecretBackendRoleOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SecretBackendRole) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o ParamRefPatchPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ParamRefPatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (o AuthBackendRoleOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AuthBackendRole) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o MrScalarTaskScalingDownPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingDownPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o MrScalarCoreScalingDownPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarCoreScalingDownPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o KubernetesClusterSpecResourceRefOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterSpecResourceRef) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o ApplicationSpecRolloutplanCanarymetricTemplaterefPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecRolloutplanCanarymetricTemplateref) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (o MachineInstanceSpecResourceRefPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MachineInstanceSpecResourceRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (r *AuthorizationRequest) Namespace() string {\n\tif !r.IsResourceRequest() {\n\t\treturn \"__MAGIC__NOMATCH_*_KEY__\"\n\t}\n\treturn r.Spec.ResourceAttributes.Namespace\n}", "func (o ParamRefOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ParamRef) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o MfaPingidOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MfaPingid) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func Namespace() string {\n\tif ns := os.Getenv(NamespaceEnvKey); ns != \"\" {\n\t\treturn ns\n\t}\n\n\tpanic(fmt.Sprintf(`The environment variable %q is not set\n\nIf this is a process running on Kubernetes, then it should be using the downward\nAPI to initialize this variable via:\n\n env:\n - name: %s\n valueFrom:\n fieldRef:\n fieldPath: metadata.namespace\n\nIf this is a Go unit test consuming system.Namespace() then it should add the\nfollowing import:\n\nimport (\n\t_ \"knative.dev/pkg/system/testing\"\n)`, NamespaceEnvKey, NamespaceEnvKey))\n}", "func (o MrScalarTerminationPolicyStatementOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarTerminationPolicyStatement) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o ApplicationStatusWorkflowContextbackendOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusWorkflowContextbackend) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o ArgoCDSpecImportOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecImport) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o ApplicationStatusWorkflowContextbackendPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusWorkflowContextbackend) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func Namespace(config string) SecretOption {\n\treturn func(o *secret) {\n\t\to.namespace = config\n\t}\n}", "func Namespace() string {\n\treturn gfile.GetContents(kubernetesNamespaceFilePath)\n}", "func (o ApplicationSpecDestinationOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecDestination) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func namespace() string {\n\tif ns := os.Getenv(\"TILLER_NAMESPACE\"); ns != \"\" {\n\t\treturn ns\n\t}\n\n\t// Fall back to the namespace associated with the service account token, if available\n\tif data, err := ioutil.ReadFile(\"/var/run/secrets/kubernetes.io/serviceaccount/namespace\"); err == nil {\n\t\tif ns := strings.TrimSpace(string(data)); len(ns) > 0 {\n\t\t\treturn ns\n\t\t}\n\t}\n\n\treturn environment.DefaultTillerNamespace\n}", "func TenantNamespace(tenant string) string {\n\treturn fmt.Sprintf(\"cyclone--%s\", tenant)\n}", "func (o ElastigroupScalingTargetPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingTargetPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o ArgoCDSpecImportPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ArgoCDSpecImport) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ForwardingRuleServiceDirectoryRegistrationResponseOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ForwardingRuleServiceDirectoryRegistrationResponse) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (c *configuration) Namespace(clientSet ClientSet) *Namespace {\n\tif clientSet != nil {\n\t\treturn NewNamespace(clientSet)\n\t}\n\treturn nil\n\n}", "func (o FluxConfigurationOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FluxConfiguration) pulumi.StringOutput { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o ApplicationSpecRolloutplanRolloutbatchesCanarymetricTemplaterefOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecRolloutplanRolloutbatchesCanarymetricTemplateref) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o KubernetesClusterSpecResourceRefPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterSpecResourceRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ElastigroupScalingUpPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingUpPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (ls *LocationStore) Namespace() string {\n\treturn fmt.Sprintf(\"locations.%s\", ls.name)\n}", "func (o AppProjectSpecDestinationsOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AppProjectSpecDestinations) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o ApplicationStatusAppliedresourcesOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusAppliedresources) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o ApplicationSpecDestinationPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecDestination) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (k *k8sUtil) NS() (string, error) {\n\tif nil == k.volProfile {\n\t\treturn \"\", fmt.Errorf(\"Volume provisioner profile not initialized at '%s'\", k.Name())\n\t}\n\n\t// Fetch pvc from volume provisioner profile\n\tpvc, err := k.volProfile.PVC()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Get orchestrator provider profile from pvc\n\toPrfle, err := orchProfile.GetOrchProviderProfile(pvc)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Get the namespace which will be queried\n\tns, err := oPrfle.NS()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn ns, nil\n}", "func (r *ReplicaSet) Namespace() string {\n\treturn r.raw.Namespace\n}", "func Namespace(featureName FeatureName, componentName ComponentName, controlPlaneSpec *v1alpha2.IstioControlPlaneSpec) (string, error) {\n\tdefaultNamespaceI, found, err := tpath.GetFromStructPath(controlPlaneSpec, \"DefaultNamespace\")\n\tif !found {\n\t\treturn \"\", fmt.Errorf(\"can't find any setting for defaultNamespace for feature=%s, component=%s\", featureName, componentName)\n\t}\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in Namepsace for feature=%s, component=%s: %s\", featureName, componentName, err)\n\n\t}\n\tdefaultNamespace, ok := defaultNamespaceI.(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"defaultNamespace has bad type %T, expect string\", defaultNamespaceI)\n\t}\n\tif defaultNamespace == \"\" {\n\t\treturn \"\", fmt.Errorf(\"defaultNamespace must be set\")\n\t}\n\n\tfeatureNamespace := defaultNamespace\n\tfeatureNodeI, found, err := tpath.GetFromStructPath(controlPlaneSpec, string(featureName)+\".Components.Namespace\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in Namepsace GetFromStructPath featureNamespace for feature=%s, component=%s: %s\", featureName, componentName, err)\n\t}\n\tif found && featureNodeI != nil {\n\t\tfeatureNamespace, ok = featureNodeI.(string)\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"feature %s namespace has bad type %T, expect string\", featureName, featureNodeI)\n\t\t}\n\t\tif featureNamespace == \"\" {\n\t\t\tfeatureNamespace = defaultNamespace\n\t\t}\n\t}\n\n\tcomponentNodeI, found, err := tpath.GetFromStructPath(controlPlaneSpec, string(featureName)+\".Components.\"+string(componentName)+\".Namespace\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in Namepsace GetFromStructPath componentNamespace for feature=%s, component=%s: %s\", featureName, componentName, err)\n\t}\n\tif !found {\n\t\treturn featureNamespace, nil\n\t}\n\tif componentNodeI == nil {\n\t\treturn featureNamespace, nil\n\t}\n\tcomponentNamespace, ok := componentNodeI.(string)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"component %s enabled has bad type %T, expect string\", componentName, componentNodeI)\n\t}\n\tif componentNamespace == \"\" {\n\t\treturn featureNamespace, nil\n\t}\n\treturn componentNamespace, nil\n}", "func (o ElastigroupScalingDownPolicyOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingDownPolicy) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o ApplicationStatusServicesScopesOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusServicesScopes) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func Namespace(iops *v1alpha1.IstioOperatorSpec) string {\n\tif iops.Namespace != \"\" {\n\t\treturn iops.Namespace\n\t}\n\tif iops.Values == nil {\n\t\treturn \"\"\n\t}\n\tif iops.Values[globalKey] == nil {\n\t\treturn \"\"\n\t}\n\tv := iops.Values[globalKey].(map[string]interface{})\n\tn := v[istioNamespaceKey]\n\tif n == nil {\n\t\treturn \"\"\n\t}\n\treturn n.(string)\n}", "func (o MachineInstanceSpecClassRefOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v MachineInstanceSpecClassRef) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o AppV2Output) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AppV2) pulumi.StringOutput { return v.Namespace }).(pulumi.StringOutput)\n}", "func (o ApplicationSpecRolloutplanRolloutbatchesCanarymetricTemplaterefPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecRolloutplanRolloutbatchesCanarymetricTemplateref) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ForwardingRuleServiceDirectoryRegistrationOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ForwardingRuleServiceDirectoryRegistration) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (rs *ReplicaSet) Namespace() string {\n\treturn rs.replicaSet.Namespace\n}", "func (c *knDynamicClient) Namespace() string {\n\treturn c.namespace\n}", "func (c *ZtunnelComponent) Namespace() string {\n\treturn c.CommonComponentFields.Namespace\n}", "func getNamespace() (string, error) {\n\n\tns, found := os.LookupEnv(namespaceEnvVar)\n\tif !found {\n\t\terr := fmt.Errorf(\"%s must be set\", namespaceEnvVar)\n\t\treturn \"\", err\n\t}\n\treturn ns, nil\n}", "func (o GetReposRepoOutput) Namespace() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetReposRepo) string { return v.Namespace }).(pulumi.StringOutput)\n}", "func (c *Client) Namespace() string {\n\treturn \"testNamespace\"\n}", "func (opts CreateOptions) Namespace() string {\n\treturn opts.toConfig().Namespace\n}", "func (opts CreateOptions) Namespace() string {\n\treturn opts.toConfig().Namespace\n}", "func (o ApplicationStatusSyncComparedToDestinationOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusSyncComparedToDestination) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func getNamespace() string {\n\tns := os.Getenv(\"POD_NAMESPACE\")\n\tif ns == \"\" {\n\t\t// Useful especially for ci tests.\n\t\tns = metav1.NamespaceSystem\n\t}\n\treturn ns\n}", "func getNamespace() string {\n\tns := os.Getenv(\"POD_NAMESPACE\")\n\tif ns == \"\" {\n\t\t// Useful especially for ci tests.\n\t\tns = metav1.NamespaceSystem\n\t}\n\treturn ns\n}", "func (cc *ClientContext) Namespace() string {\n\treturn cc.namespace\n}", "func (o KubernetesClusterSpecClassRefOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterSpecClassRef) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (m *MachineScope) Namespace() string {\n\treturn m.AzureMachine.Namespace\n}", "func (o ApplicationStatusComponentsOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusComponents) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o ApplicationStatusSyncComparedToDestinationPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusSyncComparedToDestination) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (c *Client) Namespace() string {\n\tc.modifyLock.Lock()\n\tdefer c.modifyLock.Unlock()\n\tif c.headers == nil {\n\t\treturn \"\"\n\t}\n\treturn c.headers.Get(NamespaceHeaderName)\n}", "func (opts ListConfigurationsOptions) Namespace() string {\n\treturn opts.toConfig().Namespace\n}", "func (p protobuf) Namespace() string {\n\tif n, ok := protoNameToNamespace[p.TypeName]; ok {\n\t\treturn n\n\t}\n\treturn \"?\"\n}", "func (a *ALBIngress) Namespace() string {\n\treturn a.namespace\n}", "func (opts UnsetEnvOptions) Namespace() string {\n\treturn opts.toConfig().Namespace\n}", "func (k *Key) Namespace() string { return k.kc.Namespace }", "func (m Metadata) Namespace() string {\n\tif !m.HasNamespace() {\n\t\treturn \"\"\n\t}\n\treturn m[\"namespace\"].(string)\n}", "func (a *Application) Namespace() string {\n\treturn fmt.Sprintf(\"app_%d_%d\", a.OrgID, a.ID)\n}", "func Namespace(file *descriptor.FileDescriptorProto) string {\n\toptions := file.GetOptions()\n\n\t// When there is a namespace option defined we use it\n\tif options.PhpNamespace != nil {\n\t\treturn options.GetPhpNamespace()\n\t}\n\n\treturn Name(file.GetPackage())\n}", "func (o ParamRefPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ParamRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (c *Config) Namespace() string {\n\treturn c.namespace\n}", "func Namespace(namespace string) (*badgeStorage, error) {\n\tprefix := make([]byte, len(namespace)+1)\n\n\t_ = copy(prefix, namespace)\n\n\tprefix[len(namespace)] = byte('.')\n\n\treturn &badgeStorage{\n\t\tdb: db,\n\t\tns: prefix,\n\t}, nil\n}", "func (b *OperatorIAMRoleBuilder) Namespace(value string) *OperatorIAMRoleBuilder {\n\tb.namespace = value\n\tb.bitmap_ |= 2\n\treturn b\n}", "func (c *Controller) Namespace() string {\n\treturn c.namespace.Name\n}", "func (m *MockConfig) Namespace() string {\n\targs := m.Called()\n\treturn args.String(0)\n}", "func (c *Client) Namespace() *NamespaceCommand {\n\tcmd := &NamespaceCommand{}\n\tc.beginCommand(\"NAMESPACE\", cmd).end()\n\treturn cmd\n}", "func (o MachineInstanceSpecClassRefPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *MachineInstanceSpecClassRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *SparseSSHAuthorizationPolicy) GetNamespace() (out string) {\n\n\tif o.Namespace == nil {\n\t\treturn\n\t}\n\n\treturn *o.Namespace\n}", "func GetNamespace() string {\n\tns, found := os.LookupEnv(\"POD_NAMESPACE\")\n\tif found {\n\t\treturn ns\n\t}\n\tnsb, err := ioutil.ReadFile(\"/var/run/secrets/kubernetes.io/serviceaccount/namespace\")\n\tif err == nil && len(nsb) > 0 {\n\t\treturn string(nsb)\n\t}\n\treturn DefaultNamespace\n}", "func (o DataSetRowLevelPermissionDataSetPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *DataSetRowLevelPermissionDataSet) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func GetNamespace(node *yaml.RNode, path string) string {\n\treturn GetStringField(node, path, \"metadata\", \"namespace\")\n}", "func (opts ListOptions) Namespace() string {\n\treturn opts.toConfig().Namespace\n}", "func (pi *proxyItem) Namespace() string {\n\treturn pi.ns\n}", "func (c *Current) Namespace() string {\n\tswitch c.selectedRadio {\n\tcase FocusOnInvolved, FocusOnCurrentNamespace:\n\t\treturn curr.namespace\n\tcase FocusOnAllNamespace:\n\t\treturn \"\"\n\t}\n\treturn \"\"\n}", "func (o *Claims) GetNamespace() string {\n\n\treturn o.Namespace\n}", "func (o DataSetRowLevelPermissionDataSetOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DataSetRowLevelPermissionDataSet) *string { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func (o *SSHAuthorizationPolicy) GetNamespace() string {\n\n\treturn o.Namespace\n}", "func (o KubernetesClusterSpecClassRefPtrOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterSpecClassRef) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Namespace\n\t}).(pulumi.StringPtrOutput)\n}", "func (opts DeleteOptions) Namespace() string {\n\treturn opts.toConfig().Namespace\n}", "func (spec *KubectlStorageOSConfigSpec) GetNamespace() (namespace string) {\n\tnamespace = spec.Install.StorageOSOperatorNamespace\n\tif namespace == \"\" {\n\t\tnamespace = spec.Uninstall.StorageOSOperatorNamespace\n\t}\n\n\treturn\n}", "func (n *node) Namespace() string {\n\treturn n.namespace\n}", "func (this *KeyspaceTerm) Namespace() string {\n\tif this.path != nil {\n\t\treturn this.path.Namespace()\n\t}\n\treturn \"\"\n}", "func (f *EnvFlags) Namespace() string {\n\treturn f.namespace\n}" ]
[ "0.6630212", "0.65871453", "0.6586132", "0.6539589", "0.6499313", "0.6485903", "0.6474039", "0.6429713", "0.6429713", "0.6408647", "0.6399491", "0.63927054", "0.6357824", "0.63403904", "0.6333057", "0.631867", "0.6312653", "0.6308866", "0.62932575", "0.6259896", "0.6251117", "0.62353384", "0.623325", "0.6218285", "0.621351", "0.62104857", "0.61905146", "0.61755663", "0.61647946", "0.61612487", "0.61389357", "0.6135923", "0.6129462", "0.61180854", "0.6111392", "0.6090753", "0.6086341", "0.6084935", "0.6082117", "0.60778576", "0.6074798", "0.6071707", "0.6059664", "0.60595506", "0.605635", "0.6055831", "0.6040934", "0.60393226", "0.6036545", "0.60346544", "0.6023821", "0.6001419", "0.59991366", "0.59804857", "0.5980291", "0.59649533", "0.59447527", "0.5929515", "0.5929515", "0.5912027", "0.59007144", "0.59007144", "0.58929944", "0.58898365", "0.58856237", "0.5880911", "0.58717024", "0.5843477", "0.5835128", "0.5823998", "0.5819476", "0.58156496", "0.5797621", "0.57940173", "0.5788885", "0.57580054", "0.57162833", "0.57069254", "0.5697933", "0.5693876", "0.56897575", "0.5683555", "0.5674206", "0.5670481", "0.5666127", "0.56599647", "0.56581587", "0.5656275", "0.56513846", "0.56497437", "0.56382036", "0.5607081", "0.5600504", "0.5596621", "0.5596395", "0.5570129", "0.5569163", "0.55510616", "0.55507654", "0.5548254" ]
0.5900611
62
Path of the mount or namespace to apply the quota. A blank path configures a global rate limit quota. For example `namespace1/` adds a quota to a full namespace, `namespace1/auth/userpass` adds a `quota` to `userpass` in `namespace1`. Updating this field on an existing quota can have "moving" effects. For example, updating `auth/userpass` to `namespace1/auth/userpass` moves this quota from being a global mount quota to a namespace specific mount quota. Note, namespaces are supported in Enterprise only.
func (o QuotaRateLimitOutput) Path() pulumi.StringPtrOutput { return o.ApplyT(func(v *QuotaRateLimit) pulumi.StringPtrOutput { return v.Path }).(pulumi.StringPtrOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Drive) SetQuota(value Quotaable)() {\n m.quota = value\n}", "func Quota(path string, size ...string) string {\n\tif len(size) > 0 && len(size[0]) > 0 {\n\t\tout, err := exec.Command(\"btrfs\", \"qgroup\", \"limit\", size[0]+\"G\", config.Agent.LxcPrefix+path).CombinedOutput()\n\t\tlog.Check(log.ErrorLevel, \"Limiting BTRFS subvolume \"+config.Agent.LxcPrefix+path+\" \"+string(out), err)\n\t\texec.Command(\"btrfs\", \"quota\", \"rescan\", \"-w\", config.Agent.LxcPrefix).Run()\n\t}\n\treturn Stat(path, \"quota\", false)\n}", "func (q *Control) SetQuota(targetPath string, quota Quota) error {\n\tq.RLock()\n\tprojectID, ok := q.quotas[targetPath]\n\tq.RUnlock()\n\tif !ok {\n\t\tstate := getPquotaState()\n\t\tstate.Lock()\n\t\tprojectID = state.nextProjectID\n\n\t\t//\n\t\t// assign project id to new container directory\n\t\t//\n\t\terr := setProjectID(targetPath, projectID)\n\t\tif err != nil {\n\t\t\tstate.Unlock()\n\t\t\treturn err\n\t\t}\n\n\t\tstate.nextProjectID++\n\t\tstate.Unlock()\n\n\t\tq.Lock()\n\t\tq.quotas[targetPath] = projectID\n\t\tq.Unlock()\n\t}\n\n\t//\n\t// set the quota limit for the container's project id\n\t//\n\tlog.G(context.TODO()).Debugf(\"SetQuota(%s, %d): projectID=%d\", targetPath, quota.Size, projectID)\n\treturn setProjectQuota(q.backingFsBlockDev, projectID, quota)\n}", "func DiskQuota(path string, size ...string) string {\n\tparent := id(path)\n\texec.Command(\"btrfs\", \"qgroup\", \"create\", \"1/\"+parent, config.Agent.LxcPrefix+path).Run()\n\texec.Command(\"btrfs\", \"qgroup\", \"assign\", \"0/\"+id(path+\"/opt\"), \"1/\"+parent, config.Agent.LxcPrefix+path).Run()\n\texec.Command(\"btrfs\", \"qgroup\", \"assign\", \"0/\"+id(path+\"/var\"), \"1/\"+parent, config.Agent.LxcPrefix+path).Run()\n\texec.Command(\"btrfs\", \"qgroup\", \"assign\", \"0/\"+id(path+\"/home\"), \"1/\"+parent, config.Agent.LxcPrefix+path).Run()\n\texec.Command(\"btrfs\", \"qgroup\", \"assign\", \"0/\"+id(path+\"/rootfs\"), \"1/\"+parent, config.Agent.LxcPrefix+path).Run()\n\n\tif len(size) > 0 && len(size[0]) > 0 {\n\t\tout, err := exec.Command(\"btrfs\", \"qgroup\", \"limit\", size[0]+\"G\", \"1/\"+parent, config.Agent.LxcPrefix+path).CombinedOutput()\n\t\tlog.Check(log.ErrorLevel, \"Limiting BTRFS group 1/\"+parent+\" \"+string(out), err)\n\t\texec.Command(\"btrfs\", \"quota\", \"rescan\", \"-w\", config.Agent.LxcPrefix).Run()\n\t}\n\treturn Stat(path, \"quota\", false)\n}", "func (q *Control) GetQuota(targetPath string, quota *Quota) error {\n\tq.RLock()\n\tprojectID, ok := q.quotas[targetPath]\n\tq.RUnlock()\n\tif !ok {\n\t\treturn errors.Errorf(\"quota not found for path: %s\", targetPath)\n\t}\n\n\t//\n\t// get the quota limit for the container's project id\n\t//\n\tvar d C.fs_disk_quota_t\n\n\tcs := C.CString(q.backingFsBlockDev)\n\tdefer C.free(unsafe.Pointer(cs))\n\n\t_, _, errno := unix.Syscall6(unix.SYS_QUOTACTL, C.Q_XGETPQUOTA,\n\t\tuintptr(unsafe.Pointer(cs)), uintptr(C.__u32(projectID)),\n\t\tuintptr(unsafe.Pointer(&d)), 0, 0)\n\tif errno != 0 {\n\t\treturn errors.Wrapf(errno, \"Failed to get quota limit for projid %d on %s\",\n\t\t\tprojectID, q.backingFsBlockDev)\n\t}\n\tquota.Size = uint64(d.d_blk_hardlimit) * 512\n\n\treturn nil\n}", "func (q *Control) SetQuota(targetPath string, quota Quota) error {\n\treturn ErrQuotaNotSupported\n}", "func (p *projectQuota) SetQuota(targetPath string, pathFlag types.VolumeType, size *types.DiskQuotaSize,\n\tsharedInfo *types.SharedInfo) error {\n\tif size == nil || (size.Quota+size.Inodes == 0) {\n\t\treturn nil\n\t}\n\n\tbackingFsBlockDev, err := p.findAvailableBackingDev(targetPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar prjId quotaID\n\tvar isNewId bool\n\tif sharedInfo != nil {\n\t\tprjId, isNewId, err = p.findOrCreateSharedProjectId(targetPath, pathFlag.String(), sharedInfo.PodName)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"find or create project id err: %v\", err)\n\t\t}\n\t} else {\n\n\t\tprjId, isNewId, err = p.findOrCreateProjectId(targetPath, pathFlag.String(), !projIdNoCreate, persistToFile)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"find or create project id err: %v\", err)\n\t\t}\n\t}\n\n\tif isNewId {\n\t\tklog.V(2).Infof(\"set disk quota for path(%s) with size: %+v\", targetPath, size)\n\t\terr = setProjectQuota(backingFsBlockDev.device, prjId, size)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"set disk quota for path(%s) with size(%+v) failed: %v\", targetPath, size, err)\n\t\t}\n\n\t} else {\n\t\tklog.V(4).Infof(\"disk quota for path(%s) has already set\", targetPath)\n\t}\n\n\treturn err\n}", "func (d *dir) setQuota(path string, volID int64, sizeBytes int64) error {\n\tif volID == volIDQuotaSkip {\n\t\t// Disabled on purpose, just ignore.\n\t\treturn nil\n\t}\n\n\tif volID == 0 {\n\t\treturn fmt.Errorf(\"Missing volume ID\")\n\t}\n\n\tok, err := quota.Supported(path)\n\tif err != nil || !ok {\n\t\tif sizeBytes > 0 {\n\t\t\t// Skipping quota as underlying filesystem doesn't suppport project quotas.\n\t\t\td.logger.Warn(\"The backing filesystem doesn't support quotas, skipping set quota\", logger.Ctx{\"path\": path, \"size\": sizeBytes, \"volID\": volID})\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tprojectID := d.quotaProjectID(volID)\n\tcurrentProjectID, err := quota.GetProject(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Remove current project if desired project ID is different.\n\tif currentProjectID != d.quotaProjectID(volID) {\n\t\terr = quota.DeleteProject(path, currentProjectID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Initialise the project.\n\terr = quota.SetProject(path, projectID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Set the project quota size.\n\treturn quota.SetProjectQuota(path, projectID, sizeBytes)\n}", "func (p *projectQuota) ClearQuota(targetPath string) error {\n\tbackingFsBlockDev, err := p.findAvailableBackingDev(targetPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// no need to create new project id\n\tprjId, _, err := p.findOrCreateProjectId(targetPath, \"\", projIdNoCreate, persistToFile)\n\tif err != nil {\n\t\tklog.Errorf(\"find project id err: %v\", err)\n\t\treturn err\n\t}\n\n\tsize := &types.DiskQuotaSize{\n\t\tQuota: 0,\n\t\tInodes: 0,\n\t}\n\terr = setProjectQuota(backingFsBlockDev.device, prjId, size)\n\tif err != nil {\n\t\t// just warning\n\t\tklog.Errorf(\"set zero quota failed for path(%s) with id(%d): %v\", targetPath, prjId, err)\n\t}\n\n\t// save\n\tprojName, ok := p.idNames[prjId]\n\tdelete(p.pathIds, targetPath)\n\tdelete(p.pathMapBackingDev, targetPath)\n\tdelete(p.idPaths, prjId)\n\tdelete(p.idNames, prjId)\n\tif ok {\n\t\tdelete(p.nameIds, projName)\n\t}\n\n\t// save to file\n\tif p.prjFile != nil {\n\t\tp.prjFile.UpdateProjects(p.idPaths)\n\t\tp.prjFile.UpdateProjIds(p.idNames)\n\t}\n\n\treturn nil\n}", "func (a *Client) SetQuota(params *SetQuotaParams) (*SetQuotaOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewSetQuotaParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"setQuota\",\n\t\tMethod: \"PATCH\",\n\t\tPathPattern: \"/api/v1/quotas\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &SetQuotaReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*SetQuotaOK), nil\n\n}", "func (h *handlerState) Quota(ctx context.Context, tracker attribute.Tracker, request *mixerpb.QuotaRequest, response *mixerpb.QuotaResponse) {\n\tresponse.RequestIndex = request.RequestIndex\n\tstatus := h.execute(ctx, tracker, request.AttributeUpdate, config.QuotaMethod)\n\n\tif status.Code == int32(code.Code_OK) {\n\t\tresponse.Amount = 1\n\t}\n}", "func (m *Drive) GetQuota()(Quotaable) {\n return m.quota\n}", "func (o QuotaRateLimitOutput) Namespace() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *QuotaRateLimit) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)\n}", "func TenantResourceQuota(tenant string) string {\n\treturn tenant\n}", "func (p *projectQuota) GetAllQuotaPath() map[types.VolumeType]sets.String {\n\tpaths := make(map[types.VolumeType]sets.String)\n\n\tfor id, pathGroup := range p.idPaths {\n\t\tfor _, path := range pathGroup {\n\t\t\tidName := p.idNames[id]\n\t\t\tranges := strings.Split(idName, idNameSeprator)\n\t\t\tpathFlag := types.VolumeType(ranges[0])\n\t\t\tif _, ok := paths[pathFlag]; ok {\n\t\t\t\tpaths[pathFlag].Insert(path)\n\t\t\t} else {\n\t\t\t\tpaths[pathFlag] = sets.NewString(path)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn paths\n}", "func (b *ClusterBuilder) StorageQuota(value *ValueBuilder) *ClusterBuilder {\n\tb.storageQuota = value\n\tif value != nil {\n\t\tb.bitmap_ |= 1099511627776\n\t} else {\n\t\tb.bitmap_ &^= 1099511627776\n\t}\n\treturn b\n}", "func UpdateQuota(c context.Context, limit, usage float64, metric, project, region string) {\n\tquotaLimit.Set(c, limit, metric, project, region)\n\tquotaRemaining.Set(c, limit-usage, metric, project, region)\n\tquotaUsage.Set(c, usage, metric, project, region)\n}", "func PathToMetric(p string) string {\n\t// XXX: What do we do with absolute paths that don't begin with Prefix?\n\tp = path.Clean(p)\n\tif strings.HasPrefix(p, Prefix) {\n\t\tp = p[len(Prefix):]\n\t}\n\tif strings.HasPrefix(p, \"/\") {\n\t\tp = p[1:]\n\t}\n\n\tp = strings.Replace(p, \".wsp\", \"\", 1)\n\treturn strings.Replace(p, \"/\", \".\", -1)\n}", "func (p *projectQuota) GetQuota(targetPath string) (*types.DiskQuotaSize, error) {\n\tbackingFsBlockDev, err := p.findAvailableBackingDev(targetPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// no need to create new project id\n\tprjId, _, err := p.findOrCreateProjectId(targetPath, \"\", projIdNoCreate, !persistToFile)\n\tif err != nil {\n\t\tklog.Errorf(\"find project id err: %v\", err)\n\t\treturn nil, err\n\t}\n\n\treturn getProjectQuota(backingFsBlockDev.device, prjId)\n}", "func (c *SpaceQuotaClient) Update(ctx context.Context, guid string, r *resource.SpaceQuotaCreateOrUpdate) (*resource.SpaceQuota, error) {\n\tvar q resource.SpaceQuota\n\t_, err := c.client.patch(ctx, path.Format(\"/v3/space_quotas/%s\", guid), r, &q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &q, nil\n}", "func (o FioSpecVolumeVolumeSourceGlusterfsOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceGlusterfs) string { return v.Path }).(pulumi.StringOutput)\n}", "func (q *Control) GetQuota(targetPath string, quota *Quota) error {\n\treturn ErrQuotaNotSupported\n}", "func (d *diskQuota) handlePodDiskQuota(pod *v1.Pod) {\n\tpodVolume, ok := d.handedPods[pod.UID]\n\tif !ok {\n\t\tpodVolume = &PodVolumes{\n\t\t\tPod: pod,\n\t\t\tAppClass: appclass.GetAppClass(pod),\n\t\t\tVolumes: make(map[types.VolumeType]*VolumeInfo),\n\t\t}\n\t\t// store result\n\t\td.handedPods[pod.UID] = podVolume\n\t}\n\t// must update timestamp, no matter success or failed\n\tpodVolume.lastTime = time.Now()\n\n\t// get quota path from all volume types\n\tfor _, v := range d.volumeQuotaManagers {\n\t\tvinfo, ok := podVolume.Volumes[v.Name()]\n\t\tif !ok {\n\t\t\tvinfo = &VolumeInfo{\n\t\t\t\tgetPathsSuccess: false,\n\t\t\t\tsetQuotasSuccess: false,\n\t\t\t\tPaths: make(map[string]*PathInfoWrapper),\n\t\t\t}\n\t\t\tpodVolume.Volumes[v.Name()] = vinfo\n\t\t}\n\n\t\t// no need to set again if already set quota successfully\n\t\t// there is one case no covered, which pod has changed the quota size in annotation.\n\t\tif vinfo.setQuotasSuccess {\n\t\t\t// update quota size\n\t\t\td.getVolumeQuotaSize(vinfo)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !vinfo.getPathsSuccess {\n\t\t\terr := d.getPathsInfo(vinfo, v, pod)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"get %s paths info err for pod: %s-%s\", v.Name(), pod.Namespace, pod.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\t// set quota for each path\n\tfor _, v := range d.volumeQuotaManagers {\n\t\tvinfo := podVolume.Volumes[v.Name()]\n\t\t// do not set quota either get path failed or already set quota successfully\n\t\tif !vinfo.getPathsSuccess || vinfo.setQuotasSuccess {\n\t\t\tcontinue\n\t\t}\n\n\t\tvinfo.setQuotasSuccess = true\n\t\tfor _, p := range vinfo.Paths {\n\t\t\tif p.setQuotaSuccess {\n\t\t\t\t// update quota size\n\t\t\t\td.getPathQuotaSize(p)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\terr := d.setPathQuota(p, v)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"set pod(%s-%s) volume(%s) disk quota for path %s err: %v\",\n\t\t\t\t\tpod.Namespace, pod.Name, v.Name(), p.Path, err)\n\t\t\t\tvinfo.setQuotasSuccess = false\n\t\t\t} else {\n\t\t\t\tklog.V(4).Infof(\"set pod(%s-%s) volume(%s) disk quota for path %s success\",\n\t\t\t\t\tpod.Namespace, pod.Name, v.Name(), p.Path)\n\t\t\t}\n\t\t}\n\t}\n}", "func (j *JuiceFSEngine) genQuotaCmd(value *JuiceFS, mount datav1alpha1.Mount) error {\n\toptions := mount.Options\n\tfor k, v := range options {\n\t\tif k == \"quota\" {\n\t\t\tqs, err := j.getQuota(v)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"invalid quota %s\", v)\n\t\t\t}\n\t\t\tif value.Fuse.SubPath == \"\" {\n\t\t\t\treturn fmt.Errorf(\"subPath must be set when quota is enabled\")\n\t\t\t}\n\t\t\tif value.Edition == CommunityEdition {\n\t\t\t\t// ce\n\t\t\t\t// juicefs quota set ${metaurl} --path ${path} --capacity ${capacity}\n\t\t\t\tvalue.Configs.QuotaCmd = fmt.Sprintf(\"%s quota set %s --path %s --capacity %d\", common.JuiceCeCliPath, value.Source, value.Fuse.SubPath, qs)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// ee\n\t\t\t// juicefs quota set ${metaurl} --path ${path} --capacity ${capacity}\n\t\t\tcli := common.JuiceCliPath\n\t\t\tvalue.Configs.QuotaCmd = fmt.Sprintf(\"%s quota set %s --path %s --capacity %d\", cli, value.Source, value.Fuse.SubPath, qs)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}", "func (o IopingSpecVolumeVolumeSourceGlusterfsOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceGlusterfs) string { return v.Path }).(pulumi.StringOutput)\n}", "func (o UsagePlanOutput) Quota() UsagePlanQuotaSettingsPtrOutput {\n\treturn o.ApplyT(func(v *UsagePlan) UsagePlanQuotaSettingsPtrOutput { return v.Quota }).(UsagePlanQuotaSettingsPtrOutput)\n}", "func (o FioSpecVolumeVolumeSourceGlusterfsPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceGlusterfs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func (s gPUQuotaNamespaceLister) Get(name string) (*v1alpha1.GPUQuota, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1alpha1.Resource(\"gpuquota\"), name)\n\t}\n\treturn obj.(*v1alpha1.GPUQuota), nil\n}", "func (o IopingSpecVolumeVolumeSourceGlusterfsPtrOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceGlusterfs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Path\n\t}).(pulumi.StringPtrOutput)\n}", "func TestQuotaGetSet(t *testing.T) {\n\n\tvolumeName := \"test_quota_get_set\"\n\tquotaSize := int64(12345)\n\n\t// Setup the test\n\t_, err := client.CreateVolume(defaultCtx, volumeName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// make sure we clean up when we're done\n\tdefer client.DeleteVolume(defaultCtx, volumeName)\n\tdefer client.ClearQuota(defaultCtx, volumeName)\n\n\t// Make sure there is no quota yet\n\tquota, err := client.GetQuota(defaultCtx, volumeName)\n\tif quota != nil {\n\t\tpanic(fmt.Sprintf(\"Quota should be nil: %v\", quota))\n\t}\n\tif err == nil {\n\t\tpanic(fmt.Sprintf(\"GetQuota should return an error when there isn't a quota.\"))\n\t}\n\n\t// Set the quota\n\terr = client.SetQuotaSize(defaultCtx, volumeName, quotaSize)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Make sure the quota was set\n\tquota, err = client.GetQuota(defaultCtx, volumeName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif quota == nil {\n\t\tpanic(\"Quota should not be nil\")\n\t}\n\tif quota.Thresholds.Hard != quotaSize {\n\t\tpanic(fmt.Sprintf(\"Unexpected new quota. Expected: %d Actual: %d\", quotaSize, quota.Thresholds.Hard))\n\t}\n\n}", "func setDefaultPath(path string) (string) {\n\tif path != \"\" {\n\t\treturn path\n\t}\n\n\treturn \"/\"\n}", "func PathFromNamespace(ns string) string {\n\treturn strings.Replace(ns, \"\\\\\", \"/\", -1)\n}", "func (m *GetNamespaceQuotaReq) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif l := utf8.RuneCountInString(m.GetNamespace()); l < 2 || l > 100 {\n\t\treturn GetNamespaceQuotaReqValidationError{\n\t\t\tfield: \"Namespace\",\n\t\t\treason: \"value length must be between 2 and 100 runes, inclusive\",\n\t\t}\n\t}\n\n\tif utf8.RuneCountInString(m.GetFederationClusterID()) > 100 {\n\t\treturn GetNamespaceQuotaReqValidationError{\n\t\t\tfield: \"FederationClusterID\",\n\t\t\treason: \"value length must be at most 100 runes\",\n\t\t}\n\t}\n\n\tif utf8.RuneCountInString(m.GetClusterID()) > 100 {\n\t\treturn GetNamespaceQuotaReqValidationError{\n\t\t\tfield: \"ClusterID\",\n\t\t\treason: \"value length must be at most 100 runes\",\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *UpdateNamespaceQuotaReq) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif l := utf8.RuneCountInString(m.GetNamespace()); l < 2 || l > 100 {\n\t\treturn UpdateNamespaceQuotaReqValidationError{\n\t\t\tfield: \"Namespace\",\n\t\t\treason: \"value length must be between 2 and 100 runes, inclusive\",\n\t\t}\n\t}\n\n\tif utf8.RuneCountInString(m.GetFederationClusterID()) > 100 {\n\t\treturn UpdateNamespaceQuotaReqValidationError{\n\t\t\tfield: \"FederationClusterID\",\n\t\t\treason: \"value length must be at most 100 runes\",\n\t\t}\n\t}\n\n\tif utf8.RuneCountInString(m.GetClusterID()) > 100 {\n\t\treturn UpdateNamespaceQuotaReqValidationError{\n\t\t\tfield: \"ClusterID\",\n\t\t\treason: \"value length must be at most 100 runes\",\n\t\t}\n\t}\n\n\t// no validation rules for ResourceQuota\n\n\treturn nil\n}", "func (d *VolumeDriver) Path(r volume.Request) volume.Response {\n\treturn volume.Response{Mountpoint: getMountPoint(r.Name)}\n}", "func (a *Api) Path(r *http.Request) string {\n\tif a.Prefix != \"\" {\n\t\tif strings.HasSuffix(a.Prefix, \"/\") {\n\t\t\ta.Prefix = strings.TrimSuffix(a.Prefix, \"/\")\n\t\t}\n\n\t\treturn strings.TrimPrefix(r.URL.Path, a.Prefix)\n\t}\n\treturn r.URL.Path\n}", "func (s *grpcServer) Quota(stream mixerpb.Mixer_QuotaServer) error {\n\treturn s.dispatcher(stream, \"/istio.mixer.v1.Mixer/Quota\",\n\t\tfunc() (proto.Message, proto.Message, *mixerpb.Attributes, *mixerpb.Attributes, *rpc.Status) {\n\t\t\trequest := &mixerpb.QuotaRequest{}\n\t\t\tresponse := &mixerpb.QuotaResponse{}\n\t\t\tresponse.AttributeUpdate = &mixerpb.Attributes{}\n\t\t\treturn request, response, &request.AttributeUpdate, response.AttributeUpdate, &response.Result\n\t\t},\n\t\tfunc(ctx context.Context, requestBag *attribute.MutableBag, responseBag *attribute.MutableBag, request proto.Message, response proto.Message) {\n\t\t\ts.handlers.Quota(ctx, requestBag, responseBag, request.(*mixerpb.QuotaRequest), response.(*mixerpb.QuotaResponse))\n\t\t})\n}", "func (a *NamespacesApiService) SetBacklogQuota(ctx _context.Context, tenant string, namespace string, localVarOptionals *SetBacklogQuotaOpts) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/namespaces/{tenant}/{namespace}/backlogQuota\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"tenant\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", tenant)), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"namespace\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", namespace)), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.BacklogQuotaType.IsSet() {\n\t\tlocalVarQueryParams.Add(\"backlogQuotaType\", parameterToString(localVarOptionals.BacklogQuotaType.Value(), \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (*HttpDeviceAuth) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/device_auth/%s\", ref)\n}", "func (pool *PackagePool) FullPath(path string) string {\n\treturn filepath.Join(pool.rootPath, path)\n}", "func Path(p string) Option {\n\treturn func(cs *csrf) {\n\t\tcs.opts.Path = p\n\t}\n}", "func (s *organizationServiceServer) PathPrefix() string {\n\treturn baseServicePath(s.pathPrefix, \"buf.alpha.registry.v1alpha1\", \"OrganizationService\")\n}", "func (p *Pod) namespacePath(nsType specs.LinuxNamespaceType) string {\n\tfor _, ns := range p.namespaces {\n\t\tif ns.Type == nsType {\n\t\t\treturn p.bindNamespacePath(nsType)\n\t\t}\n\t}\n\treturn \"\"\n}", "func (*InterfacePppmodem) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/pppmodem/%s\", ref)\n}", "func SetShortPathRequestTenant(req *http.Request) (*http.Request, error) {\n\n\tctx := req.Context()\n\n\trequestor, exists := request.UserFrom(ctx)\n\tif !exists {\n\t\treturn nil, errors.New(\"The user info is missing.\")\n\t}\n\n\tuserTenant := requestor.GetTenant()\n\tif userTenant == metav1.TenantNone {\n\t\t// temporary workaround\n\t\t// tracking issue: https://github.com/futurewei-cloud/arktos/issues/102\n\t\tuserTenant = metav1.TenantSystem\n\t\t//When https://github.com/futurewei-cloud/arktos/issues/102 is done, remove the above line\n\t\t// and enable the following two lines.\n\t\t//responsewriters.InternalError(w, req, errors.New(fmt.Sprintf(\"The tenant in the user info of %s is empty. \", requestor.GetName())))\n\t\t//return\n\t}\n\n\trequestInfo, exists := request.RequestInfoFrom(ctx)\n\tif !exists {\n\t\treturn nil, errors.New(\"The request info is missing.\")\n\t}\n\n\t// for a reqeust from a regular user, if the tenant in the object is empty, use the tenant from user info\n\t// this is what we call \"short-path\", which allows users to use traditional Kubernets API in the multi-tenancy Arktos\n\tresourceTenant := requestInfo.Tenant\n\tif resourceTenant == metav1.TenantNone && userTenant != metav1.TenantSystem {\n\t\trequestInfo.Tenant = userTenant\n\t}\n\n\treq = req.WithContext(request.WithRequestInfo(ctx, requestInfo))\n\n\treturn req, nil\n}", "func (m *CreateNamespaceQuotaReq) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif l := utf8.RuneCountInString(m.GetNamespace()); l < 2 || l > 100 {\n\t\treturn CreateNamespaceQuotaReqValidationError{\n\t\t\tfield: \"Namespace\",\n\t\t\treason: \"value length must be between 2 and 100 runes, inclusive\",\n\t\t}\n\t}\n\n\tif utf8.RuneCountInString(m.GetFederationClusterID()) > 100 {\n\t\treturn CreateNamespaceQuotaReqValidationError{\n\t\t\tfield: \"FederationClusterID\",\n\t\t\treason: \"value length must be at most 100 runes\",\n\t\t}\n\t}\n\n\tif utf8.RuneCountInString(m.GetClusterID()) > 100 {\n\t\treturn CreateNamespaceQuotaReqValidationError{\n\t\t\tfield: \"ClusterID\",\n\t\t\treason: \"value length must be at most 100 runes\",\n\t\t}\n\t}\n\n\tif utf8.RuneCountInString(m.GetRegion()) > 100 {\n\t\treturn CreateNamespaceQuotaReqValidationError{\n\t\t\tfield: \"Region\",\n\t\t\treason: \"value length must be at most 100 runes\",\n\t\t}\n\t}\n\n\t// no validation rules for ResourceQuota\n\n\treturn nil\n}", "func (c *SpaceQuotaClient) Get(ctx context.Context, guid string) (*resource.SpaceQuota, error) {\n\tvar q resource.SpaceQuota\n\terr := c.client.get(ctx, path.Format(\"/v3/space_quotas/%s\", guid), &q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &q, nil\n}", "func (s *QuotaService) Set(ctx context.Context, item quota.QuotaItem, inUse int) error {\n\tq, err := s.Storage.Get(ctx, item.GetName())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif inUse < 0 {\n\t\treturn quota.ErrLessThanZero\n\t}\n\tif !q.IsUnlimited() && inUse > q.Limit {\n\t\treturn &quota.QuotaExceededError{\n\t\t\tRequested: uint(inUse),\n\t\t\tAvailable: uint(q.Limit),\n\t\t}\n\t}\n\treturn s.Storage.Set(ctx, item.GetName(), inUse)\n}", "func (a *BaseAdapter) ApplyPathPrefix(path string) string {\n\treturn fmt.Sprintf(\"%s%s\", *a.pathPrefix, strings.TrimPrefix(path, string(os.PathSeparator)))\n}", "func (c *tokenConfig) Path() string {\n\treturn c.Dir\n}", "func ExampleShareURL_SetQuota() {\n\t// Create a request pipeline using your Storage account's name and account key.\n\taccountName, accountKey := accountInfo()\n\tcredential, err := azfile.NewSharedKeyCredential(accountName, accountKey)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tp := azfile.NewPipeline(credential, azfile.PipelineOptions{})\n\n\t// From the Azure portal, get your Storage account file service URL endpoint.\n\tsURL, _ := url.Parse(fmt.Sprintf(\"https://%s.file.core.windows.net/newshareforquotademo\", accountName))\n\n\t// Create an ShareURL object that wraps the share URL and a request pipeline to making requests.\n\tshareURL := azfile.NewShareURL(*sURL, p)\n\n\tctx := context.Background() // This example uses a never-expiring context\n\n\t_, err = shareURL.Create(ctx, azfile.Metadata{}, 0)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Check current usage stats for the share.\n\t// Note that the ShareStats object is part of the protocol layer for the File service.\n\tif statistics, err := shareURL.GetStatistics(ctx); err == nil {\n\t\tshareUsageGB := statistics.ShareUsageBytes/1024/1024/1024\n\t\tfmt.Printf(\"Current share usage: %d GB\\n\", shareUsageGB)\n\n\t\tshareURL.SetQuota(ctx, 10+shareUsageGB)\n\n\t\tproperties, err := shareURL.GetProperties(ctx)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfmt.Printf(\"Updated share usage: %d GB\\n\", properties.Quota())\n\t}\n\n\t_, err = shareURL.Delete(ctx, azfile.DeleteSnapshotsOptionNone)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Output:\n\t// Current share usage: 0 GB\n\t// Updated share usage: 10 GB\n}", "func UpdateLabelPath(spaceID uuid.UUID, labelID uuid.UUID) string {\n\tparam0 := spaceID.String()\n\tparam1 := labelID.String()\n\n\treturn fmt.Sprintf(\"/api/spaces/%s/labels/%s\", param0, param1)\n}", "func (d *diskQuota) clearDiskQuota() {\n\texistingPaths := d.quotaManager.GetAllQuotaPath()\n\tklog.V(3).Infof(\"existing quota paths: %+v\", existingPaths)\n\n\td.handledLock.RLock()\n\tdefer d.handledLock.RUnlock()\n\tcurrentPaths := sets.String{}\n\tfor _, volumes := range d.handedPods {\n\t\tfor _, vinfo := range volumes.Volumes {\n\t\t\tfor _, p := range vinfo.Paths {\n\t\t\t\tcurrentPaths.Insert(p.Path)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor vType, paths := range existingPaths {\n\t\tswitch vType {\n\t\tcase types.VolumeTypeHostPath:\n\t\t\t// for host path, check if the path has already been deleted from cache, and deleting quota if not existed\n\t\t\tfor _, path := range paths.List() {\n\t\t\t\tif currentPaths.Has(path) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tklog.V(2).Infof(\"hot path(%s) has not found, starting cleaning disk quota\", path)\n\t\t\t\terr := d.quotaManager.ClearQuota(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"clear disk quota for path %s err: %v\", path, err)\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\t// for other paths, check if the path is still existing, and deleting quota if not\n\t\t\tfor _, path := range paths.List() {\n\t\t\t\t_, err := os.Stat(path)\n\t\t\t\tif err == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\t\t\tklog.Errorf(\"check path(%s) err: %v\", path, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tklog.V(2).Infof(\"path(%s) not found, starting cleaning disk quota\", path)\n\t\t\t\terr = d.quotaManager.ClearQuota(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"clear disk quota for path %s err: %v\", path, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (*CaCsr) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/csr/%s\", ref)\n}", "func (*CaCrl) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/crl/%s\", ref)\n}", "func (s *ownerServiceServer) PathPrefix() string {\n\treturn baseServicePath(s.pathPrefix, \"buf.alpha.registry.v1alpha1\", \"OwnerService\")\n}", "func (*BgpSystem) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/bgp/system/%s\", ref)\n}", "func UsePath(path string) FanoutRequestFunc {\n\treturn func(ctx context.Context, original, fanout *http.Request, _ []byte) (context.Context, error) {\n\t\tfanout.URL.Path = path\n\t\tfanout.URL.RawPath = \"\"\n\t\treturn ctx, nil\n\t}\n}", "func UpdateQuota(quota models.Quota) error {\n\tquota.UpdateTime = time.Now()\n\t_, err := GetOrmer().Update(&quota)\n\treturn err\n}", "func (*CaMetaCrl) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/meta_crl/%s\", ref)\n}", "func (*HttpSpSubcat) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/sp_subcat/%s\", ref)\n}", "func (this *KeyspaceTerm) Namespace() string {\n\tif this.path != nil {\n\t\treturn this.path.Namespace()\n\t}\n\treturn \"\"\n}", "func (d *MinioDriver) Path(r volume.Request) volume.Response {\n\td.m.RLock()\n\tdefer d.m.RUnlock()\n\n\tv, exists := d.volumes[r.Name]\n\tif !exists {\n\t\treturn volumeResp(\"\", \"\", nil, capability, newErrVolNotFound(r.Name).Error())\n\t}\n\treturn volumeResp(v.mountpoint, r.Name, nil, capability, \"\")\n}", "func (s *docServiceServer) PathPrefix() string {\n\treturn baseServicePath(s.pathPrefix, \"buf.alpha.registry.v1alpha1\", \"DocService\")\n}", "func (rule *Rule) Path(ns Ref) Ref {\n\treturn ns.Append(StringTerm(string(rule.Name)))\n}", "func (m *CreateNamespaceWithQuotaReq) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Name\n\n\t// no validation rules for FederationClusterID\n\n\t// no validation rules for ProjectID\n\n\t// no validation rules for BusinessID\n\n\t// no validation rules for Labels\n\n\t// no validation rules for ClusterID\n\n\t// no validation rules for Region\n\n\t// no validation rules for MaxQuota\n\n\t// no validation rules for ResourceQuota\n\n\treturn nil\n}", "func (q *quotaAdmission) Admit(a admission.Attributes) (err error) {\n\t// ignore all operations that correspond to sub-resource actions\n\tif a.GetSubresource() != \"\" {\n\t\treturn nil\n\t}\n\n\t// if we do not know how to evaluate use for this kind, just ignore\n\tevaluators := q.registry.Evaluators()\n\tevaluator, found := evaluators[a.GetKind()]\n\tif !found {\n\t\treturn nil\n\t}\n\n\t// for this kind, check if the operation could mutate any quota resources\n\t// if no resources tracked by quota are impacted, then just return\n\top := a.GetOperation()\n\toperationResources := evaluator.OperationResources(op)\n\tif len(operationResources) == 0 {\n\t\treturn nil\n\t}\n\n\t// determine if there are any quotas in this namespace\n\t// if there are no quotas, we don't need to do anything\n\tnamespace, name := a.GetNamespace(), a.GetName()\n\titems, err := q.indexer.Index(\"namespace\", &api.ResourceQuota{ObjectMeta: api.ObjectMeta{Namespace: namespace, Name: \"\"}})\n\tif err != nil {\n\t\treturn admission.NewForbidden(a, fmt.Errorf(\"Error resolving quota.\"))\n\t}\n\t// if there are no items held in our indexer, check our live-lookup LRU, if that misses, do the live lookup to prime it.\n\tif len(items) == 0 {\n\t\tlruItemObj, ok := q.liveLookupCache.Get(a.GetNamespace())\n\t\tif !ok || lruItemObj.(liveLookupEntry).expiry.Before(time.Now()) {\n\t\t\t// TODO: If there are multiple operations at the same time and cache has just expired,\n\t\t\t// this may cause multiple List operations being issued at the same time.\n\t\t\t// If there is already in-flight List() for a given namespace, we should wait until\n\t\t\t// it is finished and cache is updated instead of doing the same, also to avoid\n\t\t\t// throttling - see #22422 for details.\n\t\t\tliveList, err := q.client.Core().ResourceQuotas(namespace).List(api.ListOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn admission.NewForbidden(a, err)\n\t\t\t}\n\t\t\tnewEntry := liveLookupEntry{expiry: time.Now().Add(q.liveTTL)}\n\t\t\tfor i := range liveList.Items {\n\t\t\t\tnewEntry.items = append(newEntry.items, &liveList.Items[i])\n\t\t\t}\n\t\t\tq.liveLookupCache.Add(a.GetNamespace(), newEntry)\n\t\t\tlruItemObj = newEntry\n\t\t}\n\t\tlruEntry := lruItemObj.(liveLookupEntry)\n\t\tfor i := range lruEntry.items {\n\t\t\titems = append(items, lruEntry.items[i])\n\t\t}\n\t}\n\t// if there are still no items, we can return\n\tif len(items) == 0 {\n\t\treturn nil\n\t}\n\n\t// find the set of quotas that are pertinent to this request\n\t// reject if we match the quota, but usage is not calculated yet\n\t// reject if the input object does not satisfy quota constraints\n\t// if there are no pertinent quotas, we can just return\n\tinputObject := a.GetObject()\n\tresourceQuotas := []*api.ResourceQuota{}\n\tfor i := range items {\n\t\tresourceQuota := items[i].(*api.ResourceQuota)\n\t\tmatch := evaluator.Matches(resourceQuota, inputObject)\n\t\tif !match {\n\t\t\tcontinue\n\t\t}\n\t\thardResources := quota.ResourceNames(resourceQuota.Status.Hard)\n\t\tevaluatorResources := evaluator.MatchesResources()\n\t\trequiredResources := quota.Intersection(hardResources, evaluatorResources)\n\t\terr := evaluator.Constraints(requiredResources, inputObject)\n\t\tif err != nil {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"Failed quota: %s: %v\", resourceQuota.Name, err))\n\t\t}\n\t\tif !hasUsageStats(resourceQuota) {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"Status unknown for quota: %s\", resourceQuota.Name))\n\t\t}\n\t\tresourceQuotas = append(resourceQuotas, resourceQuota)\n\t}\n\tif len(resourceQuotas) == 0 {\n\t\treturn nil\n\t}\n\n\t// there is at least one quota that definitely matches our object\n\t// as a result, we need to measure the usage of this object for quota\n\t// on updates, we need to subtract the previous measured usage\n\t// if usage shows no change, just return since it has no impact on quota\n\tdeltaUsage := evaluator.Usage(inputObject)\n\tif admission.Update == op {\n\t\tprevItem, err := evaluator.Get(namespace, name)\n\t\tif err != nil {\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"Unable to get previous: %v\", err))\n\t\t}\n\t\tprevUsage := evaluator.Usage(prevItem)\n\t\tdeltaUsage = quota.Subtract(deltaUsage, prevUsage)\n\t}\n\tif quota.IsZero(deltaUsage) {\n\t\treturn nil\n\t}\n\n\t// TODO: Move to a bucketing work queue\n\t// If we guaranteed that we processed the request in order it was received to server, we would reduce quota conflicts.\n\t// Until we have the bucketing work queue, we jitter requests and retry on conflict.\n\tnumRetries := 10\n\tinterval := time.Duration(rand.Int63n(90)+int64(10)) * time.Millisecond\n\n\t// seed the retry loop with the initial set of quotas to process (should reduce each iteration)\n\tresourceQuotasToProcess := resourceQuotas\n\tfor retry := 1; retry <= numRetries; retry++ {\n\t\t// the list of quotas we will try again if there is a version conflict\n\t\ttryAgain := []*api.ResourceQuota{}\n\n\t\t// check that we pass all remaining quotas so we do not prematurely charge\n\t\t// for each quota, mask the usage to the set of resources tracked by the quota\n\t\t// if request + used > hard, return an error describing the failure\n\t\tupdatedUsage := map[string]api.ResourceList{}\n\t\tfor _, resourceQuota := range resourceQuotasToProcess {\n\t\t\thardResources := quota.ResourceNames(resourceQuota.Status.Hard)\n\t\t\trequestedUsage := quota.Mask(deltaUsage, hardResources)\n\t\t\tnewUsage := quota.Add(resourceQuota.Status.Used, requestedUsage)\n\t\t\tif allowed, exceeded := quota.LessThanOrEqual(newUsage, resourceQuota.Status.Hard); !allowed {\n\t\t\t\tfailedRequestedUsage := quota.Mask(requestedUsage, exceeded)\n\t\t\t\tfailedUsed := quota.Mask(resourceQuota.Status.Used, exceeded)\n\t\t\t\tfailedHard := quota.Mask(resourceQuota.Status.Hard, exceeded)\n\t\t\t\treturn admission.NewForbidden(a,\n\t\t\t\t\tfmt.Errorf(\"Exceeded quota: %s, requested: %s, used: %s, limited: %s\",\n\t\t\t\t\t\tresourceQuota.Name,\n\t\t\t\t\t\tprettyPrint(failedRequestedUsage),\n\t\t\t\t\t\tprettyPrint(failedUsed),\n\t\t\t\t\t\tprettyPrint(failedHard)))\n\t\t\t}\n\t\t\tupdatedUsage[resourceQuota.Name] = newUsage\n\t\t}\n\n\t\t// update the status for each quota with its new usage\n\t\t// if we get a conflict, get updated quota, and enqueue\n\t\tfor i, resourceQuota := range resourceQuotasToProcess {\n\t\t\tnewUsage := updatedUsage[resourceQuota.Name]\n\t\t\tquotaToUpdate := &api.ResourceQuota{\n\t\t\t\tObjectMeta: api.ObjectMeta{\n\t\t\t\t\tName: resourceQuota.Name,\n\t\t\t\t\tNamespace: resourceQuota.Namespace,\n\t\t\t\t\tResourceVersion: resourceQuota.ResourceVersion,\n\t\t\t\t},\n\t\t\t\tStatus: api.ResourceQuotaStatus{\n\t\t\t\t\tHard: quota.Add(api.ResourceList{}, resourceQuota.Status.Hard),\n\t\t\t\t\tUsed: newUsage,\n\t\t\t\t},\n\t\t\t}\n\t\t\t_, err = q.client.Core().ResourceQuotas(quotaToUpdate.Namespace).UpdateStatus(quotaToUpdate)\n\t\t\tif err != nil {\n\t\t\t\tif !errors.IsConflict(err) {\n\t\t\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"Unable to update quota status: %s %v\", resourceQuota.Name, err))\n\t\t\t\t}\n\t\t\t\t// if we get a conflict, we get the latest copy of the quota documents that were not yet modified so we retry all with latest state.\n\t\t\t\tfor fetchIndex := i; fetchIndex < len(resourceQuotasToProcess); fetchIndex++ {\n\t\t\t\t\tlatestQuota, err := q.client.Core().ResourceQuotas(namespace).Get(resourceQuotasToProcess[fetchIndex].Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"Unable to get quota: %s %v\", resourceQuotasToProcess[fetchIndex].Name, err))\n\t\t\t\t\t}\n\t\t\t\t\ttryAgain = append(tryAgain, latestQuota)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// all quotas were updated, so we can return\n\t\tif len(tryAgain) == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\t// we have concurrent requests to update quota, so look to retry if needed\n\t\t// next iteration, we need to process the items that have to try again\n\t\t// pause the specified interval to encourage jitter\n\t\tif retry == numRetries {\n\t\t\tnames := []string{}\n\t\t\tfor _, quota := range tryAgain {\n\t\t\t\tnames = append(names, quota.Name)\n\t\t\t}\n\t\t\treturn admission.NewForbidden(a, fmt.Errorf(\"Unable to update status for quota: %s, \", strings.Join(names, \",\")))\n\t\t}\n\t\tresourceQuotasToProcess = tryAgain\n\t\ttime.Sleep(interval)\n\t}\n\treturn nil\n}", "func (a *AdminPolicyStatus1) Path() dbus.ObjectPath {\n\treturn a.client.Config.Path\n}", "func PathBase(path string) string {\n\t// If this is the root path, then just return an empty string.\n\tif path == \"\" {\n\t\treturn \"\"\n\t}\n\n\t// Identify the index of the last slash in the path.\n\tlastSlashIndex := strings.LastIndexByte(path, '/')\n\n\t// If there is no slash, then the path is a file directly under the\n\t// synchronization root.\n\tif lastSlashIndex == -1 {\n\t\treturn path\n\t}\n\n\t// Verify that the base name isn't empty (i.e. that the string doesn't end\n\t// with a slash). We could do additional validation here (e.g. validating\n\t// the path segment before the slash), but it would be costly and somewhat\n\t// unnecessary. This check is sufficient to ensure that this function can\n\t// return a meaningful answer.\n\tif lastSlashIndex == len(path)-1 {\n\t\tpanic(\"empty base name\")\n\t}\n\n\t// Extract the base name.\n\treturn path[lastSlashIndex+1:]\n}", "func (p *AuroraAdminClient) SetQuota(ctx context.Context, ownerRole string, quota *ResourceAggregate) (r *Response, err error) {\n var _args367 AuroraAdminSetQuotaArgs\n _args367.OwnerRole = ownerRole\n _args367.Quota = quota\n var _result368 AuroraAdminSetQuotaResult\n var meta thrift.ResponseMeta\n meta, err = p.Client_().Call(ctx, \"setQuota\", &_args367, &_result368)\n p.SetLastResponseMeta_(meta)\n if err != nil {\n return\n }\n return _result368.GetSuccess(), nil\n}", "func (req *Request) FullPath() string {\n\tif len(req.path) == 0 {\n\t\treq.path = req.Node.FullPath()\n\t}\n\treturn req.path\n}", "func (*CaGroup) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/group/%s\", ref)\n}", "func (n *NetNs) Path() string {\n\tif n == nil || n.netNS == nil {\n\t\treturn \"\"\n\t}\n\treturn n.netNS.Path()\n}", "func (s *roomServiceServer) PathPrefix() string {\n\treturn baseServicePath(s.pathPrefix, \"livekit\", \"RoomService\")\n}", "func (*SpxGroup) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/spx/group/%s\", ref)\n}", "func (c *Driver) MountPath(do storage.DriverOptions) (string, error) {\n\tvolName, err := c.internalName(do.Volume.Name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(c.mountpath, do.Volume.Params[\"pool\"], volName), nil\n}", "func QuotaStorage(v int) predicate.User {\n\treturn predicate.User(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldQuotaStorage), v))\n\t})\n}", "func Path(w time.Duration, typ StatType, prefix []string) []string {\n\treturn stat{window: w, typ: typ}.metaPath(prefix)\n}", "func newQuota() *catalogue.Quota {\n\treturn &catalogue.Quota{\n\t\tCores: 99999,\n\t\tFloatingIPs: 99999,\n\t\tInstances: 99999,\n\t\tKeyPairs: 99999,\n\t\tRAM: 99999,\n\t\tTenant: \"test-tenant\",\n\t}\n}", "func (o UsagePlanApiStageThrottleOutput) Path() pulumi.StringOutput {\n\treturn o.ApplyT(func(v UsagePlanApiStageThrottle) string { return v.Path }).(pulumi.StringOutput)\n}", "func (*InterfacePpp3G) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/interface/ppp3g/%s\", ref)\n}", "func (o FunctionServiceConfigSecretVolumeOutput) MountPath() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FunctionServiceConfigSecretVolume) string { return v.MountPath }).(pulumi.StringOutput)\n}", "func (adm *AdminClient) SetBucketQuota(ctx context.Context, bucket string, quota *BucketQuota) error {\n\tdata, err := json.Marshal(quota)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqueryValues := url.Values{}\n\tqueryValues.Set(\"bucket\", bucket)\n\n\treqData := requestData{\n\t\trelPath: adminAPIPrefix + \"/set-bucket-quota\",\n\t\tqueryValues: queryValues,\n\t\tcontent: data,\n\t}\n\n\t// Execute PUT on /minio/admin/v3/set-bucket-quota to set quota for a bucket.\n\tresp, err := adm.executeMethod(ctx, http.MethodPut, reqData)\n\n\tdefer closeResponse(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn httpRespToErrorResponse(resp)\n\t}\n\n\treturn nil\n}", "func (c *Config) SetNsPath(nstype specs.LinuxNamespaceType, path string) error {\n\tcpath := unsafe.Pointer(C.CString(path))\n\tl := len(path)\n\tsize := C.size_t(l)\n\n\tif l > C.MAX_NS_PATH_SIZE-1 {\n\t\treturn fmt.Errorf(\"%s namespace path too big\", nstype)\n\t}\n\n\tswitch nstype {\n\tcase specs.UserNamespace:\n\t\tC.memcpy(unsafe.Pointer(&c.config.namespace.user[0]), cpath, size)\n\tcase specs.IPCNamespace:\n\t\tC.memcpy(unsafe.Pointer(&c.config.namespace.ipc[0]), cpath, size)\n\tcase specs.UTSNamespace:\n\t\tC.memcpy(unsafe.Pointer(&c.config.namespace.uts[0]), cpath, size)\n\tcase specs.PIDNamespace:\n\t\tC.memcpy(unsafe.Pointer(&c.config.namespace.pid[0]), cpath, size)\n\tcase specs.NetworkNamespace:\n\t\tC.memcpy(unsafe.Pointer(&c.config.namespace.network[0]), cpath, size)\n\tcase specs.MountNamespace:\n\t\tC.memcpy(unsafe.Pointer(&c.config.namespace.mount[0]), cpath, size)\n\tcase specs.CgroupNamespace:\n\t\tC.memcpy(unsafe.Pointer(&c.config.namespace.cgroup[0]), cpath, size)\n\t}\n\n\tC.free(cpath)\n\n\treturn nil\n}", "func setProjectQuota(backingFsBlockDev string, projectID uint32, quota Quota) error {\n\tvar d C.fs_disk_quota_t\n\td.d_version = C.FS_DQUOT_VERSION\n\td.d_id = C.__u32(projectID)\n\td.d_flags = C.XFS_PROJ_QUOTA\n\n\td.d_fieldmask = C.FS_DQ_BHARD | C.FS_DQ_BSOFT\n\td.d_blk_hardlimit = C.__u64(quota.Size / 512)\n\td.d_blk_softlimit = d.d_blk_hardlimit\n\n\tcs := C.CString(backingFsBlockDev)\n\tdefer C.free(unsafe.Pointer(cs))\n\n\t_, _, errno := unix.Syscall6(unix.SYS_QUOTACTL, C.Q_XSETPQLIM,\n\t\tuintptr(unsafe.Pointer(cs)), uintptr(d.d_id),\n\t\tuintptr(unsafe.Pointer(&d)), 0, 0)\n\tif errno != 0 {\n\t\treturn errors.Wrapf(errno, \"failed to set quota limit for projid %d on %s\",\n\t\t\tprojectID, backingFsBlockDev)\n\t}\n\n\treturn nil\n}", "func TestRootFsQuotaManager_GetVolumes(t *testing.T) {\n\tcontainerNoRunningPodStatus := v1.PodStatus{\n\t\tContainerStatuses: []v1.ContainerStatus{\n\t\t\t{\n\t\t\t\tContainerID: \"docker://\" + containerNoId,\n\t\t\t},\n\t\t\t{\n\t\t\t\tContainerID: \"docker://\" + containerNoRunning,\n\t\t\t},\n\t\t\t{\n\t\t\t\tContainerID: \"docker://\" + containerRunning,\n\t\t\t},\n\t\t},\n\t}\n\tpodStatus := v1.PodStatus{\n\t\tContainerStatuses: []v1.ContainerStatus{\n\t\t\t{\n\t\t\t\tContainerID: \"docker://\" + containerNoId,\n\t\t\t},\n\t\t\t{\n\t\t\t\tContainerID: \"docker://\" + containerRunning,\n\t\t\t},\n\t\t},\n\t}\n\n\ttestCases := []rootFsTestData{\n\t\t{\n\t\t\tdescribe: \"containerNotRunning\",\n\t\t\tisOffline: false,\n\t\t\thasQuota: true,\n\t\t\thostNamespace: true,\n\t\t\tcontainerRunning: false,\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\ttypes.PodAnnotationPrefix + \"rootfs-diskquota\": \"quota=1024000,inodes=10000\",\n\t\t\t\t\t},\n\t\t\t\t\tUID: \"01780108-c5dd-457e-b99a-dade618bd1a1\",\n\t\t\t\t},\n\t\t\t\tStatus: containerNoRunningPodStatus,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescribe: \"onlinePodNoQuotaHostNamespace\",\n\t\t\tisOffline: false,\n\t\t\thasQuota: false,\n\t\t\thostNamespace: true,\n\t\t\tcontainerRunning: true,\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{},\n\t\t\t\t\tUID: \"01780108-c5dd-457e-b99a-dade618bd1a1\",\n\t\t\t\t},\n\t\t\t\tStatus: podStatus,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescribe: \"onlinePodHasQuotaHostNamespace\",\n\t\t\tisOffline: false,\n\t\t\thasQuota: true,\n\t\t\thostNamespace: true,\n\t\t\tcontainerRunning: true,\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\ttypes.PodAnnotationPrefix + \"rootfs-diskquota\": \"quota=1024000,inodes=10000\",\n\t\t\t\t\t},\n\t\t\t\t\tUID: \"01780108-c5dd-457e-b99a-dade618bd1a1\",\n\t\t\t\t},\n\t\t\t\tStatus: podStatus,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescribe: \"onlinePodHasQuotaNoHostNamespace\",\n\t\t\tisOffline: false,\n\t\t\thasQuota: true,\n\t\t\thostNamespace: false,\n\t\t\tcontainerRunning: true,\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\ttypes.PodAnnotationPrefix + \"rootfs-diskquota\": \"quota=1024000,inodes=10000\",\n\t\t\t\t\t},\n\t\t\t\t\tUID: \"01780108-c5dd-457e-b99a-dade618bd1a1\",\n\t\t\t\t},\n\t\t\t\tStatus: podStatus,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescribe: \"offlinePodNoQuotaHostNamespace\",\n\t\t\tisOffline: true,\n\t\t\thasQuota: false,\n\t\t\thostNamespace: true,\n\t\t\tcontainerRunning: true,\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tappclass.AnnotationOfflineKey: appclass.AnnotationOfflineValue,\n\t\t\t\t\t},\n\t\t\t\t\tUID: \"01780108-c5dd-457e-b99a-dade618bd1a1\",\n\t\t\t\t},\n\t\t\t\tStatus: podStatus,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescribe: \"offlinePodHasQuotaHostNamespace\",\n\t\t\tisOffline: true,\n\t\t\thasQuota: true,\n\t\t\thostNamespace: true,\n\t\t\tcontainerRunning: true,\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tappclass.AnnotationOfflineKey: appclass.AnnotationOfflineValue,\n\t\t\t\t\t\ttypes.PodAnnotationPrefix + \"rootfs-diskquota\": \"quota=1024000,inodes=10000\",\n\t\t\t\t\t},\n\t\t\t\t\tUID: \"01780108-c5dd-457e-b99a-dade618bd1a1\",\n\t\t\t\t},\n\t\t\t\tStatus: podStatus,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescribe: \"offlinePodHasQuotaNotHostNamespace\",\n\t\t\tisOffline: true,\n\t\t\thasQuota: true,\n\t\t\thostNamespace: false,\n\t\t\tcontainerRunning: true,\n\t\t\tpod: &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tAnnotations: map[string]string{\n\t\t\t\t\t\tappclass.AnnotationOfflineKey: appclass.AnnotationOfflineValue,\n\t\t\t\t\t\ttypes.PodAnnotationPrefix + \"rootfs-diskquota\": \"quota=1024000,inodes=10000\",\n\t\t\t\t\t},\n\t\t\t\t\tUID: \"01780108-c5dd-457e-b99a-dade618bd1a1\",\n\t\t\t\t},\n\t\t\t\tStatus: podStatus,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tutil.InHostNamespace = tc.hostNamespace\n\t\tt.Run(tc.describe, rootFsWrapperFunc(&tc))\n\t}\n}", "func (p *AuroraAdminClient) SetQuota(ctx context.Context, ownerRole string, quota *ResourceAggregate) (r *Response, err error) {\n var _args317 AuroraAdminSetQuotaArgs\n _args317.OwnerRole = ownerRole\n _args317.Quota = quota\n var _result318 AuroraAdminSetQuotaResult\n if err = p.Client_().Call(ctx, \"setQuota\", &_args317, &_result318); err != nil {\n return\n }\n return _result318.GetSuccess(), nil\n}", "func PathExpandTilda(path string) string {\n\tif len(path) < 2 {\n\t\treturn path\n\t}\n\n\tfixedPath := path\n\tif fixedPath[:2] == \"~/\" {\n\t\tuserDir, _ := user.Current()\n\t\thomeDir := userDir.HomeDir\n\t\tfixedPath = filepath.Join(homeDir, fixedPath[2:])\n\t}\n\n\treturn fixedPath\n}", "func LookUpStorageSpaceForPath(ctx context.Context, selector pool.Selectable[gateway.GatewayAPIClient], path string) (*storageProvider.StorageSpace, *rpc.Status, error) {\n\t// TODO add filter to only fetch spaces changed in the last 30 sec?\n\t// TODO cache space information, invalidate after ... 5min? so we do not need to fetch all spaces?\n\t// TODO use ListContainerStream to listen for changes\n\t// retrieve a specific storage space\n\tlSSReq := &storageProvider.ListStorageSpacesRequest{\n\t\tOpaque: &typesv1beta1.Opaque{\n\t\t\tMap: map[string]*typesv1beta1.OpaqueEntry{\n\t\t\t\t\"path\": {\n\t\t\t\t\tDecoder: \"plain\",\n\t\t\t\t\tValue: []byte(path),\n\t\t\t\t},\n\t\t\t\t\"unique\": {\n\t\t\t\t\tDecoder: \"plain\",\n\t\t\t\t\tValue: []byte(strconv.FormatBool(true)),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tclient, err := selector.Next()\n\tif err != nil {\n\t\treturn nil, status.NewInternal(ctx, \"could not select next client\"), err\n\t}\n\n\tlSSRes, err := client.ListStorageSpaces(ctx, lSSReq)\n\tif err != nil || lSSRes.Status.Code != rpc.Code_CODE_OK {\n\t\tstatus := status.NewStatusFromErrType(ctx, \"failed to lookup storage spaces\", err)\n\t\tif lSSRes != nil {\n\t\t\tstatus = lSSRes.Status\n\t\t}\n\t\treturn nil, status, err\n\t}\n\tswitch len(lSSRes.StorageSpaces) {\n\tcase 0:\n\t\treturn nil, status.NewNotFound(ctx, \"no space found\"), nil\n\tcase 1:\n\t\treturn lSSRes.StorageSpaces[0], lSSRes.Status, nil\n\t}\n\n\treturn nil, status.NewInternal(ctx, \"too many spaces returned\"), nil\n}", "func (s *rPCServer) PathPrefix() string {\n\treturn baseServicePath(s.pathPrefix, \"samsahai.io.samsahai\", \"RPC\")\n}", "func (*HttpSpCategory) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/http/sp_category/%s\", ref)\n}", "func (s *userServiceServer) PathPrefix() string {\n\treturn baseServicePath(s.pathPrefix, \"buf.alpha.registry.v1alpha1\", \"UserService\")\n}", "func (s *userServiceServer) PathPrefix() string {\n\treturn baseServicePath(s.pathPrefix, \"buf.alpha.registry.v1alpha1\", \"UserService\")\n}", "func (o *StorageNetAppCifsShareAllOf) GetPath() string {\n\tif o == nil || o.Path == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Path\n}", "func setProjectQuota(backingFsBlockDev string, projectID quotaID, quota *types.DiskQuotaSize) error {\n\tklog.V(4).Infof(\"Setting projec quota for %d: %+v\", projectID, quota)\n\n\tvar d C.fs_disk_quota_t\n\td.d_version = C.FS_DQUOT_VERSION\n\td.d_id = C.__u32(projectID)\n\td.d_flags = C.XFS_PROJ_QUOTA\n\n\td.d_fieldmask = C.FS_DQ_BHARD | C.FS_DQ_BSOFT | C.FS_DQ_IHARD | C.FS_DQ_ISOFT\n\td.d_blk_hardlimit = C.__u64(quota.Quota / 512)\n\td.d_blk_softlimit = d.d_blk_hardlimit\n\td.d_ino_hardlimit = C.__u64(quota.Inodes)\n\td.d_ino_softlimit = d.d_ino_hardlimit\n\n\tvar cs = C.CString(backingFsBlockDev)\n\tdefer C.free(unsafe.Pointer(cs))\n\n\t_, _, errno := unix.Syscall6(unix.SYS_QUOTACTL, C.Q_XSETPQLIM,\n\t\tuintptr(unsafe.Pointer(cs)), uintptr(d.d_id),\n\t\tuintptr(unsafe.Pointer(&d)), 0, 0)\n\tif errno != 0 {\n\t\treturn fmt.Errorf(\"failed to set quota limit for projid %d on %s: %v\",\n\t\t\tprojectID, backingFsBlockDev, errno)\n\t}\n\n\treturn nil\n}", "func (s *Nap) Path(path string) *Nap {\n\tbaseURL, baseErr := url.Parse(s.rawURL)\n\tpathURL, pathErr := url.Parse(path)\n\tif baseErr == nil && pathErr == nil {\n\t\ts.rawURL = baseURL.ResolveReference(pathURL).String()\n\t\tif strings.HasSuffix(path, \"/\") && !strings.HasSuffix(s.rawURL, \"/\") {\n\t\t\ts.rawURL += \"/\"\n\t\t}\n\t\treturn s\n\t}\n\treturn s\n}", "func (*SnmpGroup) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/snmp/group/%s\", ref)\n}", "func (*CaSigningCa) PutPath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/signing_ca/%s\", ref)\n}", "func (l *Local) FullPath(path string) string {\n\t// append the given path to the base path\n\treturn filepath.Join(l.basePath, path)\n}", "func SetPath(permissions string) error {\n\tif permissions != \"default\" {\n\t\tpl, err := NewPermissionsLoader(permissions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = pl\n\t\tif !pl.Get().Watch {\n\t\t\tglobalPermissions.Close() // This will still keep the permissions themselves in memory\n\t\t}\n\n\t} else {\n\t\tif globalPermissions != nil {\n\t\t\tglobalPermissions.Close()\n\t\t}\n\t\tglobalPermissions = nil\n\t}\n\treturn nil\n}" ]
[ "0.61456865", "0.59919655", "0.58387405", "0.56591785", "0.5576382", "0.5452652", "0.53241897", "0.52723014", "0.5254918", "0.52149916", "0.516941", "0.51012826", "0.5090478", "0.50741565", "0.5069529", "0.50529176", "0.50515765", "0.5025699", "0.49996784", "0.49406362", "0.49132097", "0.48894852", "0.48885503", "0.48799923", "0.48572275", "0.47997767", "0.4758655", "0.47523034", "0.47154254", "0.47049636", "0.46933046", "0.46829993", "0.46741515", "0.46590933", "0.46580482", "0.46575654", "0.46563584", "0.46536258", "0.4632203", "0.4629458", "0.46175742", "0.4617087", "0.46147925", "0.46130028", "0.46093097", "0.46082807", "0.46058708", "0.46003082", "0.45994836", "0.45969722", "0.4585441", "0.45804504", "0.4556312", "0.45557415", "0.4545817", "0.45440122", "0.45395133", "0.4531483", "0.45089874", "0.44762042", "0.44700387", "0.44685298", "0.44681212", "0.44535244", "0.4453497", "0.44522005", "0.44510114", "0.44499117", "0.4439196", "0.44253463", "0.44252548", "0.4417387", "0.44161153", "0.4411977", "0.44068334", "0.44047713", "0.44035718", "0.43972516", "0.4396119", "0.4393166", "0.43801665", "0.4373729", "0.43726602", "0.43692556", "0.43691966", "0.4364399", "0.4363282", "0.43584308", "0.4355519", "0.43547964", "0.4353342", "0.43523988", "0.43523988", "0.43501335", "0.4346249", "0.43444982", "0.4340671", "0.43312082", "0.43302935", "0.43298888" ]
0.6185023
0
The maximum number of requests at any given second to be allowed by the quota rule. The `rate` must be positive.
func (o QuotaRateLimitOutput) Rate() pulumi.Float64Output { return o.ApplyT(func(v *QuotaRateLimit) pulumi.Float64Output { return v.Rate }).(pulumi.Float64Output) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RateLimit(w http.ResponseWriter, r *http.Request) {\n\tvar tc *http.Client\n\n\tc := cloudpkgs.NewContext(w, r)\n\tctx := context.Background()\n\n\tt := c.Request.Header.Get(\"Authorization\")\n\tif t != \"\" {\n\t\tts := oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: t},\n\t\t)\n\t\ttc = oauth2.NewClient(ctx, ts)\n\t}\n\n\tclient := cloudapi.NewAPIClient(tc)\n\n\trate, _, err := client.Client.RateLimits(ctx)\n\tif err != nil {\n\t\tc.WriteJSON(http.StatusRequestTimeout, cloudpkgs.H{\"status\": http.StatusRequestTimeout})\n\t\treturn\n\t}\n\n\tc.WriteJSON(http.StatusOK, cloudpkgs.H{\"status\": http.StatusOK, \"rate\": rate})\n}", "func (s *Server) Rate() rate.Limit {\n\tr := time.Duration(s.rate) * time.Second\n\treturn rate.Every(r)\n}", "func (t *threadThrottler) setMaxRate(newRate int64) {\n\tt.maxRate.Store(newRate)\n}", "func LimitRate(timeFun func(time.Time) time.Time, limit int) pipes.Middleware {\n\tvar rateWindow string\n\tentry := &rateEntry{\n\t\tIPs: map[string]int{},\n\t}\n\n\treturn func(ctx context.Context, w http.ResponseWriter, r *http.Request, next pipes.Next) {\n\t\tip := r.RemoteAddr\n\t\tcurrentWindow := timeFun(getNow()).String()\n\n\t\tif currentWindow != rateWindow {\n\t\t\trateWindow = currentWindow\n\t\t\tentry = &rateEntry{\n\t\t\t\tIPs: map[string]int{\n\t\t\t\t\tip: 1,\n\t\t\t\t},\n\t\t\t}\n\t\t} else if entry.IPs[ip] > limit {\n\t\t\tw.WriteHeader(http.StatusTooManyRequests)\n\t\t\treturn\n\t\t} else {\n\t\t\tentry.IPs[ip]++\n\t\t}\n\t\tnext(ctx)\n\t}\n}", "func (c *Client) RateLimit() RateLimit {\n\tif c.limit != nil {\n\t\treturn *c.limit\n\t}\n\taccount, err := c.Account.Get()\n\tif err != nil {\n\t\treturn RateLimit{}\n\t}\n\tc.limit = &RateLimit{}\n\tfor _, metric := range account.Metrics {\n\t\tif metric.PlanLevel > 0 {\n\t\t\tc.limit.Limit = metric.PlanLevel\n\t\t\tc.limit.Remaining = metric.Remaining\n\t\t}\n\t}\n\treturn *c.limit\n}", "func (l *RateLimiter) Limit(now time.Time, tenantID string) float64 {\n\treturn float64(l.getTenantLimiter(now, tenantID).Limit())\n}", "func rate(read int64, t time.Duration) float64 {\n\treturn float64(read) / (1024 * 1024) / t.Seconds()\n}", "func (a *Application) Limit() int64 {\n\tif a.InProduction {\n\t\treturn rateLimitProduction\n\t}\n\n\treturn rateLimitStaging\n}", "func RateLimit(max float64) gin.HandlerFunc {\n\n\tlmt := tollbooth.NewLimiter(max, nil)\n\n\treturn func(c *gin.Context) {\n\t\thttpError := tollbooth.LimitByRequest(lmt, c.Writer, c.Request)\n\t\tif httpError != nil {\n\t\t\tc.Data(httpError.StatusCode, lmt.GetMessageContentType(), []byte(httpError.Message))\n\t\t\tc.Abort()\n\t\t} else {\n\t\t\tc.Next()\n\t\t}\n\t}\n}", "func (o *SnapmirrorResyncRequest) MaxTransferRate() int {\n\tvar r int\n\tif o.MaxTransferRatePtr == nil {\n\t\treturn r\n\t}\n\tr = *o.MaxTransferRatePtr\n\treturn r\n}", "func (c *client) rateRequest() {\n\tc.rateMu.Lock()\n\tdefer c.rateMu.Unlock()\n\n\tif time.Now().After(c.nextReq) {\n\t\tc.nextReq = time.Now().Add(rateLimit)\n\t\treturn\n\t}\n\n\tcurrentReq := c.nextReq\n\tc.nextReq = currentReq.Add(rateLimit)\n\t<-time.After(currentReq.Sub(time.Now()))\n}", "func (c *Client) RateLimit() int {\n\treturn c.rateLimit\n}", "func (o *SnapmirrorCreateRequest) MaxTransferRate() int {\n\tvar r int\n\tif o.MaxTransferRatePtr == nil {\n\t\treturn r\n\t}\n\tr = *o.MaxTransferRatePtr\n\treturn r\n}", "func (t *threadThrottler) getMaxRate() int64 {\n\treturn t.maxRate.Load()\n}", "func (limiter *redisPeriodRateLimiterImpl) Request(ctx context.Context, key string, cost float64) (float64, time.Time, error) {\n\tredisKey := fmt.Sprintf(\"%s:period-rate-limit:%s\", limiter.prefix, key)\n\tscript := redis.NewScript(redisPeriodRateLimiterScript)\n\tr, err := script.Run(ctx, limiter.redis, []string{redisKey}, cost, limiter.quota, int64(limiter.resetPeriod.Milliseconds())).Result()\n\tif err != nil {\n\t\treturn 0, time.Time{}, fmt.Errorf(\"redis error: %v\", err)\n\t}\n\n\t// parse the response\n\tresultsObject, ok := r.([]interface{})\n\tif !ok {\n\t\treturn 0, time.Time{}, ErrRedisPeriodRateLimiterUnknown\n\t}\n\tquota, err := redis.NewCmdResult(resultsObject[0], nil).Float64()\n\tif err != nil {\n\t\treturn 0, time.Time{}, ErrRedisPeriodRateLimiterUnknown\n\t}\n\tpttl, err := redis.NewCmdResult(resultsObject[1], nil).Int64()\n\tif err != nil {\n\t\treturn quota, time.Time{}, ErrRedisPeriodRateLimiterUnknown\n\t}\n\tisEnough, err := redis.NewCmdResult(resultsObject[2], nil).Bool()\n\tif err != nil {\n\t\treturn 0, time.Now().Add(time.Duration(pttl) * time.Millisecond), ErrRedisPeriodRateLimiterUnknown\n\t}\n\n\tif !isEnough {\n\t\treturn quota, time.Now().Add(time.Duration(pttl) * time.Millisecond), ErrRateLimiterQuotaNotEnough\n\t}\n\treturn quota, time.Now().Add(time.Duration(pttl) * time.Millisecond), nil\n}", "func (rl *limiter) GetRate() int64 {\n\trl.lock.RLock()\n\tqps := rl.qps\n\trl.lock.RUnlock()\n\n\treturn qps\n}", "func (n *Globals) RateLimit(url string) {\n\tif rateLimiter, ok := n.rateLimiters[url]; ok {\n\t\trateLimiter.Wait()\n\t}\n}", "func ratelimiter(args map[string]interface{}) *ratelimit.Ratelimiter {\n\trate, err := strconv.Atoi(args[\"--ratelimit-max-rate\"].(string))\n\tif err != nil {\n\t\tlog.Fatalf(\"error parsing --ratelimit-max-rate: %s\", err)\n\t}\n\n\tif rate <= 0 {\n\t\treturn nil\n\t}\n\n\tkeys, err := strconv.Atoi(args[\"--ratelimit-max-keys\"].(string))\n\tif err != nil {\n\t\tlog.Fatalf(\"error parsing --ratelimit-max-keys: %s\", err)\n\t}\n\n\treturn ratelimit.New(rate, keys)\n}", "func rateLimitHandler(limit int, within int) gin.HandlerFunc {\n\treturn throttle.Policy(&throttle.Quota{\n\t\tLimit: uint64(limit),\n\t\tWithin: time.Duration(within) * time.Second,\n\t})\n}", "func LimiterRate(rate float64) Option {\n\treturn func(o *options) {\n\t\to.limiterRate = rate\n\t}\n}", "func RateLimit(nic string, rate string) string {\n\tif rate != \"\" {\n\t\tburst, _ := strconv.Atoi(rate)\n\t\tburst = burst / 10\n\n\t\texec.Command(\"ovs-vsctl\", \"set\", \"interface\", nic,\n\t\t\t\"ingress_policing_rate=\"+rate).Run()\n\n\t\texec.Command(\"ovs-vsctl\", \"set\", \"interface\", nic,\n\t\t\t\"ingress_policing_burst=\"+strconv.Itoa(burst)).Run()\n\t}\n\n\tout, _ := exec.Command(\"ovs-vsctl\", \"list\", \"interface\", nic).Output()\n\n\tscanner := bufio.NewScanner(bytes.NewReader(out))\n\tfor scanner.Scan() {\n\t\tline := strings.Fields(scanner.Text())\n\t\tif len(line) > 0 {\n\t\t\tif line[0] == \"ingress_policing_rate:\" {\n\t\t\t\treturn line[1]\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}", "func (o BackendResponseOutput) MaxRate() pulumi.IntOutput {\n\treturn o.ApplyT(func(v BackendResponse) int { return v.MaxRate }).(pulumi.IntOutput)\n}", "func RateLimit(d time.Duration) Tick {\n\tvar last *time.Time\n\treturn func(children []Node) (Status, error) {\n\t\tnow := time.Now()\n\t\tif last != nil && now.Add(-d).Before(*last) {\n\t\t\treturn Failure, nil\n\t\t}\n\t\tlast = &now\n\t\treturn Success, nil\n\t}\n}", "func (s *Setup) RateLimit(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tip, _, err := net.SplitHostPort(r.RemoteAddr)\n\t\tif err != nil {\n\t\t\terrhandler.DecodeError(w, r, s.logger, errInternal, http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tlimiter := ratelimit.GetVisitor(ip)\n\t\tif !limiter.Allow() {\n\t\t\terrhandler.DecodeError(\n\t\t\t\tw,\n\t\t\t\tr,\n\t\t\t\ts.logger,\n\t\t\t\thttp.StatusText(http.StatusTooManyRequests),\n\t\t\t\thttp.StatusTooManyRequests,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func NewLimiter(max int64, ttl time.Duration, conf *rate.ConfigRedis) *Limiter {\n\tlimiter := &Limiter{Max: max, TTL: ttl}\n\tlimiter.MessageContentType = \"text/plain; charset=utf-8\"\n\tlimiter.Message = \"You have reached maximum request limit.\"\n\tlimiter.StatusCode = 429\n\tlimiter.tokenBuckets = make(map[string]*rate.Limiter)\n\tlimiter.IPLookups = []string{\"RemoteAddr\", \"X-Forwarded-For\", \"X-Real-IP\"}\n\n\tif err := rate.SetRedis(conf); err != nil {\n\t\tlog.Println(\"fail to set rate limiter's redis: \", err)\n\t}\n\n\treturn limiter\n}", "func NewLimitRate(name string, options LimitRateOptions) *LimitRate {\n\tthis := LimitRate{}\n\tthis.Name = name\n\tthis.Options = options\n\treturn &this\n}", "func (jl *JobLimiter) GetRequestRatePerSec() int {\n\treturn jl.currentJobCounter.getJobCountWithoutLock()\n}", "func (ob *Observable) RateLimit(timeframeMS int, notifyWhenChangesStop ...bool) {\n\tmethod := \"notifyAtFixedRate\"\n\tif len(notifyWhenChangesStop) >= 1 && notifyWhenChangesStop[0] {\n\t\tmethod = \"notifyWhenChangesStop\"\n\t}\n\tob.Extend(js.M{\n\t\t\"rateLimit\": js.M{\n\t\t\t\"timeout\": timeframeMS,\n\t\t\t\"method\": method,\n\t\t},\n\t})\n}", "func (ob *Observable) RateLimit(timeframeMS int, notifyWhenChangesStop ...bool) {\n\tmethod := \"notifyAtFixedRate\"\n\tif len(notifyWhenChangesStop) >= 1 && notifyWhenChangesStop[0] {\n\t\tmethod = \"notifyWhenChangesStop\"\n\t}\n\tob.Extend(js.M{\n\t\t\"rateLimit\": js.M{\n\t\t\t\"timeout\": timeframeMS,\n\t\t\t\"method\": method,\n\t\t},\n\t})\n}", "func (fm *FakeManager) SetMaxRate(int64) []string {\n\tpanic(panicMsg)\n}", "func RateLimitBitsPerSecond(bps uint64) ConsumerOption {\n\treturn func(o *api.ConsumerConfig) error {\n\t\to.RateLimit = bps\n\t\treturn nil\n\t}\n}", "func (conn *Conn) rateLimit(chars int) time.Duration {\n\t// Hybrid's algorithm allows for 2 seconds per line and an additional\n\t// 1/120 of a second per character on that line.\n\tlinetime := 2*time.Second + time.Duration(chars)*time.Second/120\n\telapsed := time.Now().Sub(conn.lastsent)\n\tif conn.badness += linetime - elapsed; conn.badness < 0 {\n\t\t// negative badness times are badness...\n\t\tconn.badness = 0\n\t}\n\tconn.lastsent = time.Now()\n\t// If we've sent more than 10 second's worth of lines according to the\n\t// calculation above, then we're at risk of \"Excess Flood\".\n\tif conn.badness > 10*time.Second {\n\t\treturn linetime\n\t}\n\treturn 0\n}", "func (conn *Conn) rateLimit(chars int) time.Duration {\n\t// Hybrid's algorithm allows for 2 seconds per line and an additional\n\t// 1/120 of a second per character on that line.\n\tlinetime := 2*time.Second + time.Duration(chars)*time.Second/120\n\telapsed := time.Now().Sub(conn.lastsent)\n\tif conn.badness += linetime - elapsed; conn.badness < 0 {\n\t\t// negative badness times are badness...\n\t\tconn.badness = 0\n\t}\n\tconn.lastsent = time.Now()\n\t// If we've sent more than 10 second's worth of lines according to the\n\t// calculation above, then we're at risk of \"Excess Flood\".\n\tif conn.badness > 10*time.Second {\n\t\treturn linetime\n\t}\n\treturn 0\n}", "func (o UsagePlanThrottleSettingsOutput) RateLimit() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v UsagePlanThrottleSettings) *float64 { return v.RateLimit }).(pulumi.Float64PtrOutput)\n}", "func (bucket *Bucket) Rate() float64 {\n\treturn 1e9 / float64(bucket.fillInterval)\n}", "func RateLimit(dur time.Duration) func(*Dispatcher) {\n\treturn func(d *Dispatcher) {\n\t\td.startTicker(dur)\n\t}\n}", "func rateLimit(limit int) func(next http.Handler) http.Handler {\n\tlimiter := rate.NewLimiter(rate.Every(time.Second/time.Duration(limit)), limit*2)\n\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tif !limiter.Allow() {\n\t\t\t\terrRateLimitExceeded.Write(w)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func (_BREMICO *BREMICOCaller) Rate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"rate\")\n\treturn *ret0, err\n}", "func (p *OnuTcontProfile) SetMaxRate(i int) {\r\n\tif i < 256 {\r\n\t\ti = 256\r\n\t}\r\n\tif i > 1244160 {\r\n\t\ti = 1244160\r\n\t}\r\n\tp.MaxDataRate = i\r\n}", "func getNetemLimit(rate string, delay string) string {\n\tr := rate[:len(rate)-4]\n\tunit := rate[len(rate)-4:]\n\tvar bps uint64\n\n\tswitch unit {\n\tcase \"kbit\":\n\t\tbps = 1 << 10\n\tcase \"mbit\":\n\t\tbps = 1 << 20\n\tcase \"gbit\":\n\t\tbps = 1 << 30\n\t}\n\trateUint, _ := strconv.ParseUint(r, 10, 64)\n\n\td, _ := time.ParseDuration(delay)\n\tdelayNsUint := uint64(d.Nanoseconds())\n\t// floor to 1 ms for purposes of sizing the limit\n\tif delayNsUint < 1e6 {\n\t\tdelayNsUint = 1e6\n\t}\n\n\t// Bandwidth-delay product\n\tbdp := rateUint * bps * delayNsUint / 1e9\n\n\t// Limit is in packets, so divide BDP (in bits)\n\t// by typical packet size, roughly 10,000 bits\n\t// Empirically, then multiply by 1000, to avoid some observed premature drops\n\t// Buffers really should be tuned according to application, but\n\t// we can start off with something roughly reasonable...\n\tlimit := bdp / 1e3\n\tlog.Debug(\"rate %s, delay %s => bandwidth-delay product %d bits => auto-calculated limit %d packets\", rate, delay, bdp, limit)\n\n\tif limit < minNetemLimit {\n\t\tlimit = minNetemLimit\n\t}\n\tif limit > maxNetemLimit {\n\t\tlimit = maxNetemLimit\n\t}\n\treturn strconv.FormatUint(limit, 10)\n}", "func (o AccountThrottleSettingOutput) RateLimit() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v AccountThrottleSetting) *float64 { return v.RateLimit }).(pulumi.Float64PtrOutput)\n}", "func TestThrottle_MaxRateLowerThanThreadCount(t *testing.T) {\n\tfc := &fakeClock{}\n\t// 2 Thread, 1 QPS.\n\tthrottler, _ := newThrottlerWithClock(\"test\", \"queries\", 2, 1, ReplicationLagModuleDisabled, fc.now)\n\tdefer throttler.Close()\n\n\t// 2 QPS instead of configured 1 QPS allowed since there are 2 threads which\n\t// must not starve.\n\tfc.setNow(1000 * time.Millisecond)\n\tfor threadID := 0; threadID < 1; threadID++ {\n\t\tif gotBackoff := throttler.Throttle(threadID); gotBackoff != NotThrottled {\n\t\t\tt.Fatalf(\"throttler should not have throttled thread %d: backoff = %v\", threadID, gotBackoff)\n\t\t}\n\t}\n\twantBackoff := 1000 * time.Millisecond\n\tfor threadID := 0; threadID < 1; threadID++ {\n\t\tif gotBackoff := throttler.Throttle(threadID); gotBackoff != wantBackoff {\n\t\t\tt.Fatalf(\"throttler should have throttled thread %d: got = %v, want = %v\", threadID, gotBackoff, wantBackoff)\n\t\t}\n\t}\n}", "func rateLimit(rw http.ResponseWriter, req *http.Request, app *App) bool {\n\tif app.Config.Rate_Limit.Enable {\n\t\tduration := time.Now().Unix() - app.Config.Rate_Limit.Seconds\n\t\tip, err := relevantIpBytes(req.RemoteAddr)\n\t\terrors := map[string]string{\"overall\": \"Rate limit reached.\"}\n\n\t\tif err != nil {\n\t\t\trenderErrors(rw, errors, 429)\n\t\t\treturn true\n\t\t}\n\n\t\tvar count int64\n\t\trow := app.Db.QueryRow(\"select count(*) from comments where ClientIp=? and Created>?\", ip, duration)\n\t\terr = row.Scan(&count)\n\n\t\tif err != nil || count >= app.Config.Rate_Limit.Max_Comments {\n\t\t\trenderErrors(rw, errors, 429)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func RateLimiting() {\n\n\t// First we’ll look at basic rate limiting.\n\t// Suppose we want to limit our handling of incoming requests.\n\t// We’ll serve these requests off a channel of the same name.\n\trequests := make(chan int, 5)\n\tfor i := 1; i <= 5; i++ {\n\t\trequests <- i\n\t}\n\tclose(requests)\n\n\t// This limiter channel will receive a value every 200 milliseconds.\n\t// This is the regulator in our rate limiting scheme.\n\tlimiter := time.Tick(200 * time.Millisecond)\n\n\t// By blocking on a receive from the limiter channel before serving each request,\n\t// we limit ourselves to 1 request every 200 milliseconds.\n\tfor req := range requests {\n\t\t<-limiter\n\t\tfmt.Println(\"request\", req, time.Now())\n\t}\n\t// We may want to allow short bursts of requests in our rate limiting\n\t// scheme while preserving the overall rate limit.\n\t//We can accomplish this by buffering our limiter channel.\n\t//This burstyLimiter channel will allow bursts of up to 3 events.\n\tburstyLimiter := make(chan time.Time, 3)\n\n\t// Fill up the channel to represent allowed bursting.\n\tfor i := 0; i < 3; i++ {\n\t\tburstyLimiter <- time.Now()\n\t}\n\n\t// Every 200 milliseconds we’ll try to add a new value to burstyLimiter, up to its limit of 3.\n\tgo func() {\n\t\tfor t := range time.Tick(200 * time.Millisecond) {\n\t\t\tburstyLimiter <- t\n\t\t}\n\t}()\n\n\t// Now simulate 5 more incoming requests.\n\t// The first 3 of these will benefit from the burst capability of burstyLimiter.\n\tburstyRequests := make(chan int, 5)\n\n\tfor i := 1; i <= 5; i++ {\n\t\tburstyRequests <- i\n\t}\n\tclose(burstyRequests)\n\tfor req := range burstyRequests {\n\t\t<-burstyLimiter\n\t\tfmt.Println(\"request\", req, time.Now())\n\t}\n\t// Running our program we see the first batch of requests handled once every ~200 milliseconds as desired.\n\t// For the second batch of requests we serve the first 3 immediately\n\t// because of the burstable rate limiting, then serve the remaining 2 with ~200ms delays each.\n\n}", "func (s *SlidingWindow) Limit(ctx context.Context) (time.Duration, error) {\n\tnow := s.clock.Now()\n\tcurrWindow := now.Truncate(s.rate)\n\tprevWindow := currWindow.Add(-s.rate)\n\tttl := s.rate - now.Sub(currWindow)\n\tprev, curr, err := s.backend.Increment(ctx, prevWindow, currWindow, ttl+s.rate)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\ttotal := float64(prev*int64(ttl))/float64(s.rate) + float64(curr)\n\tif total-float64(s.capacity) >= s.epsilon {\n\t\tvar wait time.Duration\n\t\tif curr <= s.capacity-1 && prev > 0 {\n\t\t\twait = ttl - time.Duration(float64(s.capacity-1-curr)/float64(prev)*float64(s.rate))\n\t\t} else {\n\t\t\t// If prev == 0.\n\t\t\twait = ttl + time.Duration((1-float64(s.capacity-1)/float64(curr))*float64(s.rate))\n\t\t}\n\t\treturn wait, ErrLimitExhausted\n\t}\n\treturn 0, nil\n}", "func (l *RateLimiter) Limit() rate.Limit {\n\treturn l.limiter.Limit()\n}", "func (o UsagePlanApiStageThrottleOutput) RateLimit() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v UsagePlanApiStageThrottle) *float64 { return v.RateLimit }).(pulumi.Float64PtrOutput)\n}", "func (_IncreasingPriceCrowdsaleImpl *IncreasingPriceCrowdsaleImplCaller) Rate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _IncreasingPriceCrowdsaleImpl.contract.Call(opts, out, \"rate\")\n\treturn *ret0, err\n}", "func (rl *limiter) SetRate(qps int64) error {\n\tif qps <= 0 {\n\t\treturn errors.New(\"qps must be greater than zero\")\n\t}\n\n\trl.lock.Lock()\n\trl.qps = qps\n\trl.lock.Unlock()\n\n\treturn nil\n}", "func TestLimiter_Burst(t *testing.T) {\n\trate := ratelimiter.Frequency(20)\n\tburst := uint64(10)\n\tlimiter, err := ratelimiter.NewLimiter(rate, burst)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error creating limiter for testing: %s\", err.Error())\n\t}\n\t// Allow limiter token bucket to fill\n\ttime.Sleep(time.Millisecond * 500)\n\tfor i := uint64(0); i < burst; i++ {\n\t\tif !limiter.Allow() {\n\t\t\tt.Errorf(\"Expected limiter to return true for Allow() but returned false.\")\n\t\t}\n\t}\n\tif limiter.Allow() {\n\t\tt.Errorf(\"Expected limiter to return false after having Allow() called the maximum burst number of times\")\n\t}\n}", "func RateLimit(r *http.Response) int {\n\treturn intResponseHeaderOrNegOne(r, \"X-RateLimit-Limit\")\n}", "func TestRateLimit(t *testing.T) {\n\tvalidate := func(desc string, msgType notification.MessageType, destType notification.DestType, _times ...time.Time) {\n\t\tt.Helper()\n\t\tt.Run(desc, func(t *testing.T) {\n\t\t\tfor i := 2; i <= len(_times); i++ {\n\t\t\t\ttimes := _times[:i]\n\t\t\t\tlast := times[len(times)-1]\n\t\t\t\tth := message.NewThrottle(message.PerCMThrottle, last, false)\n\t\t\t\tfor _, tm := range times[:len(times)-1] {\n\t\t\t\t\tth.Record(message.Message{Type: msgType, SentAt: tm, Dest: notification.Dest{Type: destType}})\n\t\t\t\t}\n\t\t\t\tassert.Falsef(t, th.InCooldown(message.Message{Type: msgType, Dest: notification.Dest{Type: destType}}), \"message #%d should not be in cooldown\", i)\n\t\t\t}\n\t\t})\n\t}\n\n\tvalidate(\"alert-voice\",\n\t\tnotification.MessageTypeAlert, notification.DestTypeVoice,\n\n\t\t// {Count: 3, Per: 15 * time.Minute},\n\t\t// {Count: 7, Per: time.Hour, Smooth: true},\n\t\t// {Count: 15, Per: 3 * time.Hour, Smooth: true},\n\n\t\ttime.Date(2015, time.May, 1, 0, 0, 0, 0, time.UTC),\n\t\ttime.Date(2015, time.May, 1, 0, 1, 0, 0, time.UTC),\n\t\ttime.Date(2015, time.May, 1, 0, 2, 0, 0, time.UTC), // 15 min limit; 13 minute gap max\n\n\t\ttime.Date(2015, time.May, 1, 0, 15, 0, 0, time.UTC), // 15 min limit expired for first message\n\t\ttime.Date(2015, time.May, 1, 0, 26, 15, 0, time.UTC), // per hour rule active\n\t\ttime.Date(2015, time.May, 1, 0, 37, 30, 0, time.UTC), // 11.25 min max gap for hour\n\t\ttime.Date(2015, time.May, 1, 0, 48, 45, 0, time.UTC),\n\n\t\ttime.Date(2015, time.May, 1, 1, 0, 0, 0, time.UTC), // start of three hour window\n\t\ttime.Date(2015, time.May, 1, 1, 15, 0, 0, time.UTC),\n\t\ttime.Date(2015, time.May, 1, 1, 30, 0, 0, time.UTC),\n\t\ttime.Date(2015, time.May, 1, 1, 45, 0, 0, time.UTC),\n\t\ttime.Date(2015, time.May, 1, 2, 0, 0, 0, time.UTC),\n\t\ttime.Date(2015, time.May, 1, 2, 15, 0, 0, time.UTC),\n\t\ttime.Date(2015, time.May, 1, 2, 30, 0, 0, time.UTC),\n\t\ttime.Date(2015, time.May, 1, 2, 45, 0, 0, time.UTC),\n\t\ttime.Date(2015, time.May, 1, 3, 0, 0, 0, time.UTC),\n\n\t\ttime.Date(2015, time.May, 1, 3, 1, 0, 0, time.UTC), // out of window\n\t)\n\n\tvalidate(\"alert-voice-staggered\",\n\t\tnotification.MessageTypeAlert, notification.DestTypeVoice,\n\n\t\t// {Count: 3, Per: 15 * time.Minute},\n\t\t// {Count: 7, Per: time.Hour, Smooth: true},\n\t\t// {Count: 15, Per: 3 * time.Hour, Smooth: true},\n\n\t\ttime.Date(2021, 7, 9, 2, 18, 20, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 3, 34, 25, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 4, 6, 25, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 4, 7, 30, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 4, 8, 35, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 4, 21, 28, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 4, 34, 30, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 5, 27, 25, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 5, 28, 33, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 6, 54, 40, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 7, 7, 31, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 7, 16, 40, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 7, 21, 30, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 7, 34, 35, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 8, 19, 40, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 8, 27, 28, 0, time.UTC),\n\t\ttime.Date(2021, 7, 9, 8, 37, 0, 0, time.UTC),\n\n\t\ttime.Date(2021, 7, 9, 8, 37+1, 0, 0, time.UTC),\n\t)\n}", "func (ctx *Context) RateLimitHandler(parent http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t<-ctx.rateLimit\n\t\tdefer func() {\n\t\t\tctx.rateLimit <- struct{}{}\n\t\t}()\n\t\tparent.ServeHTTP(w, r)\n\t})\n}", "func main() {\n\tvar limiter *ratelimit.Bucket\n\tlimiter = ratelimit.NewBucket(time.Second, 10)\n\tfor i := 0; i < 100; i++ {\n\t\tfmt.Println(limiter.TakeAvailable(1))\n\t\tif i%10 == 0 {\n\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t}\n\t}\n}", "func (_IncreasingPriceCrowdsale *IncreasingPriceCrowdsaleCaller) Rate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _IncreasingPriceCrowdsale.contract.Call(opts, out, \"rate\")\n\treturn *ret0, err\n}", "func MaxSamplingRate(r int) middleware.TraceOption {\n\treturn middleware.MaxSamplingRate(r)\n}", "func (bas *BaseService) SetRateLimit(persec int) {\n\tbas.rlock.Lock()\n\tdefer bas.rlock.Unlock()\n\n\tif persec == 0 {\n\t\tbas.rlimit = nil\n\t\treturn\n\t}\n\n\tbas.rlimit = ratelimit.New(persec, ratelimit.WithoutSlack)\n}", "func (c *metricMetadataAPI) MaximumLiveRequests() int {\n\treturn cap(c.backgroundQueue)\n}", "func (_Authority *AuthorityCaller) MaxTimeToUpload(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Authority.contract.Call(opts, out, \"maxTimeToUpload\")\n\treturn *ret0, err\n}", "func (ps *rateLimiter) TargetRate() float64 {\n\tps.mu.RLock()\n\trate := ps.stats.TargetRate\n\tps.mu.RUnlock()\n\treturn rate\n}", "func (a *AQM) Limit() bm.HandlerFunc {\n\treturn func(c *bm.Context) {\n\t\tdone, err := a.limiter.Allow(c)\n\t\tif err != nil {\n\t\t\tstats.Incr(_family, c.Request.URL.Path[1:])\n\t\t\t// TODO: priority request.\n\t\t\t// c.JSON(nil, err)\n\t\t\t// c.Abort()\n\t\t\treturn\n\t\t}\n\t\tdefer func() {\n\t\t\tif c.Error != nil && !ecode.Deadline.Equal(c.Error) && c.Err() != context.DeadlineExceeded {\n\t\t\t\tdone(rate.Ignore)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdone(rate.Success)\n\t\t}()\n\t\tc.Next()\n\t}\n}", "func RateLimiter(next http.RoundTripper) http.RoundTripper {\n\treturn &ratelimiter{\n\t\trt: next,\n\t\tlm: sync.Map{},\n\t}\n}", "func ExchangeRate(request []string) (float64, error) {\n\tcoinId, err := strconv.ParseUint(request[0], 10, 64)\n\tif err != nil {\n\t\treturn 0.00, errors.New(\"Invalid coinid format\")\n\t}\n\n\twtmClient := NewWhatToMineClient(nil, BASE, userAgent)\n\twtmClient.SetDebug(debug)\n\tstatus, err := wtmClient.GetCoin(coinId, 1000000, 0, 0)\n\tif err != nil {\n\t\treturn 0.00, err\n\t}\n\treturn status.ExchangeRate, nil\n}", "func NewRateLimiter(intervalInMillis int64, maxInInterval int, client *redis.Client) *RateLimiter {\n\treturn &RateLimiter{\n\t\tintervalInMillis: intervalInMillis,\n\t\tmaxInInterval: maxInInterval,\n\t\tclient: client,\n\t}\n}", "func (r *Ratelimit) Limited(key string, max int64) (bool, error) {\n\t// TODO make it possible to use a prate limit per minute, hour or day\n\t// minute is 04\n\thour := time.Now().Format(\"15\")\n\tk := key + \":\" + hour\n\n\ts, err := r.redis.GetInt64(k)\n\tif err != nil {\n\t\t// fail closed so if redis is down we don't run without rate limit enforcement\n\t\treturn true, err\n\t}\n\n\tif s == -1 {\n\t\tr.log.Printf(\"%s is not set\", k)\n\t} else {\n\t\tr.log.Printf(\"%s is %d\", k, s)\n\t\tif s > max {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\ti, err := r.redis.Incr(k)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tok, err := r.redis.Expire(k, time.Minute)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif !ok {\n\t\tr.log.Printf(\"failed to set expiration on %s\", k)\n\t}\n\n\treturn i <= max, nil\n}", "func (o LookupQueueResultOutput) RateLimits() RateLimitsResponseOutput {\n\treturn o.ApplyT(func(v LookupQueueResult) RateLimitsResponse { return v.RateLimits }).(RateLimitsResponseOutput)\n}", "func NewRateLimit(limit int, deltat time.Duration) *RateLimit {\n\treturn &RateLimit{Rate{NewCounter(0), deltat}, limit, time.Now()}\n}", "func (rl *redisRateLimiter) RateLimit(ctx gocontext.Context, name string, maxCalls uint64, per time.Duration) (bool, error) {\n\tif trace.FromContext(ctx) != nil {\n\t\tvar span *trace.Span\n\t\tctx, span = trace.StartSpan(ctx, \"Redis.RateLimit\")\n\t\tdefer span.End()\n\t}\n\n\tpoolCheckoutStart := time.Now()\n\n\tconn := rl.pool.Get()\n\tdefer conn.Close()\n\n\tcontext.TimeSince(ctx, \"rate_limit_redis_pool_wait\", poolCheckoutStart)\n\n\tif trace.FromContext(ctx) != nil {\n\t\tvar span *trace.Span\n\t\tctx, span = trace.StartSpan(ctx, \"Redis.RateLimit.WithPool\")\n\t\tdefer span.End()\n\t}\n\n\tif rl.dynamicConfig {\n\t\terr := rl.loadDynamicConfig(ctx, conn, name, &maxCalls, &per)\n\t\tif err != nil && err != redis.ErrNil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\tnow := time.Now()\n\ttimestamp := now.Unix() - (now.Unix() % int64(per.Seconds()))\n\n\tkey := fmt.Sprintf(\"%s:%s:%d\", rl.prefix, name, timestamp)\n\n\tcur, err := redis.Int64(conn.Do(\"GET\", key))\n\tif err != nil && err != redis.ErrNil {\n\t\treturn false, err\n\t}\n\n\tif err != redis.ErrNil && uint64(cur) >= maxCalls {\n\t\treturn false, nil\n\t}\n\n\t_, err = conn.Do(\"WATCH\", key)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tconnSend := func(commandName string, args ...interface{}) {\n\t\tif err != nil && err != redis.ErrNil {\n\t\t\treturn\n\t\t}\n\t\terr = conn.Send(commandName, args...)\n\t}\n\tconnSend(\"MULTI\")\n\tconnSend(\"INCR\", key)\n\tconnSend(\"EXPIRE\", key, int64(per.Seconds()))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treply, err := conn.Do(\"EXEC\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif reply == nil {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}", "func (o BackendOutput) MaxRate() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v Backend) *int { return v.MaxRate }).(pulumi.IntPtrOutput)\n}", "func TestLimiter_Accuracy(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"Skipping Limiter Allow test in short testing mode.\")\n\t}\n\t// 2 ^ 15 = 32768, Highest rate will be 32768Hz\n\tfor pow := 0; pow < 15; pow++ {\n\t\trate := ratelimiter.Frequency(math.Pow(2,float64(pow)))\n\t\tlimiter, err := ratelimiter.NewLimiter(rate, 1)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unexpected error creating limiter for testing: %s\", err.Error())\n\t\t}\n\t\tallowCount := 0\n\t\t// 1 / 32768 = 30.5175781e-6 seconds, we need to oversample to have any chance of making an accurate test\n\t\t// So we sample the Limiter's Allow method appoximately 8 times for every time the token will be replenished\n\t\tticker := time.NewTicker(time.Nanosecond * 30 / 8)\n\t\tgo func() {\n\t\t\tfor range ticker.C {\n\t\t\t\tif limiter.Allow() {\n\t\t\t\t\tallowCount++\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\ttestLength := 3\n\t\ttime.Sleep(time.Second * time.Duration(testLength))\n\t\texpectedAllowCount := int(rate) * testLength\n\t\tdiff := math.Abs(float64(allowCount)-float64(expectedAllowCount))\n\t\taccuracy := 100.0 - diff / float64(expectedAllowCount) * 100\n\t\tt.Logf(\"Rate: %f, Allows: %d, Expected Allows: %d, Accuracy: %f%%\", rate, allowCount, expectedAllowCount, accuracy)\n\t}\n}", "func (_FinalizableCrowdsaleImpl *FinalizableCrowdsaleImplCaller) Rate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _FinalizableCrowdsaleImpl.contract.Call(opts, out, \"rate\")\n\treturn *ret0, err\n}", "func NewRateLimiter(r float64, b int) *RateLimiter {\n\treturn &RateLimiter{limiter: rate.NewLimiter(rate.Limit(r), b)}\n}", "func NewRateLimiter(max float64, purgeDuration time.Duration) RateLimiter {\n\trl := RateLimiter{}\n\n\tif purgeDuration == 0 {\n\t\trl = RateLimiter{\n\t\t\ttollbooth.NewLimiter(max, nil),\n\t\t\tfalse,\n\t\t}\n\t} else {\n\t\trl = RateLimiter{\n\t\t\ttollbooth.NewLimiter(max, &limiter.ExpirableOptions{DefaultExpirationTTL: purgeDuration}),\n\t\t\tfalse,\n\t\t}\n\t}\n\n\trl.Limiter.SetIPLookups([]string{\"X-Forwarded-For\", \"RemoteAddr\", \"X-Real-IP\"})\n\n\treturn rl\n}", "func (_PBridge *PBridgeCaller) Rate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _PBridge.contract.Call(opts, &out, \"rate\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (h *handler) RateLimitTest(c *gin.Context) {\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"status\": 200,\n\t\t\"message\": \"Success\",\n\t})\n}", "func formatRate(r rate.Limit) string {\n\tif r == 0 {\n\t\t// \"500.00/s 2.00ms\"\n\t\treturn \" ?.??/s ?.??µs\"\n\t}\n\n\td := metrics.RateToDuration(r)\n\n\treturn fmt.Sprintf(\n\t\t\"%6.02f/s %s\",\n\t\tr,\n\t\tformatDuration(d),\n\t)\n}", "func ConfigRateLimits() {\n\tuserRl := viper.GetFloat64(\"network.user_handlers.rate_limit\")\n\tuserRateLimit = &ratelimit{RequestsPerSecond: userRl}\n\tuserRateLimit.init()\n\n\tn2nRl := viper.GetFloat64(\"network.n2n_handlers.rate_limit\")\n\tn2nRateLimit = &ratelimit{RequestsPerSecond: n2nRl}\n\tn2nRateLimit.init()\n}", "func NewQuotaRateLimit(ctx *pulumi.Context,\n\tname string, args *QuotaRateLimitArgs, opts ...pulumi.ResourceOption) (*QuotaRateLimit, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Rate == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Rate'\")\n\t}\n\tvar resource QuotaRateLimit\n\terr := ctx.RegisterResource(\"vault:index/quotaRateLimit:QuotaRateLimit\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (ps *rateLimiter) RealRate() float64 {\n\tps.mu.RLock()\n\tdefer ps.mu.RUnlock()\n\treturn ps.realRateLocked()\n}", "func GetGoodBurst(l rate.Limit) int {\n\tif l == rate.Limit(0) {\n\t\treturn MaxBurstSize\n\t}\n\t// We aim for 20 bursts per second to get good precision. Decrease this\n\t// value to get better performance, but less precision.\n\tburstSize := int64(l) / 20\n\tif burstSize < MinBurstSize {\n\t\tburstSize = MinBurstSize\n\t} else if burstSize > MaxBurstSize {\n\t\tburstSize = MaxBurstSize\n\t}\n\treturn int(burstSize)\n}", "func (s *Strava) GetRateLimits() (requestTime time.Time, limitShort, limitLong, usageShort, usageLong int) {\n\trateLimiting := strava.RateLimiting\n\treturn rateLimiting.RequestTime, rateLimiting.LimitShort, rateLimiting.LimitLong, rateLimiting.UsageShort, rateLimiting.UsageLong\n}", "func Rate(ctx context.Context, rpcURL string, contract common.Address) (*big.Int, error) {\n\tgc, err := goclient.Dial(rpcURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp, err := NewIGOFS(contract, gc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p.Rate(&bind.CallOpts{Context: ctx})\n}", "func NewRateLimiter(limit int64) *limiter {\n\treturn &limiter{\n\t\tstart: time.Now(),\n\t\tlimit: limit,\n\t\tdelay: 0.5,\n\t}\n}", "func New(c *aqm.Config) *Limiter {\n\tl := &Limiter{\n\t\trate: vegas.New(),\n\t\tqueue: aqm.New(c),\n\t}\n\tgo func() {\n\t\tticker := time.NewTicker(time.Second * 1)\n\t\tdefer ticker.Stop()\n\t\tfor {\n\t\t\t<-ticker.C\n\t\t\tv := l.rate.Stat()\n\t\t\tq := l.queue.Stat()\n\t\t\tlog.Info(\"rate/limit: limit(%d) inFlight(%d) minRtt(%v) rtt(%v) codel packets(%d)\", v.Limit, v.InFlight, v.MinRTT, v.LastRTT, q.Packets)\n\t\t}\n\t}()\n\treturn l\n}", "func (c *Stats) Rate(name string, value float64, tags []string) {\n\tselect {\n\tcase c.jobs <- &job{metric: &metric{\n\t\tname: name,\n\t\tclass: client.Rate,\n\t\tvalue: value,\n\t\ttags: tags,\n\t}}:\n\tdefault:\n\t\tatomic.AddUint64(&c.dropped, 1)\n\t}\n}", "func (_IndividuallyCappedCrowdsaleImpl *IndividuallyCappedCrowdsaleImplCaller) Rate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _IndividuallyCappedCrowdsaleImpl.contract.Call(opts, out, \"rate\")\n\treturn *ret0, err\n}", "func (r *Request) Limit(value int64) *Request {\n\tr.UnderlyingRequest.Limit(value)\n\treturn r\n}", "func (o UsagePlanThrottleSettingsPtrOutput) RateLimit() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v *UsagePlanThrottleSettings) *float64 {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.RateLimit\n\t}).(pulumi.Float64PtrOutput)\n}", "func (_IncreasingPriceCrowdsaleImpl *IncreasingPriceCrowdsaleImplSession) Rate() (*big.Int, error) {\n\treturn _IncreasingPriceCrowdsaleImpl.Contract.Rate(&_IncreasingPriceCrowdsaleImpl.CallOpts)\n}", "func (m *RateLimitedMux) rateLimit(c web.C, w http.ResponseWriter, r *http.Request, limits []int, handler web.Handler) {\n\tif m.limiter == nil || r.Header.Get(IsAdminHeader) == IsAdminHeaderValue {\n\t\thandler.ServeHTTPC(c, w, r)\n\t\treturn\n\t}\n\n\tlimit := 0\n\tfor _, v := range limits {\n\t\tlimit += v\n\t}\n\n\tif limit == 0 {\n\t\thandler.ServeHTTPC(c, w, r)\n\t\treturn\n\t}\n\n\tkey := r.Header.Get(signcontrol.PublicKeyHeader)\n\n\tlimited, context, err := m.limiter.RateLimit(key, limit)\n\n\tif err != nil {\n\t\tlog.WithField(\"service\", \"rate-limiter\").WithError(err).Error(\"failed to rate limit\")\n\t\thandler.ServeHTTPC(c, w, r)\n\t\treturn\n\t}\n\n\tif v := context.Limit; v >= 0 {\n\t\tw.Header().Add(\"X-RateLimit-Limit\", strconv.Itoa(v))\n\t}\n\n\tif v := context.Remaining; v >= 0 {\n\t\tw.Header().Add(\"X-RateLimit-Remaining\", strconv.Itoa(v))\n\t}\n\n\tif v := context.ResetAfter; v >= 0 {\n\t\tvi := int(math.Ceil(v.Seconds()))\n\t\tw.Header().Add(\"X-RateLimit-Reset\", strconv.Itoa(vi))\n\t}\n\n\tif v := context.RetryAfter; v >= 0 {\n\t\tvi := int(math.Ceil(v.Seconds()))\n\t\tw.Header().Add(\"Retry-After\", strconv.Itoa(vi))\n\t}\n\n\tif !limited {\n\t\thandler.ServeHTTPC(c, w, r)\n\t} else {\n\t\tproblem.Render(nil, w, &problem.RateLimitExceeded)\n\t\treturn\n\t}\n\n}", "func (o BackendResponseOutput) MaxRatePerInstance() pulumi.Float64Output {\n\treturn o.ApplyT(func(v BackendResponse) float64 { return v.MaxRatePerInstance }).(pulumi.Float64Output)\n}", "func NewRateLimit(client curator.CuratorFramework, username string,\n\ttotalAllowedQuota, baseQuota int64, lockTimeout time.Duration, refreshWindow time.Duration,\n\tenableOptimization bool, optimizationPctAsk float64, optimizationPctLeft float64) (*RateLimit, error) {\n\tvar err error\n\trl := &RateLimit{\n\t\tusername: username,\n\t\ttotalAllowedQuota: totalAllowedQuota,\n\t\tusableQuotaLeft: totalAllowedQuota,\n\t\tbaseQuota: baseQuota,\n\t\tlockTimeout: lockTimeout,\n\t\trefreshWindow: refreshWindow,\n\t\tclient: client,\n\t\tbaseQuotaPath: prefix + \"/\" + username + baseSuffix,\n\t\tusableQuotaPath: prefix + \"/\" + username + usableSuffix,\n\t\ttotalQuotaPath: prefix + \"/\" + username + totalSuffix,\n\t\trefreshQuotaPath: prefix + \"/\" + username + refreshSuffix,\n\t\toptimizationPctAsk: optimizationPctAsk,\n\t\toptimizationPctLeft: optimizationPctLeft,\n\t\tenableOptimization: enableOptimization,\n\t}\n\n\t// initialize the lock to be used and inject it wherever required.\n\trl.lock, err = recipe.NewInterProcessMutex(rl.client, lockPath+username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(prefix, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(prefix+\"/\"+rl.username, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.baseQuotaPath, []byte(strconv.FormatInt(rl.baseQuota, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.totalQuotaPath, []byte(strconv.FormatInt(rl.totalAllowedQuota, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.usableQuotaPath, []byte(strconv.FormatInt(rl.usableQuotaLeft, 10)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.create(rl.refreshQuotaPath, []byte(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = rl.addWatch()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// concurrently look to refresh quota\n\tgo rl.refreshQuota()\n\t// mimic user requests being processed with random size\n\tgo rl.startRequests()\n\t// just in case there is skewness observed through loadbalancer and\n\t// quota gets concentrated on a single rate limit node\n\tgo rl.relinquish()\n\n\treturn rl, nil\n}", "func (_IncreasingPriceCrowdsaleImpl *IncreasingPriceCrowdsaleImplCallerSession) Rate() (*big.Int, error) {\n\treturn _IncreasingPriceCrowdsaleImpl.Contract.Rate(&_IncreasingPriceCrowdsaleImpl.CallOpts)\n}", "func NewRateLimiter(freq time.Duration, burstSize int) *Limiter {\n\treturn &Limiter{\n\t\tconnectionFreq: freq,\n\t\tconnectionBurstSize: burstSize,\n\t}\n}", "func (r *Request) Limit(value int64) *Request {\n\treturn r.WithParam(common.ModifierLimit, strconv.FormatInt(value, 10))\n}", "func NewLimiter(rate float64, burst float64, initialTokens float64) *Limiter {\n\treturn &Limiter{\n\t\trate: rate,\n\t\tburst: burst,\n\t\ttokens: initialTokens,\n\t\tlast: time.Now(),\n\t}\n}", "func (_Authority *AuthorityCallerSession) MaxTimeToUpload() (*big.Int, error) {\n\treturn _Authority.Contract.MaxTimeToUpload(&_Authority.CallOpts)\n}", "func (m *mTOServiceItem) SetRate(val int64) {\n\tm.rateField = val\n}", "func (j *JuiceFSEngine) getQuota(v string) (int64, error) {\n\tq, err := resource.ParseQuantity(v)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"invalid quota %s: %v\", v, err)\n\t}\n\tqs := q.Value() / 1024 / 1024 / 1024\n\tif qs <= 0 {\n\t\treturn 0, fmt.Errorf(\"quota %s is too small, at least 1GiB for quota\", v)\n\t}\n\n\treturn qs, nil\n}", "func (_RefundableCrowdsale *RefundableCrowdsaleCaller) Rate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _RefundableCrowdsale.contract.Call(opts, out, \"rate\")\n\treturn *ret0, err\n}" ]
[ "0.6884591", "0.67138076", "0.6626268", "0.6499497", "0.6490157", "0.64747286", "0.6463776", "0.64438576", "0.63415706", "0.6335022", "0.6331239", "0.631643", "0.6298596", "0.6294876", "0.61940026", "0.6183884", "0.61823803", "0.6159726", "0.6142608", "0.60829914", "0.60238254", "0.6005478", "0.5942836", "0.5940865", "0.5890777", "0.58670014", "0.5857393", "0.5851308", "0.5851308", "0.5847675", "0.5823308", "0.58221287", "0.58221287", "0.58020407", "0.57998174", "0.57858324", "0.57487124", "0.5738496", "0.5738432", "0.5737562", "0.5734067", "0.57137245", "0.57111615", "0.5692684", "0.5691868", "0.5691803", "0.5690393", "0.568818", "0.56863844", "0.56778914", "0.5655628", "0.5653405", "0.5641006", "0.5631969", "0.56222636", "0.56216305", "0.56195176", "0.56154907", "0.5608304", "0.56070125", "0.5598038", "0.5588597", "0.55847013", "0.5577156", "0.55708694", "0.55681175", "0.5566669", "0.55663604", "0.5557349", "0.5555636", "0.5548029", "0.553547", "0.5530798", "0.5522053", "0.550558", "0.55033493", "0.5502947", "0.54833186", "0.5476903", "0.54630905", "0.5461365", "0.5447058", "0.54456043", "0.5444641", "0.543752", "0.5432616", "0.5428564", "0.5410608", "0.5396352", "0.5391488", "0.5385701", "0.53856397", "0.5382378", "0.5380888", "0.5357955", "0.5355516", "0.53527915", "0.535076", "0.5349437", "0.534787" ]
0.62991774
12
NewEC2RemoteClient creates and initialise a new EC2RemoteClient object, given an AWS Instance ID
func NewEC2RemoteClient(InstanceID *string, credentials *sshCmdClient.SSHCredentials) (*EC2RemoteClient, error) { ins := new(EC2RemoteClient) ins.InstanceID = *InstanceID session, err := session.NewSession() if err != nil { return nil, err } ec2Client := ec2.New(session) ins.session = session ins.ec2Client = ec2Client ins.sshCredentials = credentials err = ins.makeReady() return ins, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewEC2Client(config EC2ClientConfig) (*AwsEC2, error) {\n\tif config.ControllerID == \"\" {\n\t\treturn nil, fmt.Errorf(\"ControllerID is a required parameter\")\n\t}\n\tif config.Nametag == \"\" {\n\t\treturn nil, fmt.Errorf(\"Nametag is a required parameter\")\n\t}\n\tec2Client, err := getEC2Client(config.EndpointURL, config.InsecureTLSSkipVerify)\n\tif err != nil {\n\t\treturn nil, util.WrapError(err, \"Error creating EC2 client\")\n\t}\n\tvar ecsClient *ecs.ECS\n\tif config.ECSClusterName != \"\" {\n\t\tecsClient, err = getECSClient(config.EndpointURL, config.InsecureTLSSkipVerify)\n\t\tif err != nil {\n\t\t\treturn nil, util.WrapError(err, \"Error creating ECS client\")\n\t\t}\n\t}\n\tssmClient, err := getSSMClient(config.EndpointURL, config.InsecureTLSSkipVerify)\n\tif err != nil {\n\t\treturn nil, util.WrapError(err, \"creating SSM client\")\n\t}\n\tiamClient, err := getIAMClient(config.EndpointURL, config.InsecureTLSSkipVerify)\n\tif err != nil {\n\t\treturn nil, util.WrapError(err, \"creating IAM client\")\n\t}\n\tclient := &AwsEC2{\n\t\tclient: ec2Client,\n\t\tecs: ecsClient,\n\t\tssm: ssmClient,\n\t\tiam: iamClient,\n\t\tecsClusterName: config.ECSClusterName,\n\t\tcontrollerID: config.ControllerID,\n\t\tnametag: config.Nametag,\n\t}\n\tclient.vpcID, client.vpcCIDR, err = client.assertVPCExists(config.VPCID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient.subnetID = config.SubnetID\n\tif client.subnetID == \"\" {\n\t\tclient.subnetID, err = detectCurrentSubnet()\n\t\tif err != nil {\n\t\t\treturn nil, util.WrapError(err, \"Could not detect current subnet from metadata service. Please supply an AWS subnet id in provider.yaml\")\n\t\t}\n\t}\n\tclient.region = os.Getenv(\"AWS_REGION\")\n\n\tsubnetAttrs, err := client.getSubnetAttributes(client.subnetID)\n\tif err != nil {\n\t\treturn nil, util.WrapError(err, \"Error getting subnet attributes\")\n\t}\n\tclient.availabilityZone = subnetAttrs.AZ\n\tclient.usePublicIPs = !config.PrivateIPOnly\n\tif subnetAttrs.AddressAffinity == cloud.PrivateAddress {\n\t\tklog.V(2).Infoln(\"cells will run in a private subnet (no route to internet gateway)\")\n\t\tclient.usePublicIPs = false\n\t}\n\treturn client, nil\n}", "func CreateEC2Client(credentials *credentials.Credentials, region string) (*ec2.EC2, error) {\n\tsess, err := session.NewSession(&aws.Config{\n\t\tCredentials: credentials,\n\t\tRegion: &region,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ec2.New(sess), nil\n}", "func NewClient(config Config) (Client, error) {\n\tuuid.SetNodeID([]byte(fmt.Sprintf(\"%s:%s\", config.AppID, config.InstanceID)))\n\tconns := connection.NewManager()\n\tsubConn, err := conns.Connect(fmt.Sprintf(\"%s:%d\", config.SubscriptionService.GetHost(), config.SubscriptionService.GetPort()))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\te2tConn, err := conns.Connect(fmt.Sprintf(\"%s:%d\", config.E2TService.GetHost(), config.E2TService.GetPort()))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &e2Client{\n\t\tconfig: config,\n\t\tepClient: endpoint.NewClient(subConn),\n\t\tsubClient: subscription.NewClient(subConn),\n\t\ttaskClient: subscriptiontask.NewClient(subConn),\n\t\tterminationClient: termination.NewClient(e2tConn),\n\t\tconns: conns,\n\t}, nil\n}", "func GetEc2Client(credConfig *cred.Config) (*ec2.EC2, error) {\n\tconfig, err := GetAWSCredentialConfig(credConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tec2Session := session.Must(session.NewSession())\n\treturn ec2.New(ec2Session, config), nil\n}", "func NewRemoteClient(config *Config) *Client {\n\tif config == nil {\n\t\tconfig = &Config{}\n\t}\n\n\tclient := api.NewShell(config.Host)\n\thost := config.Host\n\tif host == \"\" {\n\t\tvar err error\n\t\thost, err = getIpfsAPIURL()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\treturn &Client{\n\t\tclient: client,\n\t\tisRemote: true,\n\t\thost: host,\n\t\tgatewayURL: config.GatewayURL,\n\t}\n}", "func NewAwsClient() (*AwsClient, error) {\n\n\ts, err := session.NewSession(&aws.Config{\n\t\tMaxRetries: aws.Int(0),\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to connect to AWS metadata service: %s\", err)\n\t}\n\n\tmd := ec2metadata.New(s)\n\tidDoc, err := md.GetInstanceIdentityDocument()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to GetInstanceIdentityDocument: %s\", err)\n\t}\n\tclient := ec2.New(s, aws.NewConfig().WithRegion(idDoc.Region))\n\n\tlogrus.Debug(\"NewAwsClient built\")\n\treturn &AwsClient{\n\t\taws: client,\n\t\tinstanceID: idDoc.InstanceID,\n\t\tprivateIP: idDoc.PrivateIP,\n\t\tnicIPtoID: make(map[string]string),\n\t}, nil\n}", "func NewClient(config ClientConfiguration) *Client {\n\tout := &Client{\n\t\tPort: 22,\n\t\tUser: \"ec2-user\",\n\t}\n\tif config.Host != \"\" {\n\t\tout.Host = config.Host\n\t}\n\tif config.Port != 0 {\n\t\tout.Port = config.Port\n\t}\n\tif config.User != \"\" {\n\t\tout.User = config.User\n\t}\n\tif config.PrivateKeyFile != \"\" {\n\t\tout.PrivateKeyFile = config.PrivateKeyFile\n\t}\n\treturn out\n}", "func NewClient(accessKeyID, secretAccessKey, region string) ClientInterface {\n\tvar (\n\t\tawsConfig = &aws.Config{\n\t\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\t}\n\t\tsess = session.Must(session.NewSession(awsConfig))\n\t\tconfig = &aws.Config{Region: aws.String(region)}\n\t)\n\n\treturn &Client{\n\t\tEC2: ec2.New(sess, config),\n\t\tELB: elb.New(sess, config),\n\t\tSTS: sts.New(sess, config),\n\t}\n}", "func NewClient(accessKeyID, secretAccessKey, region string) (*Client, error) {\n\tvar (\n\t\tawsConfig = &aws.Config{\n\t\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t\t}\n\t\tconfig = &aws.Config{Region: aws.String(region)}\n\t)\n\n\ts, err := session.NewSession(awsConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{\n\t\tEC2: ec2.New(s, config),\n\t\tELB: elb.New(s, config),\n\t\tELBv2: elbv2.New(s, config),\n\t\tIAM: iam.New(s, config),\n\t\tSTS: sts.New(s, config),\n\t\tS3: s3.New(s, config),\n\t}, nil\n}", "func (*SDKGetter) EC2(session *session.Session) EC2Interface {\n\treturn ec2svc.NewService(ec2.New(session))\n}", "func (b *backend) clientEC2(ctx context.Context, s logical.Storage, region, accountID string) (*ec2.EC2, error) {\n\tstsRole, err := b.stsRoleForAccount(ctx, s, accountID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.configMutex.RLock()\n\tif b.EC2ClientsMap[region] != nil && b.EC2ClientsMap[region][stsRole] != nil {\n\t\tdefer b.configMutex.RUnlock()\n\t\t// If the client object was already created, return it\n\t\treturn b.EC2ClientsMap[region][stsRole], nil\n\t}\n\n\t// Release the read lock and acquire the write lock\n\tb.configMutex.RUnlock()\n\tb.configMutex.Lock()\n\tdefer b.configMutex.Unlock()\n\n\t// If the client gets created while switching the locks, return it\n\tif b.EC2ClientsMap[region] != nil && b.EC2ClientsMap[region][stsRole] != nil {\n\t\treturn b.EC2ClientsMap[region][stsRole], nil\n\t}\n\n\t// Create an AWS config object using a chain of providers\n\tvar awsConfig *aws.Config\n\tawsConfig, err = b.getClientConfig(ctx, s, region, stsRole, accountID, \"ec2\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif awsConfig == nil {\n\t\treturn nil, fmt.Errorf(\"could not retrieve valid assumed credentials\")\n\t}\n\n\t// Create a new EC2 client object, cache it and return the same\n\tclient := ec2.New(session.New(awsConfig))\n\tif client == nil {\n\t\treturn nil, fmt.Errorf(\"could not obtain ec2 client\")\n\t}\n\tif _, ok := b.EC2ClientsMap[region]; !ok {\n\t\tb.EC2ClientsMap[region] = map[string]*ec2.EC2{stsRole: client}\n\t} else {\n\t\tb.EC2ClientsMap[region][stsRole] = client\n\t}\n\n\treturn b.EC2ClientsMap[region][stsRole], nil\n}", "func NewClient(config *config.Config) *Client {\n\tclient := &Client{\n\t\tConfig: config,\n\t\telbv2Svc: map[string]*elbv2.ELBV2{},\n\t\tecsSvc: map[string]*ecs.ECS{},\n\t}\n\n\tfor service := range config.Services {\n\t\tsession := session.New(&aws.Config{\n\t\t\tRegion: aws.String(config.GetRegion(service)),\n\t\t})\n\n\t\tclient.elbv2Svc[service] = elbv2.New(session)\n\t\tclient.ecsSvc[service] = ecs.New(session)\n\t}\n\n\treturn client\n}", "func NewEC2Session() (*EC2Client, error) {\n\tsess, err := session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(sessionError)\n\t\treturn nil, err\n\t}\n\tsvc := ec2.New(sess)\n\treturn &EC2Client{\n\t\tEC2API: svc,\n\t\tworkers: 1, //default workers count\n\t}, nil\n}", "func NewClient(secretId, secretKey, region string) *Client {\n\tendpoint := os.Getenv(\"CVM_ENDPOINT\")\n\tif endpoint == \"\" {\n\t\tendpoint = CVMDefaultEndpoint\n\t}\n\treturn NewClientWithEndpoint(endpoint, secretId, secretKey, region)\n}", "func NewEc2Instance(ctx sdutils.AppContext, dd *awsDeploymentDescription) (*Ec2Instance, error) {\n\tvar err error\n\tcustomData := \"\"\n\tif dd.customPropFile != \"\" {\n\t\tdata, err := ioutil.ReadFile(dd.customPropFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid custom properties file: %s\", err)\n\t\t}\n\t\tcustomData = string(data)\n\t}\n\n\tcustomLog4J := \"\"\n\tif dd.customLog4J != \"\" {\n\t\tlog4JData, err := ioutil.ReadFile(dd.customLog4J)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid custom properties file: %s\", err)\n\t\t}\n\t\tcustomLog4J = base64.StdEncoding.EncodeToString(log4JData)\n\t}\n\n\tvar envBuffer bytes.Buffer\n\tfor _, env := range dd.environment {\n\t\tenvBuffer.WriteString(fmt.Sprintf(\"export %s\\n\", env))\n\t}\n\t// The custom script cannot be null in terraform so make a temp one\n\tscriptData := []byte(\"#!/bin/bash\\nexit 0\\n\")\n\tif dd.CustomScript != \"\" {\n\t\tscriptData, err = ioutil.ReadFile(dd.CustomScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to read the script %s: %s\", dd.CustomScript, err.Error())\n\t\t}\n\t}\n\tbase64CustomScriptData := base64.StdEncoding.EncodeToString(scriptData)\n\tbase64CustomScriptPath := path.Join(dd.deployDir, \"custom-stardogscript.base64\")\n\terr = ioutil.WriteFile(base64CustomScriptPath, []byte(base64CustomScriptData), 0644)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to create the base 64 encoded custom script\")\n\t}\n\n\tscriptZkData := []byte(\"#!/bin/bash\\nexit 0\\n\")\n\tif dd.CustomZkScript != \"\" {\n\t\tscriptZkData, err = ioutil.ReadFile(dd.CustomZkScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to read the script %s: %s\", dd.CustomZkScript, err.Error())\n\t\t}\n\t}\n\tbase64CustomZkScriptData := base64.StdEncoding.EncodeToString(scriptZkData)\n\tbase64CustomZkScriptPath := path.Join(dd.deployDir, \"custom-zk-stardogscript.base64\")\n\terr = ioutil.WriteFile(base64CustomZkScriptPath, []byte(base64CustomZkScriptData), 0644)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to create the base 64 encoded custom zk script\")\n\t}\n\n\tinstance := Ec2Instance{\n\t\tDeploymentName: dd.Name,\n\t\tRegion: dd.Region,\n\t\tKeyName: dd.AwsKeyName,\n\t\tVersion: dd.Version,\n\t\tZkInstanceType: dd.ZkInstanceType,\n\t\tSdInstanceType: dd.SdInstanceType,\n\t\tAmiID: dd.AmiID,\n\t\tPrivateKey: dd.PrivateKeyPath,\n\t\tDeployDir: dd.deployDir,\n\t\tCustomScript: base64CustomScriptPath,\n\t\tCustomZkScript: base64CustomZkScriptPath,\n\t\tCtx: ctx,\n\t\tCustomPropsData: customData,\n\t\tCustomLog4JData: customLog4J,\n\t\tEnvironment: envBuffer.String(),\n\t}\n\tif dd.disableSecurity {\n\t\tinstance.StartOpts = \"--disable-security\"\n\t}\n\treturn &instance, nil\n}", "func New(awsConfig *aws.Config) *Client {\n\tctx := aws.BackgroundContext()\n\tsess := session.Must(session.NewSession(awsConfig))\n\tiam := iam.New(sess)\n\troute53 := route53.New(sess)\n\tec2 := ec2.New(sess)\n\treturn &Client{\n\t\tIAM: iam,\n\t\tRoute53: route53,\n\t\tEC2: ec2,\n\t\tContext: ctx,\n\t}\n}", "func NewRemote(endpoint string) model.SecretService {\n\treturn &plugin{endpoint}\n}", "func Ec2Client(region string) *ec2.EC2 {\n\treturn ec2.New(session.New(), aws.NewConfig().WithRegion(region))\n}", "func NewClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string, opts ...func(*client.Client)) *EC2Metadata {\n\tif !aws.BoolValue(cfg.EC2MetadataDisableTimeoutOverride) && httpClientZero(cfg.HTTPClient) {\n\t\t// If the http client is unmodified and this feature is not disabled\n\t\t// set custom timeouts for EC2Metadata requests.\n\t\tcfg.HTTPClient = &http.Client{\n\t\t\t// use a shorter timeout than default because the metadata\n\t\t\t// service is local if it is running, and to fail faster\n\t\t\t// if not running on an ec2 instance.\n\t\t\tTimeout: 1 * time.Second,\n\t\t}\n\t\t// max number of retries on the client operation\n\t\tcfg.MaxRetries = aws.Int(2)\n\t}\n\n\tif u, err := url.Parse(endpoint); err == nil {\n\t\t// Remove path from the endpoint since it will be added by requests.\n\t\t// This is an artifact of the SDK adding `/latest` to the endpoint for\n\t\t// EC2 IMDS, but this is now moved to the operation definition.\n\t\tu.Path = \"\"\n\t\tu.RawPath = \"\"\n\t\tendpoint = u.String()\n\t}\n\n\tsvc := &EC2Metadata{\n\t\tClient: client.New(\n\t\t\tcfg,\n\t\t\tmetadata.ClientInfo{\n\t\t\t\tServiceName: ServiceName,\n\t\t\t\tServiceID: ServiceName,\n\t\t\t\tEndpoint: endpoint,\n\t\t\t\tAPIVersion: \"latest\",\n\t\t\t},\n\t\t\thandlers,\n\t\t),\n\t}\n\n\t// token provider instance\n\ttp := newTokenProvider(svc, defaultTTL)\n\n\t// NamedHandler for fetching token\n\tsvc.Handlers.Sign.PushBackNamed(request.NamedHandler{\n\t\tName: fetchTokenHandlerName,\n\t\tFn: tp.fetchTokenHandler,\n\t})\n\t// NamedHandler for enabling token provider\n\tsvc.Handlers.Complete.PushBackNamed(request.NamedHandler{\n\t\tName: enableTokenProviderHandlerName,\n\t\tFn: tp.enableTokenProviderHandler,\n\t})\n\n\tsvc.Handlers.Unmarshal.PushBackNamed(unmarshalHandler)\n\tsvc.Handlers.UnmarshalError.PushBack(unmarshalError)\n\tsvc.Handlers.Validate.Clear()\n\tsvc.Handlers.Validate.PushBack(validateEndpointHandler)\n\n\t// Disable the EC2 Metadata service if the environment variable is set.\n\t// This short-circuits the service's functionality to always fail to send\n\t// requests.\n\tif strings.ToLower(os.Getenv(disableServiceEnvVar)) == \"true\" {\n\t\tsvc.Handlers.Send.SwapNamed(request.NamedHandler{\n\t\t\tName: corehandlers.SendHandler.Name,\n\t\t\tFn: func(r *request.Request) {\n\t\t\t\tr.HTTPResponse = &http.Response{\n\t\t\t\t\tHeader: http.Header{},\n\t\t\t\t}\n\t\t\t\tr.Error = awserr.New(\n\t\t\t\t\trequest.CanceledErrorCode,\n\t\t\t\t\t\"EC2 IMDS access disabled via \"+disableServiceEnvVar+\" env var\",\n\t\t\t\t\tnil)\n\t\t\t},\n\t\t})\n\t}\n\n\t// Add additional options to the service config\n\tfor _, option := range opts {\n\t\toption(svc.Client)\n\t}\n\treturn svc\n}", "func NewRemote(v gointerfaces.Version, logger log.Logger, remoteKV remote.KVClient) remoteOpts {\n\treturn remoteOpts{bucketsCfg: mdbx.WithChaindataTables, version: v, log: logger, remoteKV: remoteKV}\n}", "func (b *backend) clientEC2(s logical.Storage, region string, stsRole string) (*ec2.EC2, error) {\n\tb.configMutex.RLock()\n\tif b.EC2ClientsMap[region] != nil && b.EC2ClientsMap[region][stsRole] != nil {\n\t\tdefer b.configMutex.RUnlock()\n\t\t// If the client object was already created, return it\n\t\treturn b.EC2ClientsMap[region][stsRole], nil\n\t}\n\n\t// Release the read lock and acquire the write lock\n\tb.configMutex.RUnlock()\n\tb.configMutex.Lock()\n\tdefer b.configMutex.Unlock()\n\n\t// If the client gets created while switching the locks, return it\n\tif b.EC2ClientsMap[region] != nil && b.EC2ClientsMap[region][stsRole] != nil {\n\t\treturn b.EC2ClientsMap[region][stsRole], nil\n\t}\n\n\t// Create an AWS config object using a chain of providers\n\tvar awsConfig *aws.Config\n\tvar err error\n\tawsConfig, err = b.getClientConfig(s, region, stsRole, \"ec2\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif awsConfig == nil {\n\t\treturn nil, fmt.Errorf(\"could not retrieve valid assumed credentials\")\n\t}\n\n\t// Create a new EC2 client object, cache it and return the same\n\tclient := ec2.New(session.New(awsConfig))\n\tif client == nil {\n\t\treturn nil, fmt.Errorf(\"could not obtain ec2 client\")\n\t}\n\tif _, ok := b.EC2ClientsMap[region]; !ok {\n\t\tb.EC2ClientsMap[region] = map[string]*ec2.EC2{stsRole: client}\n\t} else {\n\t\tb.EC2ClientsMap[region][stsRole] = client\n\t}\n\n\treturn b.EC2ClientsMap[region][stsRole], nil\n}", "func New(opts Opts) (remote.Remote, error) {\n\turl, err := url.Parse(opts.URL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thost, _, err := net.SplitHostPort(url.Host)\n\tif err == nil {\n\t\turl.Host = host\n\t}\n\treturn &client{\n\t\tURL: opts.URL,\n\t\tContext: opts.Context,\n\t\tMachine: url.Host,\n\t\tUsername: opts.Username,\n\t\tPassword: opts.Password,\n\t\tPrivateMode: opts.PrivateMode,\n\t\tSkipVerify: opts.SkipVerify,\n\t}, nil\n}", "func NewIdentityV2(client *gophercloud.ProviderClient) *gophercloud.ServiceClient {\n\tv2Endpoint := client.IdentityBase + \"v2.0/\"\n\n\treturn &gophercloud.ServiceClient{\n\t\tProviderClient: client,\n\t\tEndpoint: v2Endpoint,\n\t}\n}", "func New(edvServerURL string, opts ...Option) *Client {\n\tc := &Client{edvServerURL: edvServerURL, httpClient: &http.Client{}, marshal: json.Marshal}\n\n\tfor _, opt := range opts {\n\t\topt(c)\n\t}\n\n\treturn c\n}", "func NewClient(ctx context.Context, c *vim25.Client) (*Client, error) {\n\tfilter := &types.LookupServiceRegistrationFilter{\n\t\tServiceType: &types.LookupServiceRegistrationServiceType{\n\t\t\tProduct: \"com.vmware.cis\",\n\t\t\tType: \"cs.identity\",\n\t\t},\n\t\tEndpointType: &types.LookupServiceRegistrationEndpointType{\n\t\t\tProtocol: \"wsTrust\",\n\t\t\tType: \"com.vmware.cis.cs.identity.sso\",\n\t\t},\n\t}\n\n\turl := lookup.EndpointURL(ctx, c, Path, filter)\n\tsc := c.Client.NewServiceClient(url, Namespace)\n\n\treturn &Client{sc, sc}, nil\n}", "func New(cdClient *containerd.Client, originalImageDesc v1.Descriptor, opts ...containerd.RemoteOpt) *Client {\n\treturn &Client{\n\t\tcdClient: cdClient,\n\t\tOriginalImageDesc: originalImageDesc,\n\t\tRemoteOpts: opts,\n\t}\n}", "func ConnectEC2(sshEntries lib.SSHEntries, sshConfigPath string, args []string) {\n\t// get the pub key from the ssh agent first\n\tsshAgent, err := net.Dial(\"unix\", os.Getenv(\"SSH_AUTH_SOCK\"))\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"can't connect to ssh agent, maybe SSH_AUTH_SOCK is unset?\")\n\t}\n\n\tkeys, err := agent.NewClient(sshAgent).List()\n\tif err != nil || len(keys) < 1 {\n\t\tlog.Fatal(\"Can't get public keys from ssh agent. Please ensure you have the ssh-agent running and have at least one identity added (with ssh-add)\")\n\t}\n\tpubkey := keys[0].String()\n\n\t// push the pub key to those instances one after each other\n\t// TODO: maybe make it parallel\n\tfor _, sshEntry := range sshEntries {\n\t\tvar instanceName = sshEntry.InstanceID\n\t\tif len(sshEntry.Names) > 0 {\n\t\t\tinstanceName = sshEntry.Names[0]\n\t\t}\n\t\tlog.WithField(\"instance\", instanceName).Info(\"trying to do ec2 connect...\")\n\t\tinstanceIPAddress, instanceUser, err := pushEC2Connect(sshEntry.ProfileConfig.Name, sshEntry.InstanceID, sshEntry.User, pubkey)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Fatal(\"can't push ssh key to the instance\")\n\t\t}\n\t\t// if the address is empty we set to the value we got from ec2 connect push\n\t\tif sshEntry.Address == \"\" {\n\t\t\tsshEntry.Address = instanceIPAddress\n\t\t}\n\t\tif sshEntry.User == \"\" {\n\t\t\tsshEntry.User = instanceUser\n\t\t}\n\t}\n\n\t// then generate ssh config for all instances in sshEntries\n\t// save the dynamic ssh config first\n\tif err := sshEntries.SaveConfig(sshConfigPath); err != nil {\n\t\tlog.WithError(err).Fatal(\"can't save ssh config for ec2 connect\")\n\t}\n\n\tvar instanceName = sshEntries[0].InstanceID\n\tif len(sshEntries[0].Names) > 0 {\n\t\tinstanceName = sshEntries[0].Names[0]\n\t}\n\t// connect to the first instance in sshEntry, as the other will be bastion(s)\n\tif len(args) == 0 {\n\t\t// construct default args\n\t\targs = []string{\n\t\t\t\"ssh\",\n\t\t\t\"-tt\",\n\t\t\tinstanceName,\n\t\t}\n\t}\n\n\tcommand, err := exec.LookPath(args[0])\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Can't find the binary in the PATH\")\n\t}\n\n\tvar replacer = strings.NewReplacer(\n\t\t\"{host}\", instanceName,\n\t\t\"{user}\", sshEntries[0].User,\n\t)\n\tvar newArgs []string\n\tfor _, arg := range args {\n\t\tnewArgs = append(newArgs, replacer.Replace(arg))\n\t}\n\tlog.WithField(\"instance_id\", sshEntries[0].InstanceID).Infof(\"Connecting to the instance using '%s'\", strings.Join(newArgs, \" \"))\n\n\tif err := syscall.Exec(command, newArgs, os.Environ()); err != nil {\n\t\tlog.WithFields(log.Fields{\"command\": command}).WithError(err).Fatal(\"can't run the command\")\n\t}\n}", "func (ins *EC2RemoteClient) startInstance() error {\n\tlog.Printf(\"Starting EC2 Instance %s\", ins.InstanceID)\n\t_, err := ins.ec2Client.StartInstances(&ec2.StartInstancesInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error starting instance : %s\", err)\n\t}\n\tlog.Printf(\"Waiting for Instance %s to become ready (may take a few minutes)\", ins.InstanceID)\n\terr = ins.ec2Client.WaitUntilInstanceStatusOk(&ec2.DescribeInstanceStatusInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error waiting for instance to become available : %s\", err)\n\t}\n\treturn err\n}", "func main() {\n\tif len(os.Args) != 3 {\n\t\texitErrorf(\"AMI ID and Instance Type are required\"+\n\t\t\t\"\\nUsage: %s image_id instance_type\", os.Args[0])\n\t}\n\n\n\t//Initialize the session that the SDK uses to load credentials from the shared credentials file ~/.aws/credentials\n\tsess, err := session.NewSession(&aws.Config{Region: aws.String(\"eu-west-1\")}, )\n\tsvc := ec2.New(sess)\n\tif err != nil {\n\t\texitErrorf(\"Error creating session, %v\", err)\n\t}\n\n}", "func NewComputeV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {\n\teo.ApplyDefaults(\"compute\")\n\turl, err := client.EndpointLocator(eo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &gophercloud.ServiceClient{\n\t\tProviderClient: client,\n\t\tEndpoint: url,\n\t}, nil\n}", "func NewClient(config *Config) (*Client, error) {\n c := &Client{}\n\n client, err := ssh.Dial(\"tcp\", config.Host + \":\" + strconv.Itoa(config.Port), config.ClientConfig)\n if err != nil {\n return nil, err\n }\n\n c.client = client\n return c, nil\n}", "func newClient(ctx context.Context, cfg vcConfig) (*vsClient, error) {\n\tu := url.URL{\n\t\tScheme: \"https\",\n\t\tHost: cfg.server,\n\t\tPath: \"sdk\",\n\t}\n\n\tu.User = url.UserPassword(cfg.user, cfg.password)\n\tinsecure := cfg.insecure\n\n\tgc, err := govmomi.NewClient(ctx, &u, insecure)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"connecting to vSphere API: %w\", err)\n\t}\n\n\trc := rest.NewClient(gc.Client)\n\ttm := tags.NewManager(rc)\n\n\tvsc := vsClient{\n\t\tgovmomi: gc,\n\t\trest: rc,\n\t\ttagManager: tm,\n\t}\n\n\terr = vsc.rest.Login(ctx, u.User)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"logging into rest api: %w\", err)\n\t}\n\n\treturn &vsc, nil\n}", "func (e *EdgeSwitchClient) newClient() (*ssh.Client, error) {\n\tsshConfig := &ssh.ClientConfig{\n\t\tUser: DEFAULT_USER,\n\t\tAuth: []ssh.AuthMethod{ssh.Password(DEFAULT_USER)},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", e.ipaddress, sshConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func NewInstance(projectID string, metaData map[string]string, secGroup []map[string]interface{}) openstack.InstanceClient {\n\treturn &Instance{\n\t\tprojectID: projectID,\n\t\tmetaData: metaData,\n\t\tsecGroup: secGroup,\n\t\tcreated: time.Now(),\n\t}\n}", "func (ins *EC2RemoteClient) makeReady() error {\n\t// Check Instance is running - will error if instance doesn't exist\n\tresult, err := ins.ec2Client.DescribeInstanceStatus(&ec2.DescribeInstanceStatusInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting instance status : %s\", err)\n\t}\n\n\t// Start instance if needed\n\tif len(result.InstanceStatuses) == 0 || *result.InstanceStatuses[0].InstanceState.Name != \"running\" {\n\t\terr = ins.startInstance()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error starting instance : %s\", err)\n\t\t}\n\t}\n\n\t// Get Public IP address from ec2\n\terr = ins.getIPAddress()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting IP address : %s\", err)\n\t}\n\n\t// Set up SSH connection\n\tins.cmdClient, err = sshCmdClient.NewSSHCmdClient(ins.instanceIP, ins.sshCredentials)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Check we can at least run a trivial command\n\texitStatus, err := ins.RunCommand(\"true\")\n\tif err != nil || exitStatus != 0 {\n\t\treturn fmt.Errorf(\"Error running commands on instance : %s\", err)\n\t}\n\n\treturn err\n}", "func NewClient(endPoint, id, key string) (*Client, error) {\n\treturn &Client{endPoint, id, key, \"\", false}, nil\n}", "func NewELBv2APIClient(t interface {\n\tmock.TestingT\n\tCleanup(func())\n}) *ELBv2APIClient {\n\tmock := &ELBv2APIClient{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func New(region string, logger *log.Logger) *Client {\n\tsess := session.New(&aws.Config{Region: &region})\n\tsvc := ecs.New(sess)\n\treturn &Client{\n\t\tsvc: svc,\n\t\tpollInterval: time.Second * 5,\n\t\tlogger: logger,\n\t}\n}", "func New(address string) (*EthRPC2, error) {\n\tclient, err := ethclient.Dial(address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &EthRPC2{client: client}, nil\n}", "func NewClient(host string, port int, user string, key string) (Client, error) {\n\tif err := ValidUnencryptedPrivateKey(key); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsshBinaryPath, err := exec.LookPath(\"ssh\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"command not found: ssh\")\n\t}\n\n\treturn newExternalClient(sshBinaryPath, user, host, port, key)\n}", "func NewClient(remoteName, urlString string, httpConfig configutil.HTTPClientConfig, timeout model.Duration) (*Client, error) {\n\tparsedUrl, err := url.Parse(urlString)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing-%s-url: %w\", remoteName, err)\n\t}\n\thttpClient, err := configutil.NewClientFromConfig(httpConfig, fmt.Sprintf(\"%s_client\", remoteName), configutil.WithHTTP2Disabled())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt := httpClient.Transport\n\thttpClient.Transport = &nethttp.Transport{\n\t\tRoundTripper: t,\n\t}\n\n\treturn &Client{\n\t\tremoteName: remoteName,\n\t\turl: &config.URL{URL: parsedUrl},\n\t\tClient: httpClient,\n\t\ttimeout: time.Duration(timeout),\n\t}, nil\n}", "func NewClient(remoteName string, config *cfg.Config) (*Client, bool) {\n\tremote, found := config.GetRemote(remoteName)\n\tif !found {\n\t\treturn nil, false\n\t}\n\n\treturn &Client{\n\t\tRemoteVPS: remote,\n\t\tversion: config.Version,\n\t\tproject: config.Project,\n\t\tbuildType: config.BuildType,\n\t\tbuildFilePath: config.BuildFilePath,\n\t\tsshRunner: NewSSHRunner(remote),\n\t}, true\n}", "func New(addr string, username string, password string) (*SSHClient, error) {\n\tcfg := &ssh.ClientConfig{\n\t\tUser: username,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.Password(password),\n\t\t\tssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) ([]string, error) {\n\t\t\t\tif len(questions) == 0 {\n\t\t\t\t\treturn []string{}, nil\n\t\t\t\t}\n\t\t\t\tif len(questions) == 1 {\n\t\t\t\t\treturn []string{password}, nil\n\t\t\t\t}\n\t\t\t\treturn []string{}, fmt.Errorf(\"unsupported keyboard-interactive auth\")\n\t\t\t}),\n\t\t},\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t\tTimeout: clientTimeout,\n\t}\n\n\taddr, err := checkAndBuildAddr(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &SSHClient{addr: addr, config: cfg, lock: new(sync.Mutex)}, nil\n}", "func newInputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName, resolvedRegion string) *InputService2ProtocolTest {\n\tsvc := &InputService2ProtocolTest{\n\t\tClient: client.New(\n\t\t\tcfg,\n\t\t\tmetadata.ClientInfo{\n\t\t\t\tServiceName: \"InputService2ProtocolTest\",\n\t\t\t\tServiceID: \"InputService2ProtocolTest\",\n\t\t\t\tSigningName: signingName,\n\t\t\t\tSigningRegion: signingRegion,\n\t\t\t\tPartitionID: partitionID,\n\t\t\t\tEndpoint: endpoint,\n\t\t\t\tAPIVersion: \"\",\n\t\t\t\tResolvedRegion: resolvedRegion,\n\t\t\t\tJSONVersion: \"1.1\",\n\t\t\t\tTargetPrefix: \"com.amazonaws.foo\",\n\t\t\t},\n\t\t\thandlers,\n\t\t),\n\t}\n\n\t// Handlers\n\tsvc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)\n\tsvc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)\n\tsvc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)\n\tsvc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)\n\tsvc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler)\n\n\treturn svc\n}", "func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) (*managedIdentityClient, error) {\n\tif options == nil {\n\t\toptions = &ManagedIdentityCredentialOptions{}\n\t}\n\tcp := options.ClientOptions\n\tc := managedIdentityClient{id: options.ID, endpoint: imdsEndpoint, msiType: msiTypeIMDS}\n\tenv := \"IMDS\"\n\tif endpoint, ok := os.LookupEnv(identityEndpoint); ok {\n\t\tif _, ok := os.LookupEnv(identityHeader); ok {\n\t\t\tif _, ok := os.LookupEnv(identityServerThumbprint); ok {\n\t\t\t\tenv = \"Service Fabric\"\n\t\t\t\tc.endpoint = endpoint\n\t\t\t\tc.msiType = msiTypeServiceFabric\n\t\t\t} else {\n\t\t\t\tenv = \"App Service\"\n\t\t\t\tc.endpoint = endpoint\n\t\t\t\tc.msiType = msiTypeAppService\n\t\t\t}\n\t\t} else if _, ok := os.LookupEnv(arcIMDSEndpoint); ok {\n\t\t\tenv = \"Azure Arc\"\n\t\t\tc.endpoint = endpoint\n\t\t\tc.msiType = msiTypeAzureArc\n\t\t}\n\t} else if endpoint, ok := os.LookupEnv(msiEndpoint); ok {\n\t\tenv = \"Cloud Shell\"\n\t\tc.endpoint = endpoint\n\t\tc.msiType = msiTypeCloudShell\n\t} else {\n\t\tsetIMDSRetryOptionDefaults(&cp.Retry)\n\t}\n\tc.pipeline = runtime.NewPipeline(component, version, runtime.PipelineOptions{}, &cp)\n\n\tif log.Should(EventAuthentication) {\n\t\tlog.Writef(EventAuthentication, \"Managed Identity Credential will use %s managed identity\", env)\n\t}\n\n\treturn &c, nil\n}", "func New(endpointURL string) (*Client, error) {\n\tu, err := url.Parse(endpointURL)\n\tif err != nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"invalid endpoint URL\")\n\t}\n\n\ttlsConfig := &tls.Config{}\n\n\ttransport := httptransport.New(u.Host, \"\", []string{u.Scheme})\n\ttransport.Transport = &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tTLSClientConfig: tlsConfig,\n\t}\n\n\tc := &Client{\n\t\tAPIEndpointURL: endpointURL,\n\t\tGSClientGen: gsclient.New(transport, strfmt.Default),\n\t}\n\n\tpkceResponse, err := oidc.RunPKCE(endpointURL)\n\tif err != nil {\n\t\tfmt.Println(\"DEBUG: Attempt to run the OAuth2 PKCE workflow with a local callback HTTP server failed.\")\n\t\treturn nil, microerror.Mask(err)\n\t}\n\n\tidToken, err := oidc.ParseIDToken(pkceResponse.IDToken)\n\tif err != nil {\n\t\treturn nil, microerror.Mask(err)\n\t}\n\n\t// store tokens\n\tc.IDToken = idToken\n\tc.AccessToken = pkceResponse.AccessToken\n\tc.RefreshToken = pkceResponse.RefreshToken\n\n\treturn c, nil\n}", "func (p *EC2Provisioner) CreateInstance(opts EC2CreateInstanceOptions) (*cfg.Remote, error) {\n\t// Set requested region\n\tp.WithRegion(opts.Region)\n\n\t// set highlighter\n\tvar highlight = out.NewColorer(out.CY)\n\n\t// Generate authentication\n\tvar keyName = fmt.Sprintf(\"%s_%s_inertia_key_%d\", opts.Name, p.user, time.Now().UnixNano())\n\tout.Fprintf(p.out, highlight.Sf(\":key: Generating key pair '%s'...\\n\", keyName))\n\tkeyResp, err := p.client.CreateKeyPair(&ec2.CreateKeyPairInput{\n\t\tKeyName: aws.String(keyName),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thomeDir, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Save key\n\tvar keyPath = filepath.Join(homeDir, \".ssh\", *keyResp.KeyName)\n\tout.Fprintf(p.out, highlight.Sf(\":inbox_tray: Saving key to '%s'...\\n\", keyPath))\n\tif err = local.SaveKey(*keyResp.KeyMaterial, keyPath); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create security group for network configuration\n\tvar secGroup = fmt.Sprintf(\"%s-%d\", opts.Name, time.Now().UnixNano())\n\tout.Fprintf(p.out, highlight.Sf(\":circus_tent: Creating security group '%s'...\\n\", secGroup))\n\tgroup, err := p.client.CreateSecurityGroup(&ec2.CreateSecurityGroupInput{\n\t\tGroupName: aws.String(secGroup),\n\t\tDescription: aws.String(\n\t\t\tfmt.Sprintf(\"Rules for project %s on %s\", opts.ProjectName, opts.Name),\n\t\t),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set rules for ports\n\tout.Fprintf(p.out, highlight.Sf(\":electric_plug: Exposing ports '%s'...\\n\", secGroup))\n\tif err = p.exposePorts(*group.GroupId, opts.DaemonPort, opts.Ports); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Start up instance\n\tout.Fprintf(p.out, highlight.Sf(\":boat: Requesting instance '%s'...\\n\", secGroup))\n\trunResp, err := p.client.RunInstances(&ec2.RunInstancesInput{\n\t\tImageId: aws.String(opts.ImageID),\n\t\tInstanceType: aws.String(opts.InstanceType),\n\t\tMinCount: aws.Int64(1),\n\t\tMaxCount: aws.Int64(1),\n\n\t\t// Security options\n\t\tKeyName: keyResp.KeyName,\n\t\tSecurityGroupIds: []*string{group.GroupId},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check response validity\n\tif runResp.Instances == nil || len(runResp.Instances) == 0 {\n\t\treturn nil, errors.New(\"Unable to start instances: \" + runResp.String())\n\t}\n\tout.Fprintf(p.out, highlight.Sf(\"A %s instance has been provisioned\", opts.InstanceType))\n\n\t// Loop until intance is running\n\tvar instance ec2.Instance\n\tfor {\n\t\t// Wait briefly between checks\n\t\ttime.Sleep(3 * time.Second)\n\n\t\t// Request instance status\n\t\tout.Fprintf(p.out, \"Checking status of the requested instance...\\n\")\n\t\tresult, err := p.client.DescribeInstances(&ec2.DescribeInstancesInput{\n\t\t\tInstanceIds: []*string{runResp.Instances[0].InstanceId},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Check if reservations are present\n\t\tif result.Reservations == nil || len(result.Reservations) == 0 ||\n\t\t\tlen(result.Reservations[0].Instances) == 0 {\n\t\t\t// A reservation corresponds to a command to start instances\n\t\t\t// If nothing is here... we gotta keep waiting\n\t\t\tfmt.Fprintln(p.out, \"No reservations found yet.\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get status\n\t\ts := result.Reservations[0].Instances[0].State\n\t\tif s == nil {\n\t\t\tfmt.Println(p.out, \"Status unknown.\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Code 16 means instance has started, and we can continue!\n\t\tif s.Code != nil && *s.Code == codeEC2InstanceStarted {\n\t\t\tfmt.Fprintln(p.out, \"Instance is running!\")\n\t\t\tinstance = *result.Reservations[0].Instances[0]\n\t\t\tbreak\n\t\t}\n\n\t\t// Otherwise, keep polling\n\t\tif s.Name != nil {\n\t\t\tfmt.Fprintln(p.out, \"Instance status: \"+*s.Name)\n\t\t} else {\n\t\t\tfmt.Fprintln(p.out, \"Instance status: \"+s.String())\n\t\t}\n\t\tcontinue\n\t}\n\n\t// Check instance validity\n\tif instance.PublicDnsName == nil {\n\t\treturn nil, errors.New(\"Unable to find public IP address for instance: \" + instance.String())\n\t}\n\n\t// Set tags\n\tout.Fprintf(p.out, \"Setting tags on instance...\\n\")\n\tif _, err = p.client.CreateTags(&ec2.CreateTagsInput{\n\t\tResources: []*string{instance.InstanceId},\n\t\tTags: []*ec2.Tag{\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Name\"),\n\t\t\t\tValue: aws.String(opts.Name),\n\t\t\t},\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Purpose\"),\n\t\t\t\tValue: aws.String(\"Inertia Continuous Deployment\"),\n\t\t\t},\n\t\t},\n\t}); err != nil {\n\t\tfmt.Fprintln(p.out, \"Failed to set tags: \"+err.Error())\n\t}\n\n\t// Poll for SSH port to open\n\tfmt.Fprintln(p.out, \"Waiting for ports to open...\")\n\tfor {\n\t\ttime.Sleep(3 * time.Second)\n\t\tfmt.Fprintln(p.out, \"Checking ports...\")\n\t\tif conn, err := net.Dial(\"tcp\", *instance.PublicDnsName+\":22\"); err == nil {\n\t\t\tfmt.Fprintln(p.out, \"Connection established!\")\n\t\t\tconn.Close()\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Generate webhook secret\n\tout.Fprintf(p.out, \"Generating a webhook secret...\\n\")\n\twebhookSecret, err := common.GenerateRandomString()\n\tif err != nil {\n\t\tfmt.Fprintln(p.out, err.Error())\n\t\tfmt.Fprintln(p.out, \"Using default secret 'inertia'\")\n\t\twebhookSecret = \"interia\"\n\t} else {\n\t\tfmt.Fprintf(p.out, \"Generated webhook secret: '%s'\\n\", webhookSecret)\n\t}\n\n\t// Return remote configuration\n\treturn &cfg.Remote{\n\t\tName: opts.Name,\n\t\tIP: *instance.PublicDnsName,\n\t\tSSH: &cfg.SSH{\n\t\t\tUser: p.user,\n\t\t\tIdentityFile: keyPath,\n\t\t\tSSHPort: \"22\",\n\t\t},\n\t\tDaemon: &cfg.Daemon{\n\t\t\tPort: strconv.FormatInt(opts.DaemonPort, 10),\n\t\t\tWebHookSecret: webhookSecret,\n\t\t},\n\t\tProfiles: make(map[string]string),\n\t}, nil\n}", "func New(p client.ConfigProvider, cfgs ...*aws.Config) *EC2Metadata {\n\tc := p.ClientConfig(ServiceName, cfgs...)\n\treturn NewClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)\n}", "func (pluginSPI *PluginSPIImpl) NewECSClient(secret *corev1.Secret, region string) (ECSClient, error) {\n\taccessKeyID := extractCredentialsFromData(secret.Data, AlicloudAccessKeyID, AlicloudAlternativeAccessKeyID)\n\taccessKeySecret := extractCredentialsFromData(secret.Data, AlicloudAccessKeySecret, AlicloudAlternativeAccessKeySecret)\n\tecsClient, err := ecs.NewClientWithAccessKey(region, accessKeyID, accessKeySecret)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn ecsClient, err\n}", "func New(username string, password string) core.SSHClient {\n\treturn &sshclient{\n\t\tconfig: &ssh.ClientConfig{\n\t\t\tUser: username,\n\t\t\tAuth: []ssh.AuthMethod{\n\t\t\t\tssh.Password(password),\n\t\t\t},\n\t\t\tTimeout: 5 * time.Second,\n\t\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t\t},\n\t}\n}", "func createEC2InstanceMonitoredResource(awsIdentityDoc *awsIdentityDocument) *EC2Instance {\n\tawsInstance := EC2Instance{\n\t\tAWSAccount: awsIdentityDoc.accountID,\n\t\tInstanceID: awsIdentityDoc.instanceID,\n\t\tRegion: fmt.Sprintf(\"aws:%s\", awsIdentityDoc.region),\n\t}\n\treturn &awsInstance\n}", "func createTestEC2InstanceMock() *ec2.EC2 {\n\tconn := ec2.New(session.New(), nil)\n\tconn.Handlers.Clear()\n\n\tconn.Handlers.Send.PushBack(func(r *request.Request) {\n\t\tswitch p := r.Params.(type) {\n\t\tcase *ec2.DescribeImagesInput:\n\t\t\tout, err := testDescribeImages(p)\n\t\t\tif out != nil {\n\t\t\t\t*r.Data.(*ec2.DescribeImagesOutput) = *out\n\t\t\t}\n\t\t\tr.Error = err\n\t\tcase *ec2.DescribeInstancesInput:\n\t\t\tout, err := testDescribeInstances(p)\n\t\t\tif out != nil {\n\t\t\t\t*r.Data.(*ec2.DescribeInstancesOutput) = *out\n\t\t\t}\n\t\t\tr.Error = err\n\t\tcase *ec2.RunInstancesInput:\n\t\t\tout, err := testRunInstances(p)\n\t\t\tif out != nil {\n\t\t\t\t*r.Data.(*ec2.Reservation) = *out\n\t\t\t}\n\t\t\tr.Error = err\n\t\tcase *ec2.TerminateInstancesInput:\n\t\t\tout, err := testTerminateInstances(p)\n\t\t\tif out != nil {\n\t\t\t\t*r.Data.(*ec2.TerminateInstancesOutput) = *out\n\t\t\t}\n\t\t\tr.Error = err\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"Unsupported input type %T\", p))\n\t\t}\n\t})\n\treturn conn\n}", "func NewClient(accessKeyID, secretAccessKey, region, endpoint, bucket string) S3Client {\n\tsess, err := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(region),\n\t\tEndpoint: aws.String(endpoint),\n\t\tCredentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, \"\"),\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR]: %v\\n\", \"Error while creating S3 Session\")\n\t\treturn nil\n\t}\n\n\treturn &s3Client{\n\t\tbucket,\n\t\ts3manager.NewUploader(sess),\n\t}\n}", "func New(transport runtime.ClientTransport, formats strfmt.Registry) *DivvyCloudV2 {\n\t// ensure nullable parameters have default\n\tif formats == nil {\n\t\tformats = strfmt.Default\n\t}\n\n\tcli := new(DivvyCloudV2)\n\tcli.Transport = transport\n\n\tcli.AddCloudAccount = add_cloud_account.New(transport, formats)\n\n\tcli.Clouds = clouds.New(transport, formats)\n\n\tcli.EventDrivenHarvesting = event_driven_harvesting.New(transport, formats)\n\n\tcli.Organizations = organizations.New(transport, formats)\n\n\tcli.Resources = resources.New(transport, formats)\n\n\tcli.Users = users.New(transport, formats)\n\n\treturn cli\n}", "func NewRemote() (Catalog, error) {\n\treturn newRemoteFunc()\n}", "func pushEC2Connect(profile, instanceID, instanceUser, pubKey string) (string, string, error) {\n\tctx := log.WithField(\"instance_id\", instanceID)\n\tcfg, err := config.LoadDefaultConfig(context.TODO(),\n\t\tconfig.WithSharedConfigProfile(profile))\n\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"can't get aws session: %s\", err)\n\t}\n\tec2Svc := ec2.NewFromConfig(cfg)\n\tec2Result, err := ec2Svc.DescribeInstances(context.TODO(), &ec2.DescribeInstancesInput{\n\t\tInstanceIds: []string{instanceID},\n\t})\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"can't get ec2 instance: %s\", err)\n\t}\n\n\tif len(ec2Result.Reservations) == 0 || len(ec2Result.Reservations[0].Instances) == 0 {\n\t\treturn \"\", \"\", fmt.Errorf(\"Couldn't find the instance %s\", instanceID)\n\t}\n\n\tec2Instance := ec2Result.Reservations[0].Instances[0]\n\tec2ICSvc := ec2instanceconnect.NewFromConfig(cfg)\n\n\t// no username has been provided, so we try to get it fom the instance tag first\n\tif instanceUser == \"\" {\n\t\tctx.Debug(\"no user has been set provided, trying to get it from the tags\")\n\t\t// next try to get username from the instance tags\n\t\tif instanceUser = lib.GetUserFromTags(ec2Instance.Tags); instanceUser == \"\" {\n\t\t\t// otherwise fallback to default\n\t\t\tctx.WithField(\"user\", defaultUser).Debugf(\"got no user from the instance tags, setting to default\")\n\t\t\tinstanceUser = defaultUser\n\t\t} else {\n\t\t\tctx.WithField(\"user\", instanceUser).Debugf(\"got username from tags\")\n\t\t}\n\t}\n\n\tctx.WithField(\"user\", instanceUser).Info(\"pushing SSH key...\")\n\n\tif _, err := ec2ICSvc.SendSSHPublicKey(context.TODO(), &ec2instanceconnect.SendSSHPublicKeyInput{\n\t\tInstanceId: ec2Instance.InstanceId,\n\t\tInstanceOSUser: aws.String(instanceUser),\n\t\tAvailabilityZone: ec2Instance.Placement.AvailabilityZone,\n\t\tSSHPublicKey: aws.String(pubKey),\n\t}); err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"can't push ssh key: %s\", err)\n\t}\n\tvar address = aws.ToString(ec2Instance.PrivateIpAddress)\n\tif aws.ToString(ec2Instance.PublicIpAddress) != \"\" {\n\t\taddress = aws.ToString(ec2Instance.PublicIpAddress)\n\t}\n\treturn address, instanceUser, nil\n}", "func NewRemoteHelper(ctx context.Context, regID int64) (RemoteInterface, error) {\n\tr := &remoteHelper{\n\t\tregID: regID,\n\t\tregistryMgr: reg.Mgr}\n\tif err := r.init(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}", "func NewEC2Provisioner(user, keyID, key string, out ...io.Writer) (*EC2Provisioner, error) {\n\tprov := &EC2Provisioner{}\n\treturn prov, prov.init(user, credentials.NewStaticCredentials(keyID, key, \"\"), out)\n}", "func newVirtualMachineClient(subID string, authorizer auth.Authorizer) (*client, error) {\n\tc, err := wssdcloudclient.GetVirtualMachineClient(&subID, authorizer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &client{c}, nil\n}", "func (provider *ResourceProvider) EC2Instance(id string) (*reachAWS.EC2Instance, error) {\n\tinput := &ec2.DescribeInstancesInput{\n\t\tInstanceIds: []*string{\n\t\t\taws.String(id),\n\t\t},\n\t}\n\tresult, err := provider.ec2.DescribeInstances(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstances, err := extractEC2Instances(result.Reservations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(instances) == 0 {\n\t\treturn nil, fmt.Errorf(\"AWS API returned no instances for ID '%s'\", id)\n\t}\n\n\tif len(instances) > 1 {\n\t\treturn nil, fmt.Errorf(\"AWS API returned more than one instance for ID '%s'\", id)\n\t}\n\n\tinstance := instances[0]\n\treturn &instance, nil\n}", "func New(rootDir, stateDir string, options ...RemoteOption) (Remote, error) {\n\treturn &remote{\n\t\tlogger: logrus.WithField(\"module\", \"libcontainerd\"),\n\t\trootDir: rootDir,\n\t\tstateDir: stateDir,\n\t}, nil\n}", "func NewClient(\n\tctx context.Context,\n\tuser,\n\thost,\n\tport,\n\tprivateKeyPath string,\n) (*Client, error) {\n\tauthMethod := []ssh.AuthMethod{}\n\tkey, err := ioutil.ReadFile(privateKeyPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsigner, err := ssh.ParsePrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthMethod = append(authMethod, ssh.PublicKeys(signer))\n\n\tsshConfig := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: authMethod,\n\t\t// TOOD: change right callback\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\taddr := fmt.Sprintf(\"%s:%s\", host, port)\n\treturn &Client{sshConfig, addr}, nil\n}", "func NewClient() (Client, error) {\n\ttoken, err := iv_auth.LoadCredentials()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\n\treturn &client{oauthToken: token}, nil\n}", "func NewEC2Mock() *EC2Mock {\n\treturn &EC2Mock{instances: make(instanceMap)}\n}", "func NewClient(privateKeyHex string, authHandle string, environment Environment) (Client, error) {\n\tprivateKey, err := crypto.HexToECDSA(privateKeyHex)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"private key invalid, make sure it is hex without the 0x prefix: %v\", err)\n\t}\n\tonce.Do(func() {\n\t\tinstance = &ClientImpl{\n\t\t\tprivateKey: privateKey,\n\t\t\tauthHandle: authHandle,\n\t\t\tversion: \"0.2\",\n\t\t\tcrypto: \"ETH\",\n\t\t\tenvironment: environment,\n\t\t}\n\t})\n\treturn instance, nil\n}", "func NewClient() (cloudops.Ops, error) {\n\tvar i = new(instance)\n\tvar err error\n\tif metadata.OnGCE() {\n\t\terr = gceInfo(i)\n\t} else if ok := IsDevMode(); ok {\n\t\terr = gceInfoFromEnv(i)\n\t} else {\n\t\treturn nil, fmt.Errorf(\"instance is not running on GCE\")\n\t}\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error fetching instance info. Err: %v\", err)\n\t}\n\n\tc, err := google.DefaultClient(context.Background(), compute.ComputeScope)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to authenticate with google api. Err: %v\", err)\n\t}\n\n\tservice, err := compute.New(c)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create Compute service: %v\", err)\n\t}\n\n\treturn &gceOps{\n\t\tCompute: unsupported.NewUnsupportedCompute(),\n\t\tinst: i,\n\t\tservice: service,\n\t}, nil\n}", "func New(apiKey string, secretKey string, opts ...ClientOption) (*client, error) {\n\tc := &client{\n\t\tidGenerator: &id.Generator{},\n\t\tsignatureGenerator: &auth.Generator{},\n\t\tclock: clockwork.NewRealClock(),\n\t\trequester: api.Requester{\n\t\t\tClient: http.DefaultClient,\n\t\t\tBaseURL: productionBaseURL,\n\t\t},\n\t}\n\n\tif err := c.UpdateConfig(apiKey, secretKey, opts...); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}", "func NewIP2ASNClient(conn redis.Conn) *IP2ASNClient {\n\tipasn := &IP2ASNClient{\n\t\tconn: conn,\n\t}\n\treturn ipasn\n}", "func New(instance string, options ...httptransport.ClientOption) (pb.CustomerServer, error) {\n\n\tif !strings.HasPrefix(instance, \"http\") {\n\t\tinstance = \"http://\" + instance\n\t}\n\tu, err := url.Parse(instance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_ = u\n\n\tpanic(\"No HTTP Endpoints, this client will not work, define bindings in your proto definition\")\n\n\treturn svc.Endpoints{}, nil\n}", "func New(chainID, remote string) (provider.Provider, error) {\n\thttpClient, err := rpcclient.NewHTTP(remote, \"/websocket\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWithClient(chainID, httpClient), nil\n}", "func NewClient(sshconfig *ssh.ClientConfig, host string, port string, prompts []Prompt) *Client {\n\treturn &Client{\n\t\tSshconfig: sshconfig,\n\t\tHost: host,\n\t\tPort: port,\n\t\tPrompt: prompts,\n\t}\n}", "func New(client, secret string) remote.Remote {\n\treturn &config{\n\t\tAPI: DefaultAPI,\n\t\tURL: DefaultURL,\n\t\tClient: client,\n\t\tSecret: secret,\n\t}\n}", "func NewClient(instanceConfig config.InstanceConfig, apiConfig DestinationServiceAPIConfig,\n\tsubdomain string) (*Client, error) {\n\tif err := setInstanceConfigTokenURLForSubdomain(&instanceConfig, apiConfig, subdomain); err != nil {\n\t\treturn nil, err\n\t}\n\thttpClient, err := getHTTPClient(instanceConfig, apiConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{\n\t\tHTTPClient: httpClient,\n\t\tapiConfig: apiConfig,\n\t\tauthConfig: instanceConfig,\n\t}, nil\n}", "func newEtcdServerClient(subID string, authorizer auth.Authorizer) (*client, error) {\n\tc, err := wssdcloudclient.GetEtcdServerClient(&subID, authorizer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &client{c}, nil\n}", "func ClientRemote() (*Client, error) {\n\treturn NewClient(\n\t\tSetVerbose(false),\n\t\tSetURL(os.Getenv(\"BONSAIO_HOST\")),\n\t\tSetElasticClient(client(true)))\n}", "func NewClient(options ClientOptions) Client {\n\tgenericInfo := generic{\n\t\tappName: options.LocalConfigProvider.GetApplication(),\n\t\tcomponentName: options.LocalConfigProvider.GetName(),\n\t\tlocalConfig: options.LocalConfigProvider,\n\t}\n\n\tif _, ok := options.LocalConfigProvider.(*config.LocalConfigInfo); ok {\n\t\treturn s2iClient{\n\t\t\tgeneric: genericInfo,\n\t\t\tclient: options.OCClient,\n\t\t}\n\t} else {\n\t\treturn kubernetesClient{\n\t\t\tgeneric: genericInfo,\n\t\t\tisRouteSupported: options.IsRouteSupported,\n\t\t\tclient: options.OCClient,\n\t\t}\n\t}\n}", "func createENI(ec2Client *ec2.EC2, cfg *config) (*ec2.NetworkInterface, error) {\n\tvar filterValuesGroupName []*string\n\tfor _, sg := range cfg.securityGroups {\n\t\tfilterValuesGroupName = append(filterValuesGroupName, aws.String(sg))\n\t}\n\t// Get security group id for the security group that the instance was\n\t// started with\n\tsecurityGroups, err := ec2Client.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: aws.String(\"group-name\"),\n\t\t\t\tValues: filterValuesGroupName,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: aws.String(\"vpc-id\"),\n\t\t\t\tValues: []*string{aws.String(cfg.vpc)},\n\t\t\t},\n\t\t}})\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get security group ids\")\n\t}\n\tvar securityGroupIDs []*string\n\tfor _, sg := range securityGroups.SecurityGroups {\n\t\tsecurityGroupIDs = append(securityGroupIDs, sg.GroupId)\n\t}\n\n\t// Create the ENI\n\toutput, err := ec2Client.CreateNetworkInterface(&ec2.CreateNetworkInterfaceInput{\n\t\tDescription: aws.String(\"for running end-to-end test for ECS ENI Plugin\"),\n\t\tGroups: securityGroupIDs,\n\t\tSubnetId: aws.String(cfg.subnet),\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to create network interface\")\n\t}\n\treturn output.NetworkInterface, nil\n}", "func NewRemoteExecutor(host string, port int, username string, privateKey []byte, password string) (Executor, error) {\n\tclient, err := ssh.NewClient(host, port, username, privateKey, password)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tre := &RemoteExecutor{Client: client}\n\treturn re, nil\n}", "func New(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*AdminClient, error) {\n\tclnt, err := privateNew(endpoint, accessKeyID, secretAccessKey, secure)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clnt, nil\n}", "func (connection *VSphereConnection) NewClient(ctx context.Context) (*vim25.Client, error) {\n\turl, err := soap.ParseURL(net.JoinHostPort(connection.Hostname, connection.Port))\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to parse URL: %s. err: %+v\", url, err)\n\t\treturn nil, err\n\t}\n\n\tsc := soap.NewClient(url, connection.Insecure)\n\n\tif ca := connection.CACert; ca != \"\" {\n\t\tif err := sc.SetRootCAs(ca); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\ttpHost := connection.Hostname + \":\" + connection.Port\n\tsc.SetThumbprint(tpHost, connection.Thumbprint)\n\n\tclient, err := vim25.NewClient(ctx, sc)\n\tif err != nil {\n\t\tklog.Errorf(\"Failed to create new client. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\tk8sVersion := version.Get().GitVersion\n\tclient.UserAgent = fmt.Sprintf(\"kubernetes-cloudprovider/%s\", k8sVersion)\n\n\terr = connection.login(ctx, client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tklogV := klog.V(3)\n\tif klogV.Enabled() {\n\t\ts, err := session.NewManager(client).UserSession(ctx)\n\t\tif err == nil {\n\t\t\tklogV.Infof(\"New session ID for '%s' = %s\", s.UserName, s.Key)\n\t\t}\n\t}\n\n\tif connection.RoundTripperCount == 0 {\n\t\tconnection.RoundTripperCount = RoundTripperDefaultCount\n\t}\n\tclient.RoundTripper = vim25.Retry(client.RoundTripper, vim25.TemporaryNetworkError(int(connection.RoundTripperCount)))\n\tvcNotSupported, err := isvCenterNotSupported(client.ServiceContent.About.Version, client.ServiceContent.About.ApiVersion)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to check if vCenter version:%v and api version: %s is supported or not. Error: %v\", client.ServiceContent.About.Version, client.ServiceContent.About.ApiVersion, err)\n\t}\n\tif vcNotSupported {\n\t\tklog.Warningf(\"vCenter version (version: %q, api verson: %q) is not supported for CSI Migration. Please consider upgrading vCenter and ESXi servers to 7.0u2 or higher for migrating vSphere volumes to CSI.\", client.ServiceContent.About.Version, client.ServiceContent.About.ApiVersion)\n\t}\n\treturn client, nil\n}", "func NewECRClient(region string) *ECRClientImpl {\n\tawsConfig := aws.NewConfig()\n\tawsConfig.WithRegion(region)\n\n\tsess := session.Must(\n\t\tsession.NewSession(awsConfig),\n\t)\n\n\tcreds := credentials.NewChainCredentials(\n\t\t[]credentials.Provider{\n\t\t\t&credentials.EnvProvider{},\n\t\t\t&stscreds.WebIdentityRoleProvider{},\n\t\t\t&credentials.SharedCredentialsProvider{},\n\t\t\t&ec2rolecreds.EC2RoleProvider{\n\t\t\t\tClient: ec2metadata.New(sess),\n\t\t\t},\n\t\t})\n\n\tawsConfig.WithCredentials(creds)\n\n\treturn &ECRClientImpl{\n\t\tECRClient: ecr.New(sess),\n\t}\n}", "func New(name, privateIP, publicIP, part string) EC2Instance {\n\treturn EC2Instance{name: name, privateIP: privateIP, publicIP: publicIP, partition: part}\n}", "func (ins *EC2RemoteClient) Close() error {\n\treturn ins.cmdClient.Close()\n}", "func NewClient(bucket, key, region, profile string) Client {\n\treturn Client{\n\t\tBucket: bucket,\n\t\tKey: key,\n\t\tRegion: region,\n\t\tProfile: profile,\n\t}\n}", "func New(ctx context.Context, h *http.Client, server string) (*Client, error) {\n\tservice, err := newSwarmingService(ctx, h, server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &Client{\n\t\tSwarmingService: service,\n\t\tserver: server,\n\t}\n\treturn c, nil\n}", "func NewAWSClient(sess *session.Session, region string) (*AWSClient, error) {\n\tconfig := aws.NewConfig()\n\tsvcEC2Metadata := ec2metadata.New(sess)\n\n\t// get region when the region did not pass via a command-line option.\n\t// attempt get region is following order.\n\t// 1. Load config in AWS SDK for Go\n\t// - see also https://docs.aws.amazon.com/sdk-for-go/api/aws/session/\n\t// 2. Get region via EC2 Metadata\n\t// 3. Set \"ap-northeast-1\" in hardcoding as backward compatibility for previous versions\n\tif region == \"\" {\n\t\tr := *sess.Config.Region\n\n\t\tif r == \"\" {\n\t\t\tr, _ = getRegion(svcEC2Metadata)\n\t\t}\n\n\t\tif r == \"\" {\n\t\t\tr = \"ap-northeast-1\"\n\t\t}\n\n\t\tregion = r\n\t}\n\n\tconfig = config.WithRegion(region)\n\n\treturn &AWSClient{\n\t\tsvcEC2: ec2.New(sess, config),\n\t\tsvcEC2Metadata: svcEC2Metadata,\n\t\tconfig: config,\n\t}, nil\n}", "func New(conf *aws.Config, refresh time.Duration) Client {\n\treturn &store{\n\t\tapi: ec2.NewFromConfig(*conf),\n\t\trefresh: refresh,\n\t\temitter: new(syncutil.SignalEmitter),\n\t}\n}", "func New(\n\tendpoint string,\n\tcontractAddress string,\n\tprivateKey *ecdsa.PrivateKey,\n) (*Client, error) {\n\tclient, err := ethclient.Dial(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tchainID, err := client.NetworkID(context.Background())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tret := &Client{\n\t\tclient: client,\n\t\taddress: crypto.PubkeyToAddress(privateKey.PublicKey),\n\t\tcontractAddress: common.HexToAddress(contractAddress),\n\t\tprivateKey: privateKey,\n\t\tsigner: types.NewEIP155Signer(chainID),\n\t}\n\tcontract, err := tanshell.NewTanshell(ret.contractAddress, client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tret.contract = contract\n\tif err := ret.updateNonce(context.Background()); err != nil {\n\t\treturn nil, err\n\t}\n\tret.ctx, ret.cancel = context.WithCancel(context.Background())\n\treturn ret, nil\n}", "func NewClient(config *ucloud.Config, credential *auth.Credential) *VPCClient {\n\tmeta := ucloud.ClientMeta{Product: \"VPC\"}\n\tclient := ucloud.NewClientWithMeta(config, credential, meta)\n\treturn &VPCClient{\n\t\tclient,\n\t}\n}", "func newInputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *InputService2ProtocolTest {\n\tsvc := &InputService2ProtocolTest{\n\t\tClient: client.New(\n\t\t\tcfg,\n\t\t\tmetadata.ClientInfo{\n\t\t\t\tServiceName: \"inputservice2protocoltest\",\n\t\t\t\tSigningRegion: signingRegion,\n\t\t\t\tEndpoint: endpoint,\n\t\t\t\tAPIVersion: \"2014-01-01\",\n\t\t\t},\n\t\t\thandlers,\n\t\t),\n\t}\n\n\t// Handlers\n\tsvc.Handlers.Sign.PushBack(v4.Sign)\n\tsvc.Handlers.Build.PushBackNamed(restxml.BuildHandler)\n\tsvc.Handlers.Unmarshal.PushBackNamed(restxml.UnmarshalHandler)\n\tsvc.Handlers.UnmarshalMeta.PushBackNamed(restxml.UnmarshalMetaHandler)\n\tsvc.Handlers.UnmarshalError.PushBackNamed(restxml.UnmarshalErrorHandler)\n\n\treturn svc\n}", "func NewRemote(ctx context.Context, conn *grpc.ClientConn) Subjects {\n\treturn &remote{\n\t\tclient: NewServiceClient(conn),\n\t}\n}", "func New(conn *grpc.ClientConn, runtimeID common.Namespace) RuntimeClient {\n\treturn &runtimeClient{\n\t\tcs: consensus.NewConsensusClient(conn),\n\t\tcc: coreClient.NewRuntimeClient(conn),\n\t\truntimeID: runtimeID,\n\t}\n}", "func NewECRClient(opt Options) *ecrClient {\n\treturn &ecrClient{opt: opt}\n}", "func NewMockEC2(ctrl *gomock.Controller) *MockEC2 {\n\tmock := &MockEC2{ctrl: ctrl}\n\tmock.recorder = &MockEC2MockRecorder{mock}\n\treturn mock\n}", "func New(endpoint string) *EcomClient {\n\ttr := &http.Transport{\n\t\tMaxIdleConnsPerHost: 10,\n\t}\n\tclient := &http.Client{\n\t\tTransport: tr,\n\t\tTimeout: timeout,\n\t}\n\n\turl, err := url.Parse(endpoint)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%+v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn &EcomClient{\n\t\tendpoint: endpoint,\n\t\tscheme: url.Scheme,\n\t\thostname: url.Host,\n\t\tport: url.Port(),\n\t\tclient: client,\n\t}\n}", "func newRemoteLoggingClient(ctx context.Context, conn *grpc.ClientConn) (*remoteLoggingClient, error) {\n\tcl := protocol.NewLoggingClient(conn)\n\tstream, err := cl.ReadLogs(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Read the initial response to check success and make sure we have been\n\t// subscribed to logs.\n\tif _, err := stream.Recv(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tl := &remoteLoggingClient{\n\t\tstream: stream,\n\t\tdoneCh: make(chan struct{}),\n\t}\n\n\t// Start a goroutine to call logger for every received ReadLogsResponse.\n\tgo l.runBackground(ctx)\n\n\treturn l, nil\n}", "func New(url string) Client {\n\treturn &clientImpl{\n\t\tRPCClient: jsonrpc.NewRPCClient(url),\n\t\tLogger: slf4go.Get(\"eth-rpc-client\"),\n\t}\n}", "func New(sess *session.Session) ELBv2 {\n\treturn &_elbv2{\n\t\tsvc: elbv2.New(sess),\n\t}\n}", "func NewNetworkInterface(ctx *pulumi.Context,\n\tname string, args *NetworkInterfaceArgs, opts ...pulumi.ResourceOption) (*NetworkInterface, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.SubnetId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'SubnetId'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource NetworkInterface\n\terr := ctx.RegisterResource(\"aws-native:ec2:NetworkInterface\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func New(clientID string, options ...Option) (Client, error) {\n\topts := clientOptions{\n\t\tauthority: base.AuthorityPublicCloud,\n\t\thttpClient: shared.DefaultClient,\n\t}\n\n\tfor _, o := range options {\n\t\to(&opts)\n\t}\n\tif err := opts.validate(); err != nil {\n\t\treturn Client{}, err\n\t}\n\n\tbase, err := base.New(clientID, opts.authority, oauth.New(opts.httpClient), base.WithCacheAccessor(opts.accessor), base.WithClientCapabilities(opts.capabilities), base.WithInstanceDiscovery(!opts.disableInstanceDiscovery))\n\tif err != nil {\n\t\treturn Client{}, err\n\t}\n\treturn Client{base}, nil\n}" ]
[ "0.6973776", "0.632608", "0.63121355", "0.6163207", "0.616059", "0.60730475", "0.6012531", "0.6009894", "0.5945188", "0.59106356", "0.5863934", "0.5777015", "0.57581896", "0.57090247", "0.569607", "0.5663689", "0.56583476", "0.5648572", "0.55632263", "0.55631524", "0.55515754", "0.5532741", "0.5527345", "0.55176145", "0.5515476", "0.5496259", "0.5455513", "0.54439443", "0.53892213", "0.53779876", "0.53728306", "0.53685915", "0.5352653", "0.53297246", "0.5329568", "0.5304093", "0.52985406", "0.5298185", "0.5286258", "0.5280622", "0.52785844", "0.5261515", "0.5255503", "0.52546275", "0.52435935", "0.52367157", "0.5231553", "0.5219799", "0.5216721", "0.51998776", "0.5194509", "0.51790524", "0.51580286", "0.5157439", "0.5156254", "0.5149119", "0.5144679", "0.51401275", "0.51384485", "0.513544", "0.513447", "0.5133142", "0.5115496", "0.5082994", "0.50718504", "0.50478315", "0.50422287", "0.5037737", "0.50347054", "0.5017225", "0.5011301", "0.50107104", "0.500831", "0.49927276", "0.49921575", "0.49907714", "0.49906296", "0.4990382", "0.49837935", "0.49769568", "0.49739844", "0.49673963", "0.49644014", "0.49597993", "0.49519357", "0.49503455", "0.49320275", "0.49304482", "0.49231604", "0.49229777", "0.49175808", "0.49099106", "0.49087507", "0.4908046", "0.490752", "0.49045712", "0.4896009", "0.48939103", "0.48934662", "0.48832905" ]
0.7414689
0
Close tears down all sessions and connections as appropriate
func (ins *EC2RemoteClient) Close() error { return ins.cmdClient.Close() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func destroy() {\n\tif unique.natsconn != nil {\n\t\tunique.natsconn.Close()\n\t}\n\tfor _, dict := range unique.mdb {\n\t\tdict.Close()\n\t}\n\tunique = nil\n}", "func teardown() {\n\tts.Close()\n\tdb.Close()\n}", "func teardown() {\n\tserver1.Close()\n\tserver2.Close()\n\tserver3.Close()\n}", "func (c *client) close() {\n\tc.user.Close()\n\tc.conn.Close()\n\n\tc.sysConn.Exec(\"DROP DATABASE IF EXISTS \" + c.connConfig.Database)\n\tc.sysConn.Close()\n}", "func (srv *server) Close() {\n\tif srv.l == nil {\n\t\tpanic(\"smpptest: server is not started\")\n\t}\n\tsrv.mu.Lock()\n\tdefer srv.mu.Unlock()\n\tfor _, session := range srv.s {\n\t\tsession.Close()\n\t}\n\tsrv.s = map[string]Session{}\n\tsrv.l.Close()\n}", "func (h *Harness) Close() error {\n\th.t.Helper()\n\tif recErr := recover(); recErr != nil {\n\t\tdefer panic(recErr)\n\t}\n\th.dumpDB() // early as possible\n\n\th.tw.WaitAndAssert(h.t)\n\th.slack.WaitAndAssert()\n\th.email.WaitAndAssert()\n\n\th.mx.Lock()\n\th.closing = true\n\th.mx.Unlock()\n\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\tdefer cancel()\n\terr := h.backend.Shutdown(ctx)\n\tif err != nil {\n\t\th.t.Error(\"failed to shutdown backend cleanly:\", err)\n\t}\n\th.backendLogs.Close()\n\n\th.slackS.Close()\n\th.twS.Close()\n\n\th.tw.Close()\n\n\th.pgTime.Close()\n\n\tconn, err := pgx.Connect(ctx, DBURL(\"\"))\n\tif err != nil {\n\t\th.t.Error(\"failed to connect to DB:\", err)\n\t}\n\tdefer conn.Close(ctx)\n\t_, err = conn.Exec(ctx, \"drop database \"+sqlutil.QuoteID(h.dbName))\n\tif err != nil {\n\t\th.t.Errorf(\"failed to drop database '%s': %v\", h.dbName, err)\n\t}\n\n\treturn nil\n}", "func Close() {\n\tsession.Close()\n}", "func (pool *SessionPool) Close() {\n\tpool.rwLock.Lock()\n\tdefer pool.rwLock.Unlock()\n\n\t//TODO(Aiee) append 2 lists\n\tidleLen := pool.idleSessions.Len()\n\tactiveLen := pool.activeSessions.Len()\n\n\t// iterate all sessions\n\tfor i := 0; i < idleLen; i++ {\n\t\tsession := pool.idleSessions.Front().Value.(*pureSession)\n\t\tsession.close()\n\t\tpool.idleSessions.Remove(pool.idleSessions.Front())\n\t}\n\tfor i := 0; i < activeLen; i++ {\n\t\tsession := pool.activeSessions.Front().Value.(*pureSession)\n\t\tsession.close()\n\t\tpool.activeSessions.Remove(pool.activeSessions.Front())\n\t}\n\n\tpool.closed = true\n\tif pool.cleanerChan != nil {\n\t\tclose(pool.cleanerChan)\n\t}\n}", "func (session *session) Close() {\n\t_ = session.Context.Uninit()\n\tsession.Context.Free()\n\n\tif session.Playmic {\n\t\tsession.MicCaptureDevice.Uninit()\n\t\tsession.MicPlaybackDevice.Uninit()\n\t}\n\n\tsession.DefaultPlaybackDevice.Uninit()\n\tsession.MusicPlaybackDevice.Uninit()\n}", "func teardown() {\n\tserver.Close()\n}", "func teardown() {\n\tserver.Close()\n}", "func teardown() {\n\tserver.Close()\n}", "func teardown() {\n\tserver.Close()\n}", "func teardown() {\n\tserver.Close()\n}", "func teardown() {\n\tserver.Close()\n}", "func teardown() {\n\tserver.Close()\n}", "func (c *Session) Close() {\n\tif c.devID != nil {\n\t\terr := c.devID.Close()\n\t\tif err != nil {\n\t\t\tc.log.Warn(fmt.Sprintf(\"Failed to close DevID handle: %v\", err))\n\t\t}\n\t}\n\n\tif c.ak != nil {\n\t\terr := c.ak.Close()\n\t\tif err != nil {\n\t\t\tc.log.Warn(fmt.Sprintf(\"Failed to close attestation key handle: %v\", err))\n\t\t}\n\t}\n\n\tif c.ekHandle != 0 {\n\t\tc.flushContext(c.ekHandle)\n\t}\n\n\tif c.rwc != nil {\n\t\tif closeTPM(c.rwc) {\n\t\t\treturn\n\t\t}\n\n\t\terr := c.rwc.Close()\n\t\tif err != nil {\n\t\t\tc.log.Warn(fmt.Sprintf(\"Failed to close TPM: %v\", err))\n\t\t}\n\t}\n}", "func (tre *Teoregistry) Close() {\n\ttre.session.Close()\n}", "func (s *session) Destroy() {\n\ts.conn.Close()\n}", "func Close() {\n\tif client != nil {\n\t\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\t\tdefer cancel()\n\t\tclient.Disconnect(ctx)\n\t}\n\tdb = nil\n\tclient = nil\n}", "func (session *Session) Close() {\n\tfor _, v := range session.stmtCache {\n\t\tv.Close()\n\t}\n\n\tif session.db != nil {\n\t\t// When Close be called, if session is a transaction and do not call\n\t\t// Commit or Rollback, then call Rollback.\n\t\tif session.Tx != nil && !session.IsCommitedOrRollbacked {\n\t\t\tsession.Rollback()\n\t\t}\n\t\tsession.Tx = nil\n\t\tsession.stmtCache = nil\n\t\tsession.db = nil\n\n\t\tsession.Statement.Init()\n\t\tsession.IsAutoCommit = true\n\t\tsession.IsCommitedOrRollbacked = false\n\t\tsession.IsAutoClose = false\n\t\tsession.AutoResetStatement = true\n\t\tsession.prepareStmt = false\n\n\t\t// processors\n\t\tsession.afterInsertBeans = nil\n\t\tsession.afterUpdateBeans = nil\n\t\tsession.afterDeleteBeans = nil\n\t\tsession.beforeClosures = nil\n\t\tsession.afterClosures = nil\n\t}\n}", "func (s *Session) Close() error {\n\t_, err := s.srv.conn.request(\"DELETE\", \"/_session\", nil, nil, s, 0)\n\treturn err\n}", "func (testEnv *TestEnv) TearDownTestEnv() {\n\ttestEnv.Server.Close()\n\ttestEnv.Server = nil\n\ttestEnv.Mux = nil\n\ttestEnv.Client = nil\n}", "func (db *MongoDatabase) Close() {\n\tdb.global_session.Close()\n}", "func teardown() {\n\t// if kubeTunnel != nil {\n\t// \tlog.Debugf(\"Tearing down tunnel connection to server...\")\n\t// \tkubeTunnel.Close()\n\t// }\n}", "func (sp *SessionProxy) Close() error { return sp.GetSession().Close() }", "func (c *RemoteHTTP) Close() {\n\tc.HTTPClient = nil\n\n\tif c.SSHSession != nil {\n\t\tc.SSHSession.Close()\n\t\tc.SSHSession = nil\n\t}\n\n\tif c.SSHClient != nil {\n\t\tc.SSHClient.Close()\n\t\tc.SSHClient = nil\n\t}\n}", "func Close(ctx context.Context) {\n\tmw := ctx.Value(mwContextKey{}).(sessionMiddleware)\n\tid := ctx.Value(sessionIdContextKey{}).(string)\n\tdelete(mw.sessions, id)\n}", "func Cleanup() {\n\tif conn != nil {\n\t\tconn.Close()\n\t\tconn = nil\n\t\tclient = nil\n\t}\n}", "func (mc *MysqlConn) cleanup() {\n\t// Makes cleanup idempotent\n\tif mc.netConn != nil {\n\t\tif err := mc.netConn.Close(); err != nil {\n\t\t\terrLog.Print(err)\n\t\t}\n\t\tmc.netConn = nil\n\t}\n\tmc.cfg = nil\n}", "func (s *MockSession) Close() {}", "func (p *multiplexer) destroy() {\n\tdefer func() {\n\t\tif !ex.CatchException(recover()) {\n\t\t\tp.status = MUX_CLOSED\n\t\t}\n\t}()\n\t// will not send evt_dt_closed while pending_close was indicated\n\tp.status = MUX_PENDING_CLOSE\n\tp.router.destroy() // destroy queue\n\tp.pool.destroy()\n}", "func (s *Server) Close() error {\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\t// Perform a best-effort final flush.\n\t\tif s.logtail != nil {\n\t\t\ts.logtail.Shutdown(ctx)\n\t\t}\n\t\tif s.logbuffer != nil {\n\t\t\ts.logbuffer.Close()\n\t\t}\n\t}()\n\n\tif _, isMemStore := s.Store.(*mem.Store); isMemStore && s.Ephemeral && s.lb != nil {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\t// Perform a best-effort logout.\n\t\t\ts.lb.LogoutSync(ctx)\n\t\t}()\n\t}\n\n\tif s.netstack != nil {\n\t\ts.netstack.Close()\n\t\ts.netstack = nil\n\t}\n\tif s.shutdownCancel != nil {\n\t\ts.shutdownCancel()\n\t}\n\tif s.lb != nil {\n\t\ts.lb.Shutdown()\n\t}\n\tif s.linkMon != nil {\n\t\ts.linkMon.Close()\n\t}\n\tif s.dialer != nil {\n\t\ts.dialer.Close()\n\t}\n\tif s.localAPIListener != nil {\n\t\ts.localAPIListener.Close()\n\t}\n\tif s.localAPITCPListener != nil {\n\t\ts.localAPITCPListener.Close()\n\t}\n\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfor _, ln := range s.listeners {\n\t\tln.Close()\n\t}\n\ts.listeners = nil\n\n\twg.Wait()\n\treturn nil\n}", "func (db Store) Terminate() {\n\tdb.session.Close()\n}", "func Close(session *mgo.Session) {\n\tsession.Close()\n\t}", "func (b *Backend) Close() {\n\tdefer b.mutex.Unlock()\n\tb.mutex.Lock()\n\tfor _, gtw := range b.gateways {\n\t\tgtw.Close()\n\t}\n\tb.routerConn.Close()\n}", "func (d *Dao) Close() {\n\td.redis.Close()\n\td.mallDB.Close()\n\td.ugcDB.Close()\n\td.ticketDB.Close()\n}", "func (db *DB) Close() {\n\tdb.session.Close()\n}", "func (db *DB) Close() {\n\tdb.session.Close()\n}", "func TeardownConnection() {\n\tRconn.Close()\n}", "func (this *service) close() {\n\tdoit := atomic.CompareAndSwapInt64(&this.closed, 0, 1)\n\tif !doit {\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\t// Let's recover from panic\n\t\tif r := recover(); r != nil {\n\t\t\tglog.Errorf(\"(%d/%s) Recovering from panic: %v\", this.id, this.cid, r)\n\t\t}\n\t}()\n\n\t// Close quit channel, effectively telling all the goroutines it's time to quit\n\tif this.done != nil {\n\t\tglog.Debugf(\"(%s) closing this.done\", this.cid)\n\t\tclose(this.done)\n\t}\n\n\t// Close the network connection\n\tif this.conn != nil {\n\t\tglog.Debugf(\"(%s) closing this.conn\", this.cid)\n\t\tthis.conn.Close()\n\t}\n\n\t// Unsubscribe from all the topics for this client\n\tif this.sess != nil {\n\t\ttopics, _, err := getTopicsQoss(this.sess)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"(%s/%d): %v\", this.cid, this.id, err)\n\t\t} else {\n\t\t\tfor _, t := range topics {\n\t\t\t\tthis.topicsMgr.Unsubscribe([]byte(t), this)\n\t\t\t}\n\t\t}\n\t}\n\n\ttopics.Unregister(this.cid)\n\n\t// Remove the session from session store\n\tif this.sessMgr != nil {\n\t\tthis.sessMgr.Del(this.cid)\n\t}\n\n\t// Close all the buffers and queues\n\tif this.in != nil {\n\t\tglog.Debugf(\"(%s) closing this.in\", this.cid)\n\t\tthis.in.Close()\n\t}\n\n\tif this.out != nil {\n\t\tglog.Debugf(\"(%s) closing this.out\", this.cid)\n\t\tthis.out.Close()\n\t}\n\n\tthis.wg.Wait()\n\n\tthis.conn = nil\n\tthis.in = nil\n\tthis.out = nil\n}", "func TeardownHTTP() {\n\tServer.Close()\n}", "func (s *LdapStore) Shutdown() {\n\tif s.conn != nil {\n\t\ts.conn.Close()\n\t\ts.conn = nil\n\t}\n}", "func (s Session) Close() error {\n\ts.conn.Close()\n\treturn s.cli.Close()\n}", "func (cs *CheckinSession) close() {\n\tcs.server.peerset.Untrust(cs.Auth.Fingerprint())\n\tdelete(cs.server.checkins, cs.Auth.Fingerprint())\n\tcs.result <- errors.New(\"session closed\")\n}", "func (d *Abstraction) CloseSession() {\n\tfor k, v := range d.Sigmap {\n\t\tdelete(d.Sigmap, k)\n\t\tclose(v)\n\t}\n\td.Conn.RemoveSignal(d.Recv)\n\td.Conn.Close()\n}", "func (rt *RethinkDB) Close() {\n\trt.session.Close()\n}", "func Close() {\n\t_db.Close()\n\t_db = nil\n}", "func (p *Pool) Destroy() {\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tp.factory = nil\n\tif p.conns == nil {\n\t\treturn\n\t}\n\n\tfor v := range p.conns {\n\t\tif v != nil {\n\t\t\tp.Close(v)\n\t\t}\n\t}\n\tp.conns = nil\n\n}", "func (ts *TokenStore) Close() {\n\tts.session.Close()\n}", "func CloseMongoConn() {\n\tmongoStore.session.Close()\n}", "func (ds *DataStore) Close() {\n\tds.MongoSession.Close()\n}", "func (s *session) Close() error {\n\tserverSessions.Dec()\n\ts.closeOnce.Do(func() {\n\t\t// closing needs to happen asynchronously because the last client\n\t\t// (session writer) will try to close this session, causing a deadlock\n\t\t// because of closeOnce\n\t\tgo func() {\n\t\t\ts.log.Infof(\"Closing session %v\", s.id)\n\t\t\tif s.term != nil {\n\t\t\t\ts.term.Close()\n\t\t\t}\n\t\t\tclose(s.closeC)\n\n\t\t\t// close all writers in our multi-writer\n\t\t\ts.writer.Lock()\n\t\t\tdefer s.writer.Unlock()\n\t\t\tfor writerName, writer := range s.writer.writers {\n\t\t\t\ts.log.Infof(\"Closing session writer: %v\", writerName)\n\t\t\t\tcloser, ok := io.Writer(writer).(io.WriteCloser)\n\t\t\t\tif ok {\n\t\t\t\t\tcloser.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t})\n\treturn nil\n}", "func tearDown() {\n\tserver.Close()\n}", "func (m *MultiConnPool) Close() {\n\tfor _, p := range m.Pools {\n\t\tp.Close()\n\t}\n}", "func (a *Admin) Close() {\n\ta.Connections().Reset()\n}", "func (m *MongoDB) Close() {\n\tm.db.Session.Close()\n}", "func (conn *Conn) Close() error {\n\tvar err error\n\tif conn.sess != nil {\n\t\terr = conn.sess.Close()\n\t\tconn.sess = nil\n\t}\n\tif conn.pc != nil {\n\t\terr = conn.pc.Close()\n\t\tconn.pc = nil\n\t}\n\treturn err\n}", "func (s *Session) close() {\n\tif atomic.LoadUint64(&s.connectedUsers) > 0 {\n\t\treturn\n\t}\n\ts.client.Close()\n}", "func (s *MongoStore) Close() {\n\tif s.session != nil {\n\t\ts.session.Close()\n\t}\n}", "func CleanupMongoSession() {\n\tif mongo == nil {\n\t\treturn\n\t}\n\tmongo.Close()\n\ttime.Sleep(time.Second)\n\n\tmongo = nil\n}", "func (m *MongoDB) Close() {\n\tm.sess.Close()\n}", "func DestroyConnection() {\n\n\tdb.Close()\n\n}", "func (d *Driver) Close() {\n\tappiumReq := &appiumRequest{\n\t\t\"DELETE\",\n\t\tnil,\n\t\t\"/wd/hub/session/\" + d.sessionID,\n\t}\n\n\tresp := doAppiumRequest(appiumReq, d.driverClient, \"\")\n\n\tstatusCodeErrorHandler(\n\t\tresp.StatusCode, 500,\n\t\t\"appigo: unable to close session\",\n\t)\n}", "func (db *DB) Close() {\n\tif err := db.Client.Disconnect(context.TODO()); err != nil {\n\t\tlog.Printf(\"Error closing mongo storage: %s\\n\", err)\n\t}\n}", "func (tb *TelemetryBuffer) close() {\n\tif tb.client != nil {\n\t\ttb.client.Close()\n\t}\n\n\tif tb.listener != nil {\n\t\ttb.listener.Close()\n\t}\n\n\tfor _, conn := range tb.connections {\n\t\tif conn != nil {\n\t\t\tconn.Close()\n\t\t}\n\t}\n}", "func (tb *TelemetryBuffer) close() {\n\tif tb.client != nil {\n\t\ttb.client.Close()\n\t}\n\n\tif tb.listener != nil {\n\t\ttb.listener.Close()\n\t}\n\n\tfor _, conn := range tb.connections {\n\t\tif conn != nil {\n\t\t\tconn.Close()\n\t\t}\n\t}\n}", "func (mongoDBConnect MongoDBConnect) CloseSession() {\n\tdefer mongoDBConnect.mongoSession.Close()\n}", "func (p *DBPool) Close() {\n\tfor _, db := range p.dbs {\n\t\tdb.Close()\n\t}\n}", "func (s *sshSession) Close() {\n\ts.Session.Close()\n\ts.conn.Close()\n}", "func (fs *FakeSession) Close() error {\n\treturn nil\n}", "func (repo *VesselsRepository) Close() {\n\trepo.session.Close()\n}", "func (client *AMIClient) Close() {\n\tif client.loggedIn {\n\t\tclient.Action(\"Logoff\", nil, time.Second*3)\n\t}\n\tclient.connRaw.Close()\n}", "func (dbInst *DB) Close() {\n\tdbInst.mux.Lock()\n\tif dbInst.dbState == closed {\n\t\tdbInst.mux.Unlock()\n\t\treturn\n\t}\n\n\tdefer dbInst.mux.Unlock()\n\tfor _, cfHandler := range dbInst.cfHandlesMap {\n\t\tcfHandler.Destroy()\n\t}\n\tdbInst.rocksDB.Close()\n\tdbInst.dbState = closed\n}", "func (s *Server) Close() {\n s.setupConn.Close()\n}", "func (m *Mongo) Close() {\n\tm.Session.Close()\n}", "func (m *Mongo) Close() {\n\tm.Session.Close()\n}", "func (set *HostSet) Close() error {\n\tfor hostKey, lh := range set.sessions {\n\t\tlh.mu.Lock()\n\t\tif lh.s != nil {\n\t\t\tlh.s.Close()\n\t\t\tlh.s = nil\n\t\t}\n\t\tdelete(set.sessions, hostKey)\n\t}\n\treturn nil\n}", "func (s *Server) Close() {\n\ts.invoiceTopic.Close()\n\ts.walletPoller.Stop()\n\ts.db.Close()\n}", "func (t *tOps) close() {\n\tt.bpool.Close()\n\tt.cache.Close()\n\tif t.bcache != nil {\n\t\tt.bcache.CloseWeak()\n\t}\n}", "func (conn *MongoConn) Close() {\n\tconn.Session.Close()\n}", "func (env *Env) Close() {\n\tenv.grpcCC.Close()\n\tenv.grpcServer.Stop()\n\tenv.mapEnv.Close()\n\tenv.db.Close()\n}", "func (c *connection) Close() {\n\tbaseurl := \"http://fritz.box/webservices/homeautoswitch.lua\"\n\tparameters := make(map[string]string)\n\tparameters[\"sid\"] = c.sid\n\tparameters[\"logout\"] = \"logout\"\n\tUrl := prepareRequest(baseurl, parameters)\n\tsendRequest(Url)\n}", "func (t *tInfo) teardown() {\n\tt.recorders.close()\n\n\tif t.apiClient != nil {\n\t\tt.apiClient.ClusterV1().Version().Delete(context.Background(), &api.ObjectMeta{Name: t.testName})\n\t\tt.apiClient.Close()\n\t\tt.apiClient = nil\n\t}\n\n\tif t.esClient != nil {\n\t\tt.esClient.Close()\n\t}\n\n\ttestutils.StopElasticsearch(t.elasticsearchName, t.elasticsearchDir)\n\n\tif t.mockCitadelQueryServer != nil {\n\t\tt.mockCitadelQueryServer.Stop()\n\t\tt.mockCitadelQueryServer = nil\n\t}\n\n\tif t.evtsMgr != nil {\n\t\tt.evtsMgr.Stop()\n\t\tt.evtsMgr = nil\n\t}\n\n\tt.evtProxyServices.Stop()\n\n\tif t.apiServer != nil {\n\t\tt.apiServer.Stop()\n\t\tt.apiServer = nil\n\t}\n\n\t// stop certificate server\n\ttestutils.CleanupIntegTLSProvider()\n\n\tif t.mockResolver != nil {\n\t\tt.mockResolver.Stop()\n\t\tt.mockResolver = nil\n\t}\n\n\t// remove the local persistent events store\n\tt.logger.Infof(\"removing events store %s\", t.storeConfig.Dir)\n\tos.RemoveAll(t.storeConfig.Dir)\n\n\tt.logger.Infof(\"completed test\")\n}", "func (dbWoker *DomainInformationStorage)Close() {\n\tdbWoker.session.Close()\n}", "func (gs *Service) closeSession(session Session) {\n\t//TODO: delete Chat connection\n\tfor client := range session.hub.Clients {\n\t\t_ = client.Conn.Close()\n\t}\n\tdelete(gs.sessions, session.sessionID)\n}", "func (c *TLWClient) TearDown() error {\n\treturn c.conn.Close()\n}", "func (m *MongoCrypt) Close() {\n\tC.mongocrypt_destroy(m.wrapped)\n\tif m.httpClient == httputil.DefaultHTTPClient {\n\t\thttputil.CloseIdleHTTPConnections(m.httpClient)\n\t}\n}", "func (m *Store) Close() {\n\tif m.session != nil {\n\t\tm.session.Close()\n\t}\n}", "func teardownMuxTest(hc *http.Client, backend *httptest.Server, provider *httptest.Server) {\n\tprovider.Close()\n\tbackend.Close()\n}", "func (s *IMAPConnection) Close() {\n\tif s.conn != nil {\n\t\ts.conn.Logout()\n\t}\n\ts.conn = nil\n}", "func (p *pgTester) teardown() error {\n\tvar err error\n\tif err = p.testDbConn.Close(); err != nil {\n\t\treturn err\n\t}\n\tp.testDbConn = nil\n\tif err = p.dropDB(p.TestDBName); err != nil {\n\t\treturn err\n\t}\n\tif p.liveDbConn != nil {\n\t\tif err = p.liveDbConn.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tp.liveDbConn = nil\n\t}\n\tif p.liveTestDbConn != nil {\n\t\tif err = p.liveTestDbConn.Close(); err != nil {\n\n\t\t\treturn err\n\t\t}\n\t\tp.liveTestDbConn = nil\n\t\tif err = p.dropDB(p.LiveTestDBName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn os.Remove(p.pgPassFile)\n}", "func (conn *Connection) Close() (err error) {\n\tif !conn.IsConnected() {\n\t\treturn nil //?\n\t}\n\n\t// perform a rollback\n\tif err = conn.Rollback(); err != nil {\n\t\tsetErrAt(err, \"Close[rollback]\")\n\t\treturn\n\t}\n\tconn.srvMtx.Lock()\n\tdefer conn.srvMtx.Unlock()\n\n\t// logoff of the server\n\tif conn.sessionHandle != nil {\n\t\t// Py_BEGIN_ALLOW_THREADS\n\t\tif err = conn.environment.CheckStatus(C.OCISessionEnd((conn.handle),\n\t\t\tconn.environment.errorHandle, conn.sessionHandle,\n\t\t\tC.OCI_DEFAULT), \"Close[end session]\"); err != nil {\n\t\t\treturn\n\t\t}\n\t\tC.OCIHandleFree(unsafe.Pointer(conn.handle), C.OCI_HTYPE_SVCCTX)\n\t}\n\tconn.handle = nil\n\tif conn.serverHandle != nil {\n\t\tif err = conn.environment.CheckStatus(\n\t\t\tC.OCIServerDetach(conn.serverHandle, conn.environment.errorHandle, C.OCI_DEFAULT),\n\t\t\t\"Close[server detach]\"); err != nil {\n\t\t\treturn\n\t\t}\n\t\tconn.serverHandle = nil\n\t}\n\treturn nil\n}", "func (d *Dao) Close() {\n\tif d.redis != nil {\n\t\td.redis.Close()\n\t}\n\tif d.mc != nil {\n\t\td.mc.Close()\n\t}\n\tif d.db != nil {\n\t\td.db.Close()\n\t}\n}", "func Close() {\n\tif xormengine != nil {\n\t\terr := xormengine.Close()\n\t\tif err != nil {\n\t\t\tlogger.Info(\"DB connection has been shut down gracefully\")\n\t\t} else {\n\t\t\tlogger.Error(\"Error closing DB connection\", zap.Error(err))\n\t\t}\n\t}\n}", "func (c *Cluster) Close() {\n\tc.sessionManager.Close()\n\tc.channelManager.Close()\n}", "func (srv *MockTestServer) Close() {\n\tif srv.NonTLS.Instance != nil {\n\t\tsrv.NonTLS.Instance.Close()\n\t}\n\tif srv.TLS.Instance != nil {\n\t\tsrv.TLS.Instance.Close()\n\t}\n}", "func (d *Dumper) Cleanup() {\n\td.client.Close()\n\td.adminClient.Close()\n}", "func (d *dao) Close() {\n\t d.cache.Close()\n\t d.db.Close()\n\t d.cache.Close()\n}", "func (t *TestDB) Close() {\n\tt.client.Disconnect(context.Background())\n}", "func (d *Discord) Close() {\n\td.session.Close()\n}" ]
[ "0.728361", "0.7082861", "0.7051466", "0.7046239", "0.68948776", "0.6801976", "0.67688215", "0.66486776", "0.6642524", "0.66257674", "0.66257674", "0.66257674", "0.66257674", "0.66257674", "0.66257674", "0.66257674", "0.6618159", "0.66098464", "0.66039705", "0.6602691", "0.6572063", "0.6521356", "0.6508538", "0.6503077", "0.6477539", "0.6455734", "0.6439525", "0.6427068", "0.6407429", "0.64064366", "0.6396955", "0.6341447", "0.6339362", "0.62952375", "0.6287519", "0.627703", "0.62744975", "0.6264873", "0.6264873", "0.6259533", "0.62484396", "0.6246121", "0.62424034", "0.624144", "0.6241354", "0.6227621", "0.62271905", "0.6215046", "0.6214684", "0.618637", "0.6177395", "0.61676645", "0.61661977", "0.6161432", "0.6154516", "0.6152838", "0.6149137", "0.61413896", "0.61312556", "0.6126837", "0.61264795", "0.6124871", "0.61222", "0.61187595", "0.6108438", "0.6106788", "0.6106788", "0.6095021", "0.60849214", "0.607962", "0.6076601", "0.60742265", "0.6065864", "0.60626113", "0.6061273", "0.6059202", "0.6059202", "0.60526484", "0.60441786", "0.6043245", "0.60401225", "0.6034373", "0.60332495", "0.6031051", "0.60308546", "0.6028582", "0.6019515", "0.6019279", "0.6005869", "0.5989693", "0.5988202", "0.5986402", "0.59824735", "0.5981509", "0.59732234", "0.5971657", "0.5970849", "0.5969684", "0.5969613", "0.59646195", "0.59639883" ]
0.0
-1
startInstance starts an EC2 instance, and waits for it to become ready
func (ins *EC2RemoteClient) startInstance() error { log.Printf("Starting EC2 Instance %s", ins.InstanceID) _, err := ins.ec2Client.StartInstances(&ec2.StartInstancesInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})}) if err != nil { return fmt.Errorf("Error starting instance : %s", err) } log.Printf("Waiting for Instance %s to become ready (may take a few minutes)", ins.InstanceID) err = ins.ec2Client.WaitUntilInstanceStatusOk(&ec2.DescribeInstanceStatusInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})}) if err != nil { return fmt.Errorf("Error waiting for instance to become available : %s", err) } return err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func startInstance(ec2Service *ec2.EC2, instance *ec2.Instance) error {\n\tinstanceState, err := getInstanceState(*instance)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif instanceState == \"shutting-down\" || instanceState == \"terminated\" || instanceState == \"stopping\" || instanceState == \"stopped\" {\n\t\tfmt.Errorf(\"instance stopped or terminated\")\n\t}\n\n\tinstanceId := *instance.InstanceId\n\tinput := &ec2.StartInstancesInput{\n\t\tInstanceIds: []*string {\n\t\t\taws.String(instanceId),\n\t\t},\n\t}\n\n\t_, err = ec2Service.StartInstances(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"starting...\")\n\treturn nil\n}", "func (p *ProxMox) StartInstance(ctx *lepton.Context, instanceID string) error {\n\n\treq, err := http.NewRequest(\"POST\", p.apiURL+\"/api2/json/nodes/\"+p.nodeNAME+\"/qemu/\"+instanceID+\"/status/start\", nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\treq.Header.Add(\"Authorization\", \"PVEAPIToken=\"+p.tokenID+\"=\"+p.secret)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\t_, err = io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func runAndWaitForInstance(svc *ec2.EC2, name string, params *ec2.RunInstancesInput) (ec2.Instance, error) {\n\trunResult, err := svc.RunInstances(params)\n\tif err != nil {\n\t\treturn ec2.Instance{}, gruntworkerrors.WithStackTrace(err)\n\t}\n\n\tif len(runResult.Instances) == 0 {\n\t\terr := errors.New(\"Could not create test EC2 instance\")\n\t\treturn ec2.Instance{}, gruntworkerrors.WithStackTrace(err)\n\t}\n\n\terr = svc.WaitUntilInstanceExists(&ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t&ec2.Filter{\n\t\t\t\tName: awsgo.String(\"instance-id\"),\n\t\t\t\tValues: []*string{runResult.Instances[0].InstanceId},\n\t\t\t},\n\t\t},\n\t})\n\n\tif err != nil {\n\t\treturn ec2.Instance{}, gruntworkerrors.WithStackTrace(err)\n\t}\n\n\t// Add test tag to the created instance\n\t_, err = svc.CreateTags(&ec2.CreateTagsInput{\n\t\tResources: []*string{runResult.Instances[0].InstanceId},\n\t\tTags: []*ec2.Tag{\n\t\t\t{\n\t\t\t\tKey: awsgo.String(\"Name\"),\n\t\t\t\tValue: awsgo.String(name),\n\t\t\t},\n\t\t},\n\t})\n\n\tif err != nil {\n\t\treturn ec2.Instance{}, gruntworkerrors.WithStackTrace(err)\n\t}\n\n\t// EC2 Instance must be in a running before this function returns\n\terr = svc.WaitUntilInstanceRunning(&ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t&ec2.Filter{\n\t\t\t\tName: awsgo.String(\"instance-id\"),\n\t\t\t\tValues: []*string{runResult.Instances[0].InstanceId},\n\t\t\t},\n\t\t},\n\t})\n\n\tif err != nil {\n\t\treturn ec2.Instance{}, gruntworkerrors.WithStackTrace(err)\n\t}\n\n\treturn *runResult.Instances[0], nil\n\n}", "func (c *Client) StartInstance(id string) error {\n\n\tactionRequest := core.InstanceActionRequest{}\n\tactionRequest.Action = core.InstanceActionActionStart\n\tactionRequest.InstanceId = &id\n\n\tstartResp, err := c.computeClient.InstanceAction(context.Background(), actionRequest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// wait until lifecycle status is Running\n\tpollUntilRunning := func(r common.OCIOperationResponse) bool {\n\t\tif converted, ok := r.Response.(core.GetInstanceResponse); ok {\n\t\t\treturn converted.LifecycleState != core.InstanceLifecycleStateRunning\n\t\t}\n\t\treturn true\n\t}\n\n\tpollingGetRequest := core.GetInstanceRequest{\n\t\tInstanceId: startResp.Instance.Id,\n\t\tRequestMetadata: helpers.GetRequestMetadataWithCustomizedRetryPolicy(pollUntilRunning),\n\t}\n\n\t_, err = c.computeClient.GetInstance(context.Background(), pollingGetRequest)\n\n\treturn err\n}", "func (p *OnPrem) StartInstance(ctx *Context, instancename string) error {\n\treturn fmt.Errorf(\"Operation not supported\")\n}", "func (p *OnPrem) StartInstance(ctx *Context, instancename string) error {\n\treturn fmt.Errorf(\"Operation not supported\")\n}", "func (a *Agent) spawnInstance(ctx context.Context, c instance.Config) {\n\tinst, err := a.instanceFactory(a.cfg.Global, c, a.cfg.WALDir, a.logger)\n\tif err != nil {\n\t\tlevel.Error(a.logger).Log(\"msg\", \"failed to create instance\", \"err\", err)\n\t\treturn\n\t}\n\n\tfor {\n\t\terr = inst.Run(ctx)\n\t\tif err != nil && err != context.Canceled {\n\t\t\tinstanceAbnormalExits.WithLabelValues(c.Name).Inc()\n\t\t\tlevel.Error(a.logger).Log(\"msg\", \"instance stopped abnormally, restarting after backoff period\", \"err\", err, \"backoff\", a.cfg.InstanceRestartBackoff, \"instance\", c.Name)\n\t\t\ttime.Sleep(a.cfg.InstanceRestartBackoff)\n\t\t} else {\n\t\t\tlevel.Info(a.logger).Log(\"msg\", \"stopped instance\", \"instance\", c.Name)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (c *Client) StartInstance(instanceId string) error {\n\treturn StartInstance(c, instanceId)\n}", "func (i *InstanceServiceHandler) Start(ctx context.Context, instanceID string) error {\n\turi := fmt.Sprintf(\"%s/%s/start\", instancePath, instanceID)\n\n\treq, err := i.client.NewRequest(ctx, http.MethodPost, uri, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.client.DoWithContext(ctx, req, nil)\n}", "func (c *EC2) createAWSEC2Instance(input *RunInstancesInput) (r aws.Referencer, attr aws.Attrabuter, err error) {\n\n\truninstancesrequest := input\n\treservation, err := RunInstances(runinstancesrequest)\n\tif err == nil {\n\t\tdescribeinstancesrequest := &DescribeInstancesInput{}\n\t\tif err := awsutil.CopyValue(describeinstancesrequest, \"InstanceIds\", reservation, \"Instances[].InstanceId\"); err != nil {\n\t\t\treturn reservation, reservation, err\n\t\t}\n\t\tif err := WaitUntilInstanceRunning(describeinstancesrequest); err != nil {\n\t\t\treturn reservation, reservation, err\n\t\t}\n\n\t} else {\n\t\treturn nil, nil, err\n\t}\n\tstartinstancesrequest := &StartInstancesInput{}\n\tif err := awsutil.CopyValue(startinstancesrequest, \"InstanceIds\", reservation, \"Instances[].InstanceId\"); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tstartinstancesresult, err := StartInstances(startinstancesrequest)\n\tif err == nil {\n\t\tdescribeinstancesrequest := &DescribeInstancesInput{}\n\t\tif err := awsutil.CopyValue(describeinstancesrequest, \"InstanceIds\", reservation, \"Instances[].InstanceId\"); err != nil {\n\t\t\treturn reservation, reservation, err\n\t\t}\n\t\tif err := WaitUntilInstanceRunning(describeinstancesrequest); err != nil {\n\t\t\treturn reservation, reservation, err\n\t\t}\n\n\t} else {\n\t\treturn nil, nil, err\n\t}\n\treturn reservation, reservation, nil\n}", "func (c *TestClient) StartInstance(project, zone, name string) error {\n\tif c.StartInstanceFn != nil {\n\t\treturn c.StartInstanceFn(project, zone, name)\n\t}\n\treturn c.client.StartInstance(project, zone, name)\n}", "func StartInstance(computeService *compute.Service) (*compute.Operation, error) {\n\treturn computeService.Instances.Start(ProjectID, Zone, InstanceName).Do()\n}", "func (a *AliyunInstanceAttribute) startBastionHostInstance() {\n\tattemptCnt := 0\n\tfor attemptCnt < 60 {\n\t\tres, err := ExecCmdReturnOutput(\"bash\", \"-c\", \"aliyun ecs DescribeInstanceAttribute --InstanceId=\"+a.BastionInstanceID)\n\t\tcheckError(err)\n\t\tdecodedQuery := decodeAndQueryFromJSONString(res)\n\t\tstatus, err := decodedQuery.String(\"Status\")\n\t\tcheckError(err)\n\t\tif status == \"Running\" {\n\t\t\ttime.Sleep(time.Second * 30)\n\t\t\tfmt.Println(\"Bastion host started.\")\n\t\t\tbreak\n\t\t} else if status == \"Stopped\" {\n\t\t\tfmt.Println(\"Starting bastion host...\")\n\t\t\t_, err = ExecCmdReturnOutput(\"bash\", \"-c\", \"aliyun ecs StartInstance --InstanceId=\"+a.BastionInstanceID)\n\t\t\tcheckError(err)\n\t\t} else if status == \"Starting\" {\n\t\t\tfmt.Println(\"Waiting for bastion host to start...\")\n\t\t} else if status == \"Stopping\" {\n\t\t\tfmt.Println(\"Bastion host is currently stopping...\")\n\t\t}\n\t\ttime.Sleep(time.Second * 2)\n\t\tattemptCnt++\n\t}\n\tif attemptCnt == 60 {\n\t\tfmt.Println(\"Bastion host starting time out. Please try again.\")\n\t\tos.Exit(2)\n\t}\n\tfmt.Println(\"Allocating bastion host IP address...\")\n\tres, err := ExecCmdReturnOutput(\"bash\", \"-c\", \"aliyun ecs AllocatePublicIpAddress --InstanceId=\"+a.BastionInstanceID)\n\tcheckError(err)\n\tdecodedQuery := decodeAndQueryFromJSONString(res)\n\ta.BastionIP, err = decodedQuery.String(\"IpAddress\")\n\tcheckError(err)\n\ttime.Sleep(time.Second * 10)\n\tfmt.Println(\"Bastion host IP address allocated.\")\n}", "func (p *ProcessDefinition) StartInstance(by QueryProcessDefinitionBy, req ReqStartInstance) (processDefinition *ResStartedProcessDefinition, err error) {\n\tprocessDefinition = &ResStartedProcessDefinition{}\n\tres, err := p.client.doPostJson(\"/process-definition/\"+by.String()+\"/start\", map[string]string{}, &req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = p.client.readJsonResponse(res, processDefinition)\n\treturn\n}", "func startInstance(cs *compute.Service, w http.ResponseWriter) {\n\toperation, err := StartInstance(cs)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Fatal(err)\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tdata, _ := operation.MarshalJSON()\n\tw.Write(data)\n}", "func (m *EC2Client) StartEC2Instances(instanceIDs []*string) (*ec2.StartInstancesOutput, error) {\n\tresult, err := m.EC2API.StartInstances(&ec2.StartInstancesInput{\n\t\tInstanceIds: instanceIDs,\n\t})\n\tif err != nil {\n\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\treturn nil, awsErr\n\t\t}\n\t}\n\treturn result, nil\n}", "func WaitForInstance(commandID, instanceID *string, wg *sync.WaitGroup) {\n\n\tdefer wg.Done()\n\tvar err error\n\n\terr = ssmSvc.WaitUntilCommandExecuted(&ssm.GetCommandInvocationInput{\n\t\tCommandId: commandID,\n\t\tInstanceId: instanceID,\n\t})\n\n\tif err != nil {\n\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase request.WaiterResourceNotReadyErrorCode:\n\t\t\t\texitCode = 1\n\t\t\tdefault:\n\t\t\t\tfmt.Printf(\"ERROR waiting for instance %s to execute: %s\\n\", *instanceID, err)\n\t\t\t}\n\t\t}\n\t}\n\n}", "func (ins *EC2RemoteClient) makeReady() error {\n\t// Check Instance is running - will error if instance doesn't exist\n\tresult, err := ins.ec2Client.DescribeInstanceStatus(&ec2.DescribeInstanceStatusInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting instance status : %s\", err)\n\t}\n\n\t// Start instance if needed\n\tif len(result.InstanceStatuses) == 0 || *result.InstanceStatuses[0].InstanceState.Name != \"running\" {\n\t\terr = ins.startInstance()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error starting instance : %s\", err)\n\t\t}\n\t}\n\n\t// Get Public IP address from ec2\n\terr = ins.getIPAddress()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting IP address : %s\", err)\n\t}\n\n\t// Set up SSH connection\n\tins.cmdClient, err = sshCmdClient.NewSSHCmdClient(ins.instanceIP, ins.sshCredentials)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Check we can at least run a trivial command\n\texitStatus, err := ins.RunCommand(\"true\")\n\tif err != nil || exitStatus != 0 {\n\t\treturn fmt.Errorf(\"Error running commands on instance : %s\", err)\n\t}\n\n\treturn err\n}", "func waitForAWSInstances(api *ec2.EC2, ids []*string, d time.Duration) error {\n\tafter := time.After(d)\n\n\tonline := make(map[string]bool)\n\n\tfor len(ids) != len(online) {\n\t\tselect {\n\t\tcase <-after:\n\t\t\treturn fmt.Errorf(\"timed out waiting for instances to run\")\n\t\tdefault:\n\t\t}\n\n\t\t// don't make api calls too quickly, or we will hit the rate limit\n\n\t\ttime.Sleep(10 * time.Second)\n\n\t\tgetinst := &ec2.DescribeInstancesInput{\n\t\t\tInstanceIds: ids,\n\t\t}\n\n\t\tinsts, err := api.DescribeInstances(getinst)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, r := range insts.Reservations {\n\t\t\tfor _, i := range r.Instances {\n\t\t\t\t// skip instances known to be up\n\t\t\t\tif online[*i.InstanceId] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// \"running\"\n\t\t\t\tif *i.State.Code == int64(16) {\n\t\t\t\t\t// XXX: ssh is a terrible way to check this, but it is all we have.\n\t\t\t\t\tc, err := net.DialTimeout(\"tcp\", *i.PublicIpAddress+\":22\", 10*time.Second)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tc.Close()\n\n\t\t\t\t\tonline[*i.InstanceId] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func cmdStart() {\n\tswitch state := status(B2D.VM); state {\n\tcase vmUnregistered:\n\t\tlog.Fatalf(\"%s is not registered.\", B2D.VM)\n\tcase vmRunning:\n\t\tlog.Printf(\"%s is already running.\", B2D.VM)\n\tcase vmPaused:\n\t\tlog.Printf(\"Resuming %s\", B2D.VM)\n\t\tif err := vbm(\"controlvm\", B2D.VM, \"resume\"); err != nil {\n\t\t\tlog.Fatalf(\"Failed to resume vm: %s\", err)\n\t\t}\n\t\taddr := fmt.Sprintf(\"localhost:%d\", B2D.SSHPort)\n\t\tif err := read(addr); err != nil {\n\t\t\tlog.Fatalf(\"Failed to connect to SSH port at %s: %s\", addr, err)\n\t\t}\n\t\tlog.Printf(\"Resumed.\")\n\tcase vmSaved, vmPoweroff, vmAborted:\n\t\tlog.Printf(\"Starting %s...\", B2D.VM)\n\t\tif err := vbm(\"startvm\", B2D.VM, \"--type\", \"headless\"); err != nil {\n\t\t\tlog.Fatalf(\"Failed to start vm: %s\", err)\n\t\t}\n\t\tlog.Printf(\"Waiting for SSH server to start...\")\n\t\taddr := fmt.Sprintf(\"localhost:%d\", B2D.SSHPort)\n\t\tif err := read(addr); err != nil {\n\t\t\tlog.Fatalf(\"Failed to connect to SSH port at %s: %s\", addr, err)\n\t\t}\n\t\tlog.Printf(\"Started.\")\n\tdefault:\n\t\tlog.Fatalf(\"Cannot start %s from state %.\", B2D.VM, state)\n\t}\n\n\t// Check if $DOCKER_HOST ENV var is properly configured.\n\tDockerHost := getenv(\"DOCKER_HOST\", \"\")\n\tif DockerHost != fmt.Sprintf(\"tcp://localhost:%d\", B2D.DockerPort) {\n\t\tfmt.Printf(\"\\nTo connect the docker client to the Docker daemon, please set:\\n\")\n\t\tfmt.Printf(\"export DOCKER_HOST=tcp://localhost:%d\\n\\n\", B2D.DockerPort)\n\t}\n}", "func (awsI *Ec2Instance) CreateInstance(volumeSize int, zookeeperSize int, idleTimeout int, bastionVolSnapshotId string) error {\n\terr := awsI.runTerraformInit()\n\n\tif (bastionVolSnapshotId != \"\") {\n\t\tbastionVolData, err := Asset(\"etc/extras/bastion_volume.tf\")\n\t\tif err != nil {\n\t\t\tawsI.Ctx.ConsoleLog(0, \"Error while initializing terraform for the additional bastion volume: %s\\n\", err)\n\t\t\treturn nil\n\t\t}\n\t\tbastionVolumePath := path.Join(awsI.DeployDir, \"etc\", \"terraform\", \"instance\", \"bastion_volume.tf\")\n\t\tbastionVolContents := string(bastionVolData[:])\n\t\tsdutils.WriteFile(bastionVolumePath, fmt.Sprintf(bastionVolContents, bastionVolSnapshotId, awsI.PrivateKey))\n\t}\n\n\terr = awsI.runTerraformApply(volumeSize, zookeeperSize, \"0.0.0.0/32\", idleTimeout, \"Creating the instance VMs...\")\n\tif err != nil {\n\t\tawsI.Ctx.ConsoleLog(1, \"Failed to create the instance.\\n\")\n\t\treturn err\n\t}\n\tawsI.Ctx.ConsoleLog(1, \"Successfully created the instance.\\n\")\n\treturn nil\n}", "func (c *Client) CreateInstance(displayName, availabilityDomain, compartmentID, nodeShape, nodeImageName, nodeSubnetID, sshUser, authorizedKeys string, nodeOCPUs, nodeMemoryInGBs int) (string, error) {\n\n\treq := identity.ListAvailabilityDomainsRequest{}\n\treq.CompartmentId = &compartmentID\n\tads, err := c.identityClient.ListAvailabilityDomains(context.Background(), req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Just in case shortened or lower-case availability domain name was used\n\tlog.Debugf(\"Resolving availability domain from %s\", availabilityDomain)\n\tfor _, ad := range ads.Items {\n\t\tif strings.Contains(*ad.Name, strings.ToUpper(availabilityDomain)) {\n\t\t\tlog.Debugf(\"Availability domain %s\", *ad.Name)\n\t\t\tavailabilityDomain = *ad.Name\n\t\t}\n\t}\n\n\timageID, err := c.getImageID(compartmentID, nodeImageName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Create the launch compute instance request\n\trequest := core.LaunchInstanceRequest{\n\t\tLaunchInstanceDetails: core.LaunchInstanceDetails{\n\t\t\tAvailabilityDomain: &availabilityDomain,\n\t\t\tCompartmentId: &compartmentID,\n\t\t\tShape: &nodeShape,\n\t\t\tCreateVnicDetails: &core.CreateVnicDetails{\n\t\t\t\tSubnetId: &nodeSubnetID,\n\t\t\t},\n\t\t\tDisplayName: &displayName,\n\t\t\tMetadata: map[string]string{\n\t\t\t\t\"ssh_authorized_keys\": authorizedKeys,\n\t\t\t\t\"user_data\": base64.StdEncoding.EncodeToString(createCloudInitScript(sshUser)),\n\t\t\t},\n\t\t\tSourceDetails: core.InstanceSourceViaImageDetails{\n\t\t\t\tImageId: imageID,\n\t\t\t},\n\t\t},\n\t}\n\n\tif nodeOCPUs > 0 {\n\t\toCPUs := float32(nodeOCPUs)\n\t\tmemoryInGBs := float32(nodeMemoryInGBs)\n\n\t\tLaunchInstanceShapeConfigDetails := core.LaunchInstanceShapeConfigDetails{\n\t\t\tOcpus: &oCPUs,\n\t\t\tMemoryInGBs: &memoryInGBs,\n\t\t}\n\t\trequest.ShapeConfig = &LaunchInstanceShapeConfigDetails\n\t}\n\n\tlog.Debugf(\"Launching instance with cloud-init: %s\", string(createCloudInitScript(sshUser)))\n\n\tcreateResp, err := c.computeClient.LaunchInstance(context.Background(), request)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// wait until lifecycle status is Running\n\tpollUntilRunning := func(r common.OCIOperationResponse) bool {\n\t\tif converted, ok := r.Response.(core.GetInstanceResponse); ok {\n\t\t\treturn converted.LifecycleState != core.InstanceLifecycleStateRunning\n\t\t}\n\t\treturn true\n\t}\n\n\t// create get instance request with a retry policy which takes a function\n\t// to determine shouldRetry or not\n\tpollingGetRequest := core.GetInstanceRequest{\n\t\tInstanceId: createResp.Instance.Id,\n\t\tRequestMetadata: helpers.GetRequestMetadataWithCustomizedRetryPolicy(pollUntilRunning),\n\t}\n\n\tinstance, pollError := c.computeClient.GetInstance(context.Background(), pollingGetRequest)\n\tif pollError != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn *instance.Id, nil\n}", "func SpawnInstance(user *twitter.User, twitterClient *twitter.Client, appConfig *AppConfig, tweetRefID *int64) error {\n\tvar count int\n\tif err := CountActiveSession(&count); err != nil {\n\t\treturn err\n\t}\n\n\tif count > appConfig.Scw.Limit {\n\t\treturn errors.New(\"Server limit reached\")\n\t}\n\n\ts, _ := scw.NewScalewayAPI(appConfig.Scw.AccessKey, appConfig.Scw.SecretKey, \"SCW-Twt\", appConfig.Scw.Region)\n\tpassword := NewPassword(6)\n\tserver := scw.ScalewayServerDefinition{\n\t\tName: user.ScreenName,\n\t\tImage: &appConfig.Scw.Image,\n\t\tOrganization: appConfig.Scw.AccessKey,\n\t\tCommercialType: appConfig.Scw.InstanceType,\n\t\tTags: []string{password},\n\t}\n\n\tid, err := s.PostServer(server)\n\n\tsession := &Session{\n\t\tUserID: user.ID,\n\t\tScreenName: user.ScreenName,\n\t\tServerID: id,\n\t\tState: \"starting\",\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := CreateSession(session); err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"twitter ID\": user.ID,\n\t\t\"server ID\": id,\n\t}).Info(\"Server created\")\n\tTweet(\n\t\ttwitterClient,\n\t\tfmt.Sprintf(\"@%s %s\", user.ScreenName, appConfig.Messages.StartingInProgress),\n\t\ttweetRefID,\n\t)\n\n\tif err := scw.StartServer(s, id, true); err != nil {\n\t\treturn err\n\n\t}\n\tlog.WithFields(logrus.Fields{\n\t\t\"twitter ID\": user.ID,\n\t\t\"server ID\": id,\n\t}).Info(\"Server started\")\n\n\tserver_info, _ := s.GetServer(id)\n\n\tnow := time.Now()\n\tsession.SessionEndAt = now.Add(time.Duration(appConfig.Scw.SessionTime * 60000000000))\n\tsession.State = \"running\"\n\n\tif err := UpdateSession(session); err != nil {\n\t\treturn err\n\t}\n\n\tTweet(\n\t\ttwitterClient,\n\t\tfmt.Sprintf(\"@%s %s\", user.ScreenName, appConfig.Messages.ServerReady),\n\t\ttweetRefID,\n\t)\n\n\tDM(\n\t\ttwitterClient,\n\t\tuser.ID,\n\t\tuser.ScreenName,\n\t\tfmt.Sprintf(\"%s %s ubuntu@%s\", appConfig.Messages.DmServerReady, password, server_info.PublicAddress.IP),\n\t)\n\treturn nil\n}", "func (s *API) WaitForInstance(req *WaitForInstanceRequest) (*Instance, error) {\n\tterminalStatus := map[InstanceStatus]struct{}{\n\t\tInstanceStatusReady: {},\n\t\tInstanceStatusDiskFull: {},\n\t\tInstanceStatusError: {},\n\t}\n\n\tinstance, err := async.WaitSync(&async.WaitSyncConfig{\n\t\tGet: func() (interface{}, bool, error) {\n\t\t\tres, err := s.GetInstance(&GetInstanceRequest{\n\t\t\t\tInstanceID: req.InstanceID,\n\t\t\t\tRegion: req.Region,\n\t\t\t})\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, false, err\n\t\t\t}\n\t\t\t_, isTerminal := terminalStatus[res.Status]\n\n\t\t\treturn res, isTerminal, nil\n\t\t},\n\t\tTimeout: req.Timeout,\n\t\tIntervalStrategy: async.LinearIntervalStrategy(5 * time.Second),\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"waiting for instance failed\")\n\t}\n\treturn instance.(*Instance), nil\n}", "func waitUntilRDSInstanceCreated(rdsClientSess *rds.RDS, restoreParams map[string]string) error {\n\trdsClusterName := restoreParams[\"restoreRDS\"]\n\trdsInstanceName := rdsClusterName + \"-0\" // TODO: this should be handled better\n\n\tinput := &rds.DescribeDBInstancesInput{\n\t\tDBInstanceIdentifier: aws.String(rdsInstanceName),\n\t}\n\n\tstart := time.Now()\n\tmaxWaitAttempts := 120\n\n\tfmt.Printf(\"Wait until RDS instance [%v] in cluster [%v] is fully created ...\\n\", rdsInstanceName, rdsClusterName)\n\n\tfor waitAttempt := 0; waitAttempt < maxWaitAttempts; waitAttempt++ {\n\t\telapsedTime := time.Since(start)\n\t\tif waitAttempt > 0 {\n\t\t\tformattedTime := strings.Split(fmt.Sprintf(\"%6v\", elapsedTime), \".\")\n\t\t\tfmt.Printf(\"Instance creation elapsed time: %vs\\n\", formattedTime[0])\n\t\t}\n\n\t\tresp, err := rdsClientSess.DescribeDBInstances(input)\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Wait RDS instance create err %v\", err)\n\t\t}\n\n\t\tfmt.Printf(\"Instance status: [%s]\\n\", *resp.DBInstances[0].DBInstanceStatus)\n\t\tif *resp.DBInstances[0].DBInstanceStatus== \"available\" {\n\t\t\tfmt.Printf(\"RDS instance [%v] created successfully\\n\", rdsClusterName)\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(30 * time.Second)\n\t}\n\tfmt.Printf(\"RDS instance [%v] created successfully in RDS cluster [%v]\\n\", rdsInstanceName, rdsClusterName)\n\treturn nil\n}", "func HandleInstanceCreate(w rest.ResponseWriter, r *rest.Request) {\n\t// get ima\n\tima := Ima{}\n\terr := r.DecodeJsonPayload(&ima)\n\tif err != nil {\n\t\trest.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif ima.Ima == \"\" {\n\t\trest.Error(w, \"ima required\", 400)\n\t\treturn\n\t}\n\tif ima.Mem == 0 {\n\t\trest.Error(w, \"memory required\", 400)\n\t\treturn\n\t}\n\tif ima.Cpu == 0 {\n\t\trest.Error(w, \"cpu required\", 400)\n\t\treturn\n\t}\n\n\t// start the instance\n\tos := getImaOs(ima.Ima)\n\tswitch os {\n\tcase \"freebsd\":\n\t\t// clone ima to instance\n\t\tinstanceid := allocateInstanceId()\n\t\tcloneIma(ima.Ima, instanceid)\n\n\t\t// create network interface and bring up\n\t\ttap := allocateTap()\n\t\tif tap == \"\" {\n\t\t\treturn\n\t\t}\n\t\tsaveTap(tap, instanceid)\n\t\tbridge := findBridge()\n\t\taddTapToBridge(tap, bridge)\n\t\tbridgeUp(bridge)\n\n\t\tnmdm := \"/dev/nmdm-\" + instanceid + \"-A\"\n\t\tsaveCpu(ima.Cpu, instanceid)\n\t\tsaveMem(ima.Mem, instanceid)\n\t\tgo startFreeBSDVM(nmdm, ima.Cpu, ima.Mem, tap, instanceid)\n\t\tw.WriteJson(&instanceid)\n\tcase \"linux\":\n\t\t// clone ima to instance\n\t\tinstanceid := allocateInstanceId()\n\t\tcloneIma(ima.Ima, instanceid)\n\n\t\t// create network interface and bring up\n\t\ttap := allocateTap()\n\t\tif tap == \"\" {\n\t\t\treturn\n\t\t}\n\t\tsaveTap(tap, instanceid)\n\t\tbridge := findBridge()\n\t\taddTapToBridge(tap, bridge)\n\t\tbridgeUp(bridge)\n\n\t\t//nmdm := \"/dev/nmdm-\" + instanceid + \"-A\"\n\t\tsaveCpu(ima.Cpu, instanceid)\n\t\tsaveMem(ima.Mem, instanceid)\n\t\tbhyveDestroy(instanceid)\n\t\tnmdm := \"/dev/nmdm-\" + instanceid + \"-A\"\n\t\tgo startLinuxVM(nmdm, ima.Cpu, ima.Mem, tap, instanceid)\n\t\tw.WriteJson(&instanceid)\n\tdefault:\n\t\trest.Error(w, \"unknown OS\", 400)\n\t}\n}", "func (p *EC2Provisioner) CreateInstance(opts EC2CreateInstanceOptions) (*cfg.Remote, error) {\n\t// Set requested region\n\tp.WithRegion(opts.Region)\n\n\t// set highlighter\n\tvar highlight = out.NewColorer(out.CY)\n\n\t// Generate authentication\n\tvar keyName = fmt.Sprintf(\"%s_%s_inertia_key_%d\", opts.Name, p.user, time.Now().UnixNano())\n\tout.Fprintf(p.out, highlight.Sf(\":key: Generating key pair '%s'...\\n\", keyName))\n\tkeyResp, err := p.client.CreateKeyPair(&ec2.CreateKeyPairInput{\n\t\tKeyName: aws.String(keyName),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thomeDir, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Save key\n\tvar keyPath = filepath.Join(homeDir, \".ssh\", *keyResp.KeyName)\n\tout.Fprintf(p.out, highlight.Sf(\":inbox_tray: Saving key to '%s'...\\n\", keyPath))\n\tif err = local.SaveKey(*keyResp.KeyMaterial, keyPath); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create security group for network configuration\n\tvar secGroup = fmt.Sprintf(\"%s-%d\", opts.Name, time.Now().UnixNano())\n\tout.Fprintf(p.out, highlight.Sf(\":circus_tent: Creating security group '%s'...\\n\", secGroup))\n\tgroup, err := p.client.CreateSecurityGroup(&ec2.CreateSecurityGroupInput{\n\t\tGroupName: aws.String(secGroup),\n\t\tDescription: aws.String(\n\t\t\tfmt.Sprintf(\"Rules for project %s on %s\", opts.ProjectName, opts.Name),\n\t\t),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set rules for ports\n\tout.Fprintf(p.out, highlight.Sf(\":electric_plug: Exposing ports '%s'...\\n\", secGroup))\n\tif err = p.exposePorts(*group.GroupId, opts.DaemonPort, opts.Ports); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Start up instance\n\tout.Fprintf(p.out, highlight.Sf(\":boat: Requesting instance '%s'...\\n\", secGroup))\n\trunResp, err := p.client.RunInstances(&ec2.RunInstancesInput{\n\t\tImageId: aws.String(opts.ImageID),\n\t\tInstanceType: aws.String(opts.InstanceType),\n\t\tMinCount: aws.Int64(1),\n\t\tMaxCount: aws.Int64(1),\n\n\t\t// Security options\n\t\tKeyName: keyResp.KeyName,\n\t\tSecurityGroupIds: []*string{group.GroupId},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check response validity\n\tif runResp.Instances == nil || len(runResp.Instances) == 0 {\n\t\treturn nil, errors.New(\"Unable to start instances: \" + runResp.String())\n\t}\n\tout.Fprintf(p.out, highlight.Sf(\"A %s instance has been provisioned\", opts.InstanceType))\n\n\t// Loop until intance is running\n\tvar instance ec2.Instance\n\tfor {\n\t\t// Wait briefly between checks\n\t\ttime.Sleep(3 * time.Second)\n\n\t\t// Request instance status\n\t\tout.Fprintf(p.out, \"Checking status of the requested instance...\\n\")\n\t\tresult, err := p.client.DescribeInstances(&ec2.DescribeInstancesInput{\n\t\t\tInstanceIds: []*string{runResp.Instances[0].InstanceId},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Check if reservations are present\n\t\tif result.Reservations == nil || len(result.Reservations) == 0 ||\n\t\t\tlen(result.Reservations[0].Instances) == 0 {\n\t\t\t// A reservation corresponds to a command to start instances\n\t\t\t// If nothing is here... we gotta keep waiting\n\t\t\tfmt.Fprintln(p.out, \"No reservations found yet.\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get status\n\t\ts := result.Reservations[0].Instances[0].State\n\t\tif s == nil {\n\t\t\tfmt.Println(p.out, \"Status unknown.\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Code 16 means instance has started, and we can continue!\n\t\tif s.Code != nil && *s.Code == codeEC2InstanceStarted {\n\t\t\tfmt.Fprintln(p.out, \"Instance is running!\")\n\t\t\tinstance = *result.Reservations[0].Instances[0]\n\t\t\tbreak\n\t\t}\n\n\t\t// Otherwise, keep polling\n\t\tif s.Name != nil {\n\t\t\tfmt.Fprintln(p.out, \"Instance status: \"+*s.Name)\n\t\t} else {\n\t\t\tfmt.Fprintln(p.out, \"Instance status: \"+s.String())\n\t\t}\n\t\tcontinue\n\t}\n\n\t// Check instance validity\n\tif instance.PublicDnsName == nil {\n\t\treturn nil, errors.New(\"Unable to find public IP address for instance: \" + instance.String())\n\t}\n\n\t// Set tags\n\tout.Fprintf(p.out, \"Setting tags on instance...\\n\")\n\tif _, err = p.client.CreateTags(&ec2.CreateTagsInput{\n\t\tResources: []*string{instance.InstanceId},\n\t\tTags: []*ec2.Tag{\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Name\"),\n\t\t\t\tValue: aws.String(opts.Name),\n\t\t\t},\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Purpose\"),\n\t\t\t\tValue: aws.String(\"Inertia Continuous Deployment\"),\n\t\t\t},\n\t\t},\n\t}); err != nil {\n\t\tfmt.Fprintln(p.out, \"Failed to set tags: \"+err.Error())\n\t}\n\n\t// Poll for SSH port to open\n\tfmt.Fprintln(p.out, \"Waiting for ports to open...\")\n\tfor {\n\t\ttime.Sleep(3 * time.Second)\n\t\tfmt.Fprintln(p.out, \"Checking ports...\")\n\t\tif conn, err := net.Dial(\"tcp\", *instance.PublicDnsName+\":22\"); err == nil {\n\t\t\tfmt.Fprintln(p.out, \"Connection established!\")\n\t\t\tconn.Close()\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Generate webhook secret\n\tout.Fprintf(p.out, \"Generating a webhook secret...\\n\")\n\twebhookSecret, err := common.GenerateRandomString()\n\tif err != nil {\n\t\tfmt.Fprintln(p.out, err.Error())\n\t\tfmt.Fprintln(p.out, \"Using default secret 'inertia'\")\n\t\twebhookSecret = \"interia\"\n\t} else {\n\t\tfmt.Fprintf(p.out, \"Generated webhook secret: '%s'\\n\", webhookSecret)\n\t}\n\n\t// Return remote configuration\n\treturn &cfg.Remote{\n\t\tName: opts.Name,\n\t\tIP: *instance.PublicDnsName,\n\t\tSSH: &cfg.SSH{\n\t\t\tUser: p.user,\n\t\t\tIdentityFile: keyPath,\n\t\t\tSSHPort: \"22\",\n\t\t},\n\t\tDaemon: &cfg.Daemon{\n\t\t\tPort: strconv.FormatInt(opts.DaemonPort, 10),\n\t\t\tWebHookSecret: webhookSecret,\n\t\t},\n\t\tProfiles: make(map[string]string),\n\t}, nil\n}", "func DeployInstance(w http.ResponseWriter, r *http.Request) {\n\tProjectID = os.Getenv(\"PROJECT_ID\")\n\tZone = os.Getenv(\"ZONE\")\n\tRegion = os.Getenv(\"REGION\")\n\tInstanceName = os.Getenv(\"INSTANCE_NAME\")\n\tVPCName = os.Getenv(\"VPC_Name\")\n\tSubnetName = os.Getenv(\"Subnet_Name\")\n\tFileshareMountPrimary = os.Getenv(\"FILESHARE_MOUNT_PRIMARY\")\n\tFilestoreIpPrimary = os.Getenv(\"FILESTORE_IP_PRIMARY\")\n\tFileshareNamePrimary = os.Getenv(\"FILESHARE_NAME_PRIMARY\")\n\tFileshareMountSecondary = os.Getenv(\"FILESHARE_MOUNT_SECONDARY\")\n\tFileshareNameSecondary = os.Getenv(\"FILESHARE_NAME_SECONDARY\")\n\tFilestoreIpSecondary = os.Getenv(\"FILESTORE_IP_SECONDARY\")\n\tGcpBucketName = os.Getenv(\"GCP_BUCKET_NAME\")\n\n\n\n\n\n\n\n\tcs, err := InitComputeService()\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Fatal(err)\n\t}\n\n\t//Try retrieve the instance. On error we shall HAPHAZARDLY assume it doesnt exist and try create it.\n\t// There could be other reasons.\n\tinstance, err := GetInstance(cs)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusTemporaryRedirect)\n\t\tw.Write([]byte(err.Error() + \" instance may not exist yet\"))\n\t\tlog.Print(err)\n\n\t\t_, err = CreateInstance(cs)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tw.Write([]byte(\"creating instance \" + InstanceName + \"in zone: \" + Zone))\n\t\t}\n\t}else {\n\t\tswitch instance.Status {\n\t\tcase \"RUNNING\":\n\t\t\tstopInstance(cs, w)\n\t\tcase \"PROVISIONING\":\n\t\t\tstopInstance(cs, w)\n\t\tcase \"STAGING\":\n\t\t\tstopInstance(cs, w)\n\t\tcase \"STOPPED\":\n\t\t\tstartInstance(cs, w)\n\t\tcase \"TERMINATED\":\n\t\t\tstartInstance(cs, w)\n\t\tdefault:\n\t\t\tmsg := \"instance is in intermediate state: \" + instance.Status\n\t\t\tw.WriteHeader(http.StatusAccepted)\n\t\t\tw.Write([]byte(msg))\n\t\t\tlog.Println(msg)\n\t\t}\n\t}\n}", "func (c *EC2) WaitUntilInstanceRunning(input *DescribeInstancesInput) error {\n\treturn c.WaitUntilInstanceRunningWithContext(aws.BackgroundContext(), input)\n}", "func (s *EcsService) WaitForEcsInstance(instanceId string, status Status, timeout int) error {\n\tif timeout <= 0 {\n\t\ttimeout = DefaultTimeout\n\t}\n\tfor {\n\t\tinstance, err := s.DescribeInstance(instanceId)\n\t\tif err != nil && !NotFoundError(err) {\n\t\t\treturn err\n\t\t}\n\t\tif instance.Status == string(status) {\n\t\t\t//Sleep one more time for timing issues\n\t\t\ttime.Sleep(DefaultIntervalMedium * time.Second)\n\t\t\tbreak\n\t\t}\n\t\ttimeout = timeout - DefaultIntervalShort\n\t\tif timeout <= 0 {\n\t\t\treturn GetTimeErrorFromString(GetTimeoutMessage(\"ECS Instance\", string(status)))\n\t\t}\n\t\ttime.Sleep(DefaultIntervalShort * time.Second)\n\n\t}\n\treturn nil\n}", "func (c *Client) Start() error {\n\t// memguard is used to securely keep sensitive information in memory.\n\t// This call makes sure all data will be destroy when the program exits.\n\tdefer memguard.Purge()\n\n\tif c.Conf.Id == \"\" {\n\t\tu, err := uuid.NewV4()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not auto generate app instance id: %v\", err)\n\t\t}\n\t\tc.Conf.Id = u.String()[:8]\n\t}\n\n\tr, err := c.Running()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"id\": c.Conf.Id,\n\t\t}).WithError(err).Error(\"error while checking for another instance using the same id\")\n\n\t\treturn err\n\t}\n\n\tif r {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"id\": c.Conf.Id,\n\t\t}).Error(\"can't start. Another instance is already using the same id\")\n\n\t\treturn fmt.Errorf(\"can't start. Another instance is already using the same id %s\", c.Conf.Id)\n\t}\n\n\tlog.Infof(\"instance identifier is %s\", c.Conf.Id)\n\n\tif c.Conf.Detach {\n\t\tvar err error\n\n\t\tic, err := NewDetachedInstance(c.Conf.Id)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Errorf(\"error while creating directory to store mole instance related files\")\n\t\t\treturn err\n\t\t}\n\n\t\terr = startDaemonProcess(ic)\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"id\": c.Conf.Id,\n\t\t\t}).WithError(err).Error(\"error starting ssh tunnel\")\n\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tgo c.handleSignals()\n\t}\n\n\tif c.Conf.Verbose {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\n\td, err := fsutils.CreateInstanceDir(c.Conf.Id)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"id\": c.Conf.Id,\n\t\t}).WithError(err).Error(\"error creating directory for mole instance\")\n\n\t\treturn err\n\t}\n\n\tif c.Conf.Rpc {\n\t\taddr, err := rpc.Start(c.Conf.RpcAddress)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trd := filepath.Join(d.Dir, \"rpc\")\n\n\t\terr = ioutil.WriteFile(rd, []byte(addr.String()), 0644)\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"id\": c.Conf.Id,\n\t\t\t}).WithError(err).Error(\"error creating file with rpc address\")\n\n\t\t\treturn err\n\t\t}\n\n\t\tc.Conf.RpcAddress = addr.String()\n\n\t\tlog.Infof(\"rpc server address saved on %s\", rd)\n\t}\n\n\tt, err := createTunnel(c.Conf)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"id\": c.Conf.Id,\n\t\t}).WithError(err).Error(\"error creating tunnel\")\n\n\t\treturn err\n\t}\n\n\tc.Tunnel = t\n\n\tif err = c.Tunnel.Start(); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"tunnel\": c.Tunnel.String(),\n\t\t}).WithError(err).Error(\"error while starting tunnel\")\n\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (d *driver) LaunchInstance(\n\tvimInstance *catalogue.VIMInstance,\n\thostname, image, flavour, keyPair string,\n\tnetworks []*catalogue.VNFDConnectionPoint,\n\tsecurityGroups []string,\n\tuserData string) (*catalogue.Server, error) {\n\n\ttag := util.FuncName()\n\n\td.WithFields(log.Fields{\n\t\t\"tag\": tag,\n\t}).Debug(\"received request\")\n\n\treturn d.LaunchInstanceAndWaitWithIPs(vimInstance, hostname, image, flavour, keyPair, networks, securityGroups, userData, nil, nil)\n}", "func (p *OnPrem) CreateInstance(ctx *Context) error {\n\tc := ctx.config\n\n\thypervisor := HypervisorInstance()\n\tif hypervisor == nil {\n\t\tfmt.Println(\"No hypervisor found on $PATH\")\n\t\tfmt.Println(\"Please install OPS using curl https://ops.city/get.sh -sSfL | sh\")\n\t\tos.Exit(1)\n\t}\n\n\tinstancename := c.CloudConfig.ImageName\n\n\tfmt.Printf(\"booting %s ...\\n\", instancename)\n\n\topshome := GetOpsHome()\n\timgpath := path.Join(opshome, \"images\", instancename)\n\n\tc.RunConfig.BaseName = instancename\n\tc.RunConfig.Imagename = imgpath\n\tc.RunConfig.OnPrem = true\n\n\thypervisor.Start(&c.RunConfig)\n\n\treturn nil\n}", "func (d *Driver) Start() error {\n\tcs := d.client()\n\t_, err := cs.AsyncRequest(&egoscale.StartVirtualMachine{\n\t\tID: d.ID,\n\t}, d.async)\n\n\treturn err\n}", "func (c *EC2) WaitUntilInstanceExists(input *DescribeInstancesInput) error {\n\treturn c.WaitUntilInstanceExistsWithContext(aws.BackgroundContext(), input)\n}", "func (g GCPClient) CreateInstance(name, image, zone, machineType string, disks Disks, data *string, nested, vtpm, replace bool) error {\n\tif replace {\n\t\tif err := g.DeleteInstance(name, zone, true); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.Infof(\"Creating instance %s from image %s (type: %s in %s)\", name, image, machineType, zone)\n\n\tenabled := new(string)\n\t*enabled = \"1\"\n\n\tk, err := ssh.NewPublicKey(g.privKey.Public())\n\tif err != nil {\n\t\treturn err\n\t}\n\tsshKey := new(string)\n\t*sshKey = fmt.Sprintf(\"moby:%s moby\", string(ssh.MarshalAuthorizedKey(k)))\n\n\t// check provided image to be compatible with provided options\n\top, err := g.compute.Images.Get(g.projectName, image).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\tuefiCompatible := false\n\tfor _, feature := range op.GuestOsFeatures {\n\t\tif feature != nil && feature.Type == uefiCompatibleFeature {\n\t\t\tuefiCompatible = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif vtpm && !uefiCompatible {\n\t\treturn fmt.Errorf(\"cannot use vTPM without UEFI_COMPATIBLE image\")\n\t}\n\t// we should check for nested\n\tvmxLicense := false\n\tfor _, license := range op.Licenses {\n\t\t// we omit hostname and version when define license\n\t\tif strings.HasSuffix(license, vmxImageLicence) {\n\t\t\tvmxLicense = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif nested && !vmxLicense {\n\t\treturn fmt.Errorf(\"cannot use nested virtualization without enable-vmx image\")\n\t}\n\n\tinstanceDisks := []*compute.AttachedDisk{\n\t\t{\n\t\t\tAutoDelete: true,\n\t\t\tBoot: true,\n\t\t\tInitializeParams: &compute.AttachedDiskInitializeParams{\n\t\t\t\tSourceImage: fmt.Sprintf(\"global/images/%s\", image),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor i, disk := range disks {\n\t\tvar diskName string\n\t\tif disk.Path != \"\" {\n\t\t\tdiskName = disk.Path\n\t\t} else {\n\t\t\tdiskName = fmt.Sprintf(\"%s-disk-%d\", name, i)\n\t\t}\n\t\tvar diskSizeGb int64\n\t\tif disk.Size == 0 {\n\t\t\tdiskSizeGb = int64(1)\n\t\t} else {\n\t\t\tdiskSizeGb = int64(convertMBtoGB(disk.Size))\n\t\t}\n\t\tdiskObj := &compute.Disk{Name: diskName, SizeGb: diskSizeGb}\n\t\tif vtpm {\n\t\t\tdiskObj.GuestOsFeatures = []*compute.GuestOsFeature{\n\t\t\t\t{Type: uefiCompatibleFeature},\n\t\t\t}\n\t\t}\n\t\tdiskOp, err := g.compute.Disks.Insert(g.projectName, zone, diskObj).Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := g.pollZoneOperationStatus(diskOp.Name, zone); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tinstanceDisks = append(instanceDisks, &compute.AttachedDisk{\n\t\t\tAutoDelete: true,\n\t\t\tBoot: false,\n\t\t\tSource: fmt.Sprintf(\"zones/%s/disks/%s\", zone, diskName),\n\t\t})\n\t}\n\n\tinstanceObj := &compute.Instance{\n\t\tMachineType: fmt.Sprintf(\"zones/%s/machineTypes/%s\", zone, machineType),\n\t\tName: name,\n\t\tDisks: instanceDisks,\n\t\tNetworkInterfaces: []*compute.NetworkInterface{\n\t\t\t{\n\t\t\t\tNetwork: \"global/networks/default\",\n\t\t\t\tAccessConfigs: []*compute.AccessConfig{\n\t\t\t\t\t{\n\t\t\t\t\t\tType: \"ONE_TO_ONE_NAT\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tMetadata: &compute.Metadata{\n\t\t\tItems: []*compute.MetadataItems{\n\t\t\t\t{\n\t\t\t\t\tKey: \"serial-port-enable\",\n\t\t\t\t\tValue: enabled,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tKey: \"ssh-keys\",\n\t\t\t\t\tValue: sshKey,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tKey: \"user-data\",\n\t\t\t\t\tValue: data,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tif nested {\n\t\tinstanceObj.MinCpuPlatform = \"Intel Haswell\"\n\t}\n\tif vtpm {\n\t\tinstanceObj.ShieldedInstanceConfig = &compute.ShieldedInstanceConfig{EnableVtpm: true}\n\t}\n\n\t// Don't wait for operation to complete!\n\t// A headstart is needed as by the time we've polled for this event to be\n\t// completed, the instance may have already terminated\n\t_, err = g.compute.Instances.Insert(g.projectName, zone, instanceObj).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Infof(\"Instance created\")\n\treturn nil\n}", "func NewInstance(ac *aws.Clients, asg *autoscaling.Group, asgInst *autoscaling.Instance, launchConfigName *string, force bool, startTime time.Time, preTerminateCmd *string) (*Instance, error) {\n\tvar ec2Inst *ec2.Instance\n\terr := retry(apiRetryCount, apiRetrySleep, func() (err error) {\n\t\tec2Inst, err = ac.ASGInstToEC2Inst(asgInst)\n\t\treturn\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error converting ASG Inst to EC2 inst for %s\", *asgInst.InstanceId)\n\t}\n\n\tinst := Instance{\n\t\tEC2Instance: ec2Inst,\n\t\tASGInstance: asgInst,\n\t\tAutoscalingGroup: asg,\n\t\tIsOld: isInstanceOld(asgInst, ec2Inst, launchConfigName, force, startTime),\n\t\tIsHealthy: isInstanceHealthy(asgInst, ec2Inst),\n\t\tPreTerminateCmd: preTerminateCmd,\n\t}\n\n\treturn &inst, nil\n}", "func TestListInstances(t *testing.T) {\n\tinstances := []*aws.Instance{\n\t\t{\n\t\t\tHostname: \"testHostname1\",\n\t\t\tIPAddress: \"10.10.10.1\",\n\t\t\tID: \"i-xxxxxxxxxxxxxxxx1\",\n\t\t\tPrivateDNSName: \"test1.local\",\n\t\t\tName: \"testNode1\",\n\t\t\tOSName: \"Amazon Linux\",\n\t\t\tOSType: \"Linux\",\n\t\t\tOSVersion: \"2\",\n\t\t},\n\t\t{\n\t\t\tHostname: \"testHostname2\",\n\t\t\tIPAddress: \"10.10.10.2\",\n\t\t\tID: \"i-xxxxxxxxxxxxxxxx2\",\n\t\t\tPrivateDNSName: \"test2.local\",\n\t\t\tName: \"testNode2\",\n\t\t\tOSName: \"Ubuntu\",\n\t\t\tOSType: \"Linux\",\n\t\t\tOSVersion: \"18.04\",\n\t\t},\n\t}\n\tinteractive := false\n\tformat := FormatText\n\tinput := StartInput{\n\t\tOutputFormat: &format,\n\t\tInteractive: &interactive,\n\t}\n\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\tm := NewMockCloudInstances(ctrl) // skipcq: SCC-compile\n\n\tm.EXPECT().ListInstances().Return(instances, nil)\n\n\tassert.NoError(t, input.listInstances(m))\n\t// TODO test integractive part\n}", "func (i *instance) Go(ctx context.Context) {\n\tconst maxTries = 5\n\ttype stateT int\n\tconst (\n\t\t// Perform capacity check for EC2 spot.\n\t\tstateCapacity stateT = iota\n\t\t// Launch the instance via EC2.\n\t\tstateLaunch\n\t\t// Tag the instance\n\t\tstateTag\n\t\t// Wait for the instance to enter running state.\n\t\tstateWait\n\t\t// Describe the instance via EC2.\n\t\tstateDescribe\n\t\t// Wait for offers to appear--i.e., the Reflowlet is live.\n\t\tstateOffers\n\t\tstateDone\n\t)\n\tvar (\n\t\tstate stateT\n\t\tid string\n\t\tdns string\n\t\tn int\n\t\td = 5 * time.Second\n\t)\n\t// TODO(marius): propagate context to the underlying AWS calls\n\tfor state < stateDone && ctx.Err() == nil {\n\t\tswitch state {\n\t\tcase stateCapacity:\n\t\t\tif !i.Spot {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// 20 instances should be a good margin for spot.\n\t\t\tvar ok bool\n\t\t\tok, i.err = i.ec2HasCapacity(ctx, 20)\n\t\t\tif i.err == nil && !ok {\n\t\t\t\ti.err = errors.E(errors.Unavailable, errors.New(\"ec2 capacity is likely exhausted\"))\n\t\t\t}\n\t\tcase stateLaunch:\n\t\t\tid, i.err = i.launch(ctx)\n\t\t\tif i.err != nil {\n\t\t\t\ti.Log.Errorf(\"instance launch error: %v\", i.err)\n\t\t\t} else {\n\t\t\t\tspot := \"\"\n\t\t\t\tif i.Spot {\n\t\t\t\t\tspot = \"spot \"\n\t\t\t\t}\n\t\t\t\ti.Log.Printf(\"launched %sinstance %v: %s: %s %d %s\",\n\t\t\t\t\tspot,\n\t\t\t\t\tid, i.Config.Type,\n\t\t\t\t\tdata.Size(i.Config.Resources.Memory),\n\t\t\t\t\ti.Config.Resources.CPU,\n\t\t\t\t\tdata.Size(i.Config.Resources.Disk))\n\t\t\t}\n\n\t\tcase stateTag:\n\t\t\tinput := &ec2.CreateTagsInput{\n\t\t\t\tResources: []*string{aws.String(id)},\n\t\t\t\tTags: []*ec2.Tag{{Key: aws.String(\"Name\"), Value: aws.String(i.Tag)}},\n\t\t\t}\n\t\t\tfor k, v := range i.Labels {\n\t\t\t\tinput.Tags = append(input.Tags, &ec2.Tag{Key: aws.String(k), Value: aws.String(v)})\n\t\t\t}\n\t\t\t_, i.err = i.EC2.CreateTags(input)\n\t\tcase stateWait:\n\t\t\ti.err = i.EC2.WaitUntilInstanceRunning(&ec2.DescribeInstancesInput{\n\t\t\t\tInstanceIds: []*string{aws.String(id)},\n\t\t\t})\n\t\tcase stateDescribe:\n\t\t\tvar resp *ec2.DescribeInstancesOutput\n\t\t\tresp, i.err = i.EC2.DescribeInstances(&ec2.DescribeInstancesInput{\n\t\t\t\tInstanceIds: []*string{aws.String(id)},\n\t\t\t})\n\t\t\tif len(resp.Reservations) != 1 || len(resp.Reservations[0].Instances) != 1 {\n\t\t\t\ti.err = errors.Errorf(\"ec2.describeinstances %v: invalid output\", id)\n\t\t\t}\n\t\t\tif i.err == nil {\n\t\t\t\ti.ec2inst = resp.Reservations[0].Instances[0]\n\t\t\t\tif i.ec2inst.PublicDnsName == nil || *i.ec2inst.PublicDnsName == \"\" {\n\t\t\t\t\ti.err = errors.Errorf(\"ec2.describeinstances %v: no public DNS name\", id)\n\t\t\t\t} else {\n\t\t\t\t\tdns = *i.ec2inst.PublicDnsName\n\t\t\t\t}\n\t\t\t}\n\t\tcase stateOffers:\n\t\t\tvar pool pool.Pool\n\t\t\tpool, i.err = client.New(fmt.Sprintf(\"https://%s:9000/v1/\", dns), i.HTTPClient, nil /*log.New(os.Stderr, \"client: \", 0)*/)\n\t\t\tif i.err != nil {\n\t\t\t\ti.err = errors.E(errors.Fatal, i.err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tctx, cancel := context.WithTimeout(ctx, 10*time.Second)\n\t\t\t_, i.err = pool.Offers(ctx)\n\t\t\tif i.err != nil && strings.HasSuffix(i.err.Error(), \"connection refused\") {\n\t\t\t\ti.err = errors.E(errors.Temporary, i.err)\n\t\t\t}\n\t\t\tcancel()\n\t\tdefault:\n\t\t\tpanic(\"unknown state\")\n\t\t}\n\t\tif i.err == nil {\n\t\t\tn = 0\n\t\t\td = 5 * time.Second\n\t\t\tstate++\n\t\t\tcontinue\n\t\t}\n\t\tif n == maxTries {\n\t\t\tbreak\n\t\t}\n\t\tif awserr, ok := i.err.(awserr.Error); ok {\n\t\t\tswitch awserr.Code() {\n\t\t\t// According to EC2 API docs, these codes indicate\n\t\t\t// capacity issues.\n\t\t\t//\n\t\t\t// http://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html\n\t\t\t//\n\t\t\t// TODO(marius): add a separate package for interpreting AWS errors.\n\t\t\tcase \"InsufficientCapacity\", \"InsufficientInstanceCapacity\", \"InsufficientHostCapacity\", \"InsufficientReservedInstanceCapacity\", \"InstanceLimitExceeded\":\n\t\t\t\ti.err = errors.E(errors.Unavailable, awserr)\n\t\t\t}\n\t\t}\n\t\tswitch {\n\t\tcase i.err == nil:\n\t\tcase errors.Match(errors.Fatal, i.err):\n\t\t\treturn\n\t\tcase errors.Match(errors.Unavailable, i.err):\n\t\t\t// Return these immediately because our caller may be able to handle\n\t\t\t// them by selecting a different instance type.\n\t\t\treturn\n\t\tcase !errors.Recover(i.err).Timeout() && !errors.Recover(i.err).Temporary():\n\t\t\ti.Log.Errorf(\"instance error: %v\", i.err)\n\t\t}\n\t\ttime.Sleep(d)\n\t\tn++\n\t\td *= time.Duration(2)\n\t}\n\tif i.err != nil {\n\t\treturn\n\t}\n\ti.err = ctx.Err()\n}", "func NewInstance(ssmInstance *ssm.InstanceInformation, ec2Instance *ec2.Instance) *Instance {\n\ti := &Instance{\n\t\tInstanceID: aws.StringValue(ssmInstance.InstanceId),\n\t\tName: aws.StringValue(ssmInstance.ComputerName),\n\t\tPlatformName: aws.StringValue(ssmInstance.PlatformName),\n\t\tPlatformVersion: aws.StringValue(ssmInstance.PlatformVersion),\n\t\tIPAddress: aws.StringValue(ssmInstance.IPAddress),\n\t\tPingStatus: aws.StringValue(ssmInstance.PingStatus),\n\t\tLastPingDateTime: aws.TimeValue(ssmInstance.LastPingDateTime),\n\t}\n\n\tif ec2Instance != nil {\n\t\tfor _, tag := range ec2Instance.Tags {\n\t\t\tif aws.StringValue(tag.Key) == \"Name\" {\n\t\t\t\ti.Name = aws.StringValue(tag.Value)\n\t\t\t}\n\t\t}\n\t\ti.State = aws.StringValue(ec2Instance.State.Name)\n\t\ti.ImageID = aws.StringValue(ec2Instance.ImageId)\n\t}\n\n\treturn i\n}", "func (cracker *Firecracker) Start() error {\n\treturn cracker.action(\"InstanceStart\", \"\")\n}", "func (i *Instance) SpawnInstance() (instance *Instance, err error) {\n\tvar res uintptr\n\tvar newUnknown *ole.IUnknown\n\n\tres, _, _ = syscall.SyscallN(\n\t\ti.vTable.SpawnInstance, // IWbemClassObject::SpawnInstance(\n\t\tuintptr(unsafe.Pointer(i.object)), // IWbemClassObject ptr\n\t\tuintptr(0), // [in] long lFlags,\n\t\tuintptr(unsafe.Pointer(&newUnknown))) // [out] IWbemClassObject **ppNewInstance)\n\tif res != 0 {\n\t\treturn nil, ole.NewError(res)\n\t}\n\n\treturn newInstance(newUnknown, i.service), nil\n}", "func (s *AutoscalerSuite) TestInstanceLaunching(c *check.C) {\n\tclusterName := \"bob\"\n\tinstance := &gaws.Instance{\n\t\tID: \"instance-1\",\n\t}\n\tqueue := newMockQueue(\"queue-1\")\n\tec := newMockEC2(&ec2.Instance{\n\t\tInstanceId: aws.String(\"instance-1\"),\n\t})\n\ta, err := New(Config{\n\t\tClusterName: clusterName,\n\t\tNewLocalInstance: func() (*gaws.Instance, error) {\n\t\t\treturn instance, nil\n\t\t},\n\t\tQueue: queue,\n\t\tCloud: ec,\n\t})\n\tc.Assert(err, check.IsNil)\n\tc.Assert(a, check.NotNil)\n\n\tctx, cancel := context.WithCancel(context.TODO())\n\tdefer cancel()\n\top := newMockOperator(ops.Site{\n\t\tAccountID: \"1\",\n\t\tDomain: \"example.com\",\n\t\tClusterState: storage.ClusterState{},\n\t})\n\tgo a.ProcessEvents(ctx, queue.url, op)\n\n\t// send launched event\n\tinstanceID := \"instance-1\"\n\tmsg := &message{\n\t\treceipt: \"message-1\",\n\t\tbody: mustMarshalHook(HookEvent{\n\t\t\tInstanceID: instanceID,\n\t\t\tType: InstanceLaunching,\n\t\t}),\n\t}\n\tselect {\n\tcase <-time.After(time.Second):\n\t\tc.Fatalf(\"timeout\")\n\tcase queue.messagesC <- msg:\n\t}\n\n\t// expect the turn off request to arrive\n\tselect {\n\tcase input := <-ec.modifyC:\n\t\tc.Assert(aws.StringValue(input.InstanceId), check.DeepEquals, instanceID)\n\t\tc.Assert(input.SourceDestCheck.Value, check.DeepEquals, aws.Bool(false))\n\tcase <-time.After(time.Second):\n\t\tc.Fatalf(\"timeout\")\n\t}\n\n\t// expect the message to be scheduled for deletion\n\tselect {\n\tcase m := <-queue.deletedC:\n\t\tc.Assert(aws.StringValue(m.ReceiptHandle), check.DeepEquals, msg.receipt)\n\tcase <-time.After(time.Second):\n\t\tc.Fatalf(\"timeout\")\n\t}\n}", "func (c *EC2) WaitUntilInstanceStopped(input *DescribeInstancesInput) error {\n\treturn c.WaitUntilInstanceStoppedWithContext(aws.BackgroundContext(), input)\n}", "func testInstance() Instance {\n\treturn Instance{\n\t\tCreated: true,\n\t\tImageID: \"ami-7172b611\",\n\t\tInstanceID: \"i-1234567890abcdef0\",\n\t\tInstanceType: \"t2.nano\",\n\t\tSubnetID: \"subnet-1234567890abcdef0\",\n\t\tKeyPairName: \"bastion-test\",\n\t\tSecurityGroupID: \"sg-1234567890abcdef0\",\n\t\tPublicIPAddress: \"8.8.8.8\",\n\t\tPrivateIPAddress: \"10.0.0.1\",\n\t\tSSHUser: \"ec2-user\",\n\t}\n}", "func (oh *OperatingHours) StartInstances(startInstances []*string) error {\n\n\tlog.WithField(\"len\", len(startInstances)).Info(\"startInstances\")\n\n\tif len(startInstances) > 0 {\n\t\t_, err := oh.EC2API.StartInstances(&ec2.StartInstancesInput{InstanceIds: startInstances})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, instanceID := range startInstances {\n\t\t\tlog.WithField(\"instanceID:\", aws.StringValue(instanceID)).Info(\"start\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func createEC2InstanceMonitoredResource(awsIdentityDoc *awsIdentityDocument) *EC2Instance {\n\tawsInstance := EC2Instance{\n\t\tAWSAccount: awsIdentityDoc.accountID,\n\t\tInstanceID: awsIdentityDoc.instanceID,\n\t\tRegion: fmt.Sprintf(\"aws:%s\", awsIdentityDoc.region),\n\t}\n\treturn &awsInstance\n}", "func (c *Client) StartInstances(instanceIds []string) ([]InstanceStateChange, error) {\n\tresponse := InstancesStateChangeResponse{}\n\targs := &StartInstancesArgs{InstanceIds: instanceIds}\n\terr := c.Invoke(\"StartInstances\", args, &response)\n\tif err == nil {\n\t\treturn response.InstancesSet.Item, nil\n\t}\n\treturn nil, err\n}", "func TestGetInstance(t *testing.T) {\n\tctx, cancelFunc := context.WithTimeout(context.Background(), standardTimeout)\n\tdefer cancelFunc()\n\n\tinstances, err := bat.StartRandomInstances(ctx, \"\", 1)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to launch instance: %v\", err)\n\t}\n\n\t_, err = bat.RetrieveInstanceStatus(ctx, \"\", instances[0])\n\tif err != nil {\n\t\tt.Errorf(\"Failed to retrieve instance status: %v\", err)\n\t}\n\n\tscheduled, err := bat.WaitForInstancesLaunch(ctx, \"\", instances, false)\n\tif err != nil {\n\t\tt.Errorf(\"Instance %s did not launch: %v\", instances[0], err)\n\t}\n\n\t_, err = bat.DeleteInstances(ctx, \"\", scheduled)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to delete instance %s: %v\", instances[0], err)\n\t}\n}", "func InitInstance() {\n\tvar err error\n\tvar token string\n\tif Inst().ConfigMap != \"\" {\n\t\tlogrus.Infof(\"Using Config Map: %s \", Inst().ConfigMap)\n\t\ttoken, err = Inst().S.GetTokenFromConfigMap(Inst().ConfigMap)\n\t\texpect(err).NotTo(haveOccurred())\n\t\tlogrus.Infof(\"Token used for initializing: %s \", token)\n\t} else {\n\t\ttoken = \"\"\n\t}\n\n\terr = Inst().S.Init(scheduler.InitOptions{\n\t\tSpecDir: Inst().SpecDir,\n\t\tVolDriverName: Inst().V.String(),\n\t\tNodeDriverName: Inst().N.String(),\n\t\tSecretConfigMapName: Inst().ConfigMap,\n\t\tCustomAppConfig: Inst().CustomAppConfig,\n\t\tStorageProvisioner: Inst().Provisioner,\n\t\tSecretType: Inst().SecretType,\n\t\tVaultAddress: Inst().VaultAddress,\n\t\tVaultToken: Inst().VaultToken,\n\t\tPureVolumes: Inst().PureVolumes,\n\t\tHelmValuesConfigMapName: Inst().HelmValuesConfigMap,\n\t})\n\texpect(err).NotTo(haveOccurred())\n\n\terr = Inst().N.Init(node.InitOptions{\n\t\tSpecDir: Inst().SpecDir,\n\t})\n\texpect(err).NotTo(haveOccurred())\n\n\terr = Inst().V.Init(Inst().S.String(), Inst().N.String(), token, Inst().Provisioner, Inst().CsiGenericDriverConfigMap)\n\texpect(err).NotTo(haveOccurred())\n\n\tif Inst().Backup != nil {\n\t\terr = Inst().Backup.Init(Inst().S.String(), Inst().N.String(), Inst().V.String(), token)\n\t\texpect(err).NotTo(haveOccurred())\n\t}\n\tif testRailHostname != \"\" && testRailUsername != \"\" && testRailPassword != \"\" {\n\t\terr = testrailuttils.Init(testRailHostname, testRailUsername, testRailPassword)\n\t\tif err == nil {\n\t\t\tif testrailuttils.MilestoneName == \"\" || testrailuttils.RunName == \"\" || testrailuttils.JobRunID == \"\" {\n\t\t\t\tprocessError(fmt.Errorf(\"not all details provided to update testrail\"))\n\t\t\t}\n\t\t\ttestrailuttils.CreateMilestone()\n\t\t}\n\t} else {\n\t\tlogrus.Debugf(\"Not all information to connect to testrail is provided, skipping updates to testrail\")\n\t}\n\n\tif jiraUserName != \"\" && jiraToken != \"\" {\n\t\tlogrus.Info(\"Initializing JIRA connection\")\n\t\tjirautils.Init(jiraUserName, jiraToken)\n\n\t} else {\n\t\tlogrus.Debugf(\"Not all information to connect to JIRA is provided.\")\n\t}\n}", "func (f *fakeEC2BuildletClient) StartNewVM(ctx context.Context, buildEnv *buildenv.Environment, hconf *dashboard.HostConfig, vmName, hostType string, opts *buildlet.VMOpts) (buildlet.Client, error) {\n\t// check required params\n\tif opts == nil || opts.TLS.IsZero() {\n\t\treturn nil, errors.New(\"TLS keypair is not set\")\n\t}\n\tif buildEnv == nil {\n\t\treturn nil, errors.New(\"invalid build enviornment\")\n\t}\n\tif hconf == nil {\n\t\treturn nil, errors.New(\"invalid host configuration\")\n\t}\n\tif vmName == \"\" || hostType == \"\" {\n\t\treturn nil, fmt.Errorf(\"invalid vmName: %q and hostType: %q\", vmName, hostType)\n\t}\n\tif opts.DeleteIn == 0 {\n\t\t// Note: This implements a short default in the rare case the caller doesn't care.\n\t\topts.DeleteIn = 30 * time.Minute\n\t}\n\tif !f.createVMRequestSuccess {\n\t\treturn nil, fmt.Errorf(\"unable to create instance %s: creation disabled\", vmName)\n\t}\n\tcondRun := func(fn func()) {\n\t\tif fn != nil {\n\t\t\tfn()\n\t\t}\n\t}\n\tcondRun(opts.OnInstanceRequested)\n\tif !f.VMCreated {\n\t\treturn nil, errors.New(\"error waiting for instance to exist: vm existence disabled\")\n\t}\n\n\tcondRun(opts.OnInstanceCreated)\n\n\tif !f.buildletCreated {\n\t\treturn nil, errors.New(\"error waiting for buildlet: buildlet creation disabled\")\n\t}\n\n\tif opts.OnGotEC2InstanceInfo != nil {\n\t\topts.OnGotEC2InstanceInfo(&cloud.Instance{\n\t\t\tCPUCount: 4,\n\t\t\tCreatedAt: time.Time{},\n\t\t\tDescription: \"sample vm\",\n\t\t\tID: \"id-\" + instanceName(\"random\", 4),\n\t\t\tIPAddressExternal: \"127.0.0.1\",\n\t\t\tIPAddressInternal: \"127.0.0.1\",\n\t\t\tImageID: \"image-x\",\n\t\t\tName: vmName,\n\t\t\tSSHKeyID: \"key-15\",\n\t\t\tSecurityGroups: nil,\n\t\t\tState: \"running\",\n\t\t\tTags: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tType: \"yy.large\",\n\t\t\tZone: \"zone-a\",\n\t\t})\n\t}\n\treturn &buildlet.FakeClient{}, nil\n}", "func TerminateInstance() {\n\tlog.Println(\"Starting to run terminate instance process\")\n\t// Get instance id and region from metadata\n\tinstanceId, instanceRegion := getInstanceID()\n\tlog.Printf(\"Working on %v in %v region\", instanceId, instanceRegion)\n\n\t// Init aws session\n\tawsSession,_ := initSession(instanceRegion)\n\tlog.Println(\"Initialized aws session\")\n\n\t// Init Aws auto scaling session\n\tinitAutoScalingAwsSession(awsSession)\n\tlog.Println(\"Initialized auto scaling session\")\n\n\t// Get auto scaling group name\n\tinstanceAutoScaleGroupName := getAutoScalingName(instanceId)\n\tlog.Printf(\"Instance %v auto scaling group name is: %v\", instanceId, instanceAutoScaleGroupName)\n\n\t// Set instance scale in policy to false\n\tsuccess := setScaleInProtectionToInstance(instanceAutoScaleGroupName, instanceId)\n\n\t// Terminate ec2 instance after setting scale in policy to false\n\tif success{\n\t\tterminateInstance(instanceId)\n\t}\n}", "func setupSpinmint(prNumber int, prRef string, repo *Repository, upgrade bool) (*ec2.Instance, error) {\n\tLogInfo(\"Setting up spinmint for PR: \" + strconv.Itoa(prNumber))\n\n\tsvc := ec2.New(session.New(), Config.GetAwsConfig())\n\n\tvar setupScript string\n\tif upgrade {\n\t\tsetupScript = repo.InstanceSetupUpgradeScript\n\t} else {\n\t\tsetupScript = repo.InstanceSetupScript\n\t}\n\n\tdata, err := ioutil.ReadFile(path.Join(\"config\", setupScript))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsdata := string(data)\n\tsdata = strings.Replace(sdata, \"BUILD_NUMBER\", strconv.Itoa(prNumber), -1)\n\tsdata = strings.Replace(sdata, \"BRANCH_NAME\", prRef, -1)\n\tbsdata := []byte(sdata)\n\tsdata = base64.StdEncoding.EncodeToString(bsdata)\n\n\tvar one int64 = 1\n\tparams := &ec2.RunInstancesInput{\n\t\tImageId: &Config.AWSImageId,\n\t\tMaxCount: &one,\n\t\tMinCount: &one,\n\t\tInstanceType: &Config.AWSInstanceType,\n\t\tUserData: &sdata,\n\t\tSecurityGroupIds: []*string{&Config.AWSSecurityGroup},\n\t}\n\n\tresp, err := svc.RunInstances(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Add tags to the created instance\n\ttime.Sleep(time.Second * 10)\n\t_, errtag := svc.CreateTags(&ec2.CreateTagsInput{\n\t\tResources: []*string{resp.Instances[0].InstanceId},\n\t\tTags: []*ec2.Tag{\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Name\"),\n\t\t\t\tValue: aws.String(\"Spinmint-\" + prRef),\n\t\t\t},\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Created\"),\n\t\t\t\tValue: aws.String(time.Now().Format(\"2006-01-02/15:04:05\")),\n\t\t\t},\n\t\t},\n\t})\n\tif errtag != nil {\n\t\tLogError(\"Could not create tags for instance: \" + *resp.Instances[0].InstanceId + \" Error: \" + errtag.Error())\n\t}\n\n\treturn resp.Instances[0], nil\n}", "func (c *ClientManager) WaitInstanceUntilReady(id int, until time.Time) error {\n\tfor {\n\t\tvirtualGuest, found, err := c.GetInstance(id, \"id, lastOperatingSystemReload[id,modifyDate], activeTransaction[id,transactionStatus.name], provisionDate, powerState.keyName\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !found {\n\t\t\treturn bosherr.WrapErrorf(err, \"SoftLayer virtual guest '%d' does not exist\", id)\n\t\t}\n\n\t\tlastReload := virtualGuest.LastOperatingSystemReload\n\t\tactiveTxn := virtualGuest.ActiveTransaction\n\t\tprovisionDate := virtualGuest.ProvisionDate\n\n\t\t// if lastReload != nil && lastReload.ModifyDate != nil {\n\t\t// \tfmt.Println(\"lastReload: \", (*lastReload.ModifyDate).Format(time.RFC3339))\n\t\t// }\n\t\t// if activeTxn != nil && activeTxn.TransactionStatus != nil && activeTxn.TransactionStatus.Name != nil {\n\t\t// \tfmt.Println(\"activeTxn: \", *activeTxn.TransactionStatus.Name)\n\t\t// }\n\t\t// if provisionDate != nil {\n\t\t// \tfmt.Println(\"provisionDate: \", (*provisionDate).Format(time.RFC3339))\n\t\t// }\n\n\t\treloading := activeTxn != nil && lastReload != nil && *activeTxn.Id == *lastReload.Id\n\t\tif provisionDate != nil && !reloading {\n\t\t\t// fmt.Println(\"power state:\", *virtualGuest.PowerState.KeyName)\n\t\t\tif *virtualGuest.PowerState.KeyName == \"RUNNING\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tnow := time.Now()\n\t\tif now.After(until) {\n\t\t\treturn bosherr.Errorf(\"Power on virtual guest with id %d Time Out!\", *virtualGuest.Id)\n\t\t}\n\n\t\tmin := math.Min(float64(10.0), float64(until.Sub(now)))\n\t\ttime.Sleep(time.Duration(min) * time.Second)\n\t}\n}", "func (awsI *Ec2Instance) OpenInstance(volumeSize int, zookeeperSize int, mask string, idleTimeout int) error {\n\terr := awsI.runTerraformApply(volumeSize, zookeeperSize, mask, idleTimeout, \"Opening the firewall...\")\n\tif err != nil {\n\t\tawsI.Ctx.ConsoleLog(1, \"Failed to open up the instance.\\n\")\n\t\treturn err\n\t}\n\tawsI.Ctx.ConsoleLog(1, \"Successfully opened up the instance.\\n\")\n\treturn nil\n}", "func getBkupInstances(svc *ec2.EC2, bkupId string, reboot bool) (bkupInstances []*ec2.CreateImageInput, err error) {\n\n\tvar instanceSlice []*string\n\tvar ec2Filter ec2.Filter\n\n\t// if instance id provided use it else search for tags autobkup\n\tif len(bkupId) > 0 {\n\t\tinstanceSlice = append(instanceSlice, &bkupId)\n\t\tec2Filter.Name = nil\n\t\tec2Filter.Values = nil\n\t} else {\n\t\tec2Filter.Name = aws.String(\"tag-key\")\n\t\tec2Filter.Values = []*string{aws.String(\"autobkup\")}\n\t\tinstanceSlice = nil\n\t}\n\n\tec2dii := ec2.DescribeInstancesInput{InstanceIds: instanceSlice, Filters: []*ec2.Filter{&ec2Filter}}\n\n\tresp, err := svc.DescribeInstances(&ec2dii)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// for any instance found extract tag name and instanceid\n\tfor reservation := range resp.Reservations {\n\t\tfor instance := range resp.Reservations[reservation].Instances {\n\t\t\t// Create a new theInstance variable for each run through the loop\n\t\t\ttheInstance := ec2.CreateImageInput{}\n\n\t\t\tfor tag := range resp.Reservations[reservation].Instances[instance].Tags {\n\t\t\t\tif *resp.Reservations[reservation].Instances[instance].Tags[tag].Key == \"Name\" {\n\t\t\t\t\t// name of the created AMI must be unique so add the Unix Epoch\n\t\t\t\t\ttheInstance.Name = aws.String(\n\t\t\t\t\t\t*resp.Reservations[reservation].Instances[instance].Tags[tag].Value +\n\t\t\t\t\t\t\t\"-\" +\n\t\t\t\t\t\t\tstrconv.FormatInt(time.Now().Unix(), 10))\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\ttheInstance.Name = aws.String(\n\t\t\t\t\t\t*resp.Reservations[reservation].Instances[instance].InstanceId +\n\t\t\t\t\t\t\t\"-\" +\n\t\t\t\t\t\t\tstrconv.FormatInt(time.Now().Unix(), 10))\n\t\t\t\t}\n\t\t\t}\n\t\t\ttheInstance.Description = aws.String(\"Auto backup of instance \" + *resp.Reservations[reservation].Instances[instance].InstanceId)\n\t\t\ttheInstance.InstanceId = resp.Reservations[reservation].Instances[instance].InstanceId\n\t\t\t// swap value as the question is NoReboot?\n\t\t\ttheInstance.NoReboot = aws.Bool(!reboot)\n\t\t\t// append details on this instance to the slice\n\t\t\tbkupInstances = append(bkupInstances, &theInstance)\n\t\t}\n\t}\n\treturn bkupInstances, nil\n}", "func main() {\n\tif len(os.Args) != 3 {\n\t\texitErrorf(\"AMI ID and Instance Type are required\"+\n\t\t\t\"\\nUsage: %s image_id instance_type\", os.Args[0])\n\t}\n\n\n\t//Initialize the session that the SDK uses to load credentials from the shared credentials file ~/.aws/credentials\n\tsess, err := session.NewSession(&aws.Config{Region: aws.String(\"eu-west-1\")}, )\n\tsvc := ec2.New(sess)\n\tif err != nil {\n\t\texitErrorf(\"Error creating session, %v\", err)\n\t}\n\n}", "func NewEc2Instance(ctx sdutils.AppContext, dd *awsDeploymentDescription) (*Ec2Instance, error) {\n\tvar err error\n\tcustomData := \"\"\n\tif dd.customPropFile != \"\" {\n\t\tdata, err := ioutil.ReadFile(dd.customPropFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid custom properties file: %s\", err)\n\t\t}\n\t\tcustomData = string(data)\n\t}\n\n\tcustomLog4J := \"\"\n\tif dd.customLog4J != \"\" {\n\t\tlog4JData, err := ioutil.ReadFile(dd.customLog4J)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid custom properties file: %s\", err)\n\t\t}\n\t\tcustomLog4J = base64.StdEncoding.EncodeToString(log4JData)\n\t}\n\n\tvar envBuffer bytes.Buffer\n\tfor _, env := range dd.environment {\n\t\tenvBuffer.WriteString(fmt.Sprintf(\"export %s\\n\", env))\n\t}\n\t// The custom script cannot be null in terraform so make a temp one\n\tscriptData := []byte(\"#!/bin/bash\\nexit 0\\n\")\n\tif dd.CustomScript != \"\" {\n\t\tscriptData, err = ioutil.ReadFile(dd.CustomScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to read the script %s: %s\", dd.CustomScript, err.Error())\n\t\t}\n\t}\n\tbase64CustomScriptData := base64.StdEncoding.EncodeToString(scriptData)\n\tbase64CustomScriptPath := path.Join(dd.deployDir, \"custom-stardogscript.base64\")\n\terr = ioutil.WriteFile(base64CustomScriptPath, []byte(base64CustomScriptData), 0644)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to create the base 64 encoded custom script\")\n\t}\n\n\tscriptZkData := []byte(\"#!/bin/bash\\nexit 0\\n\")\n\tif dd.CustomZkScript != \"\" {\n\t\tscriptZkData, err = ioutil.ReadFile(dd.CustomZkScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to read the script %s: %s\", dd.CustomZkScript, err.Error())\n\t\t}\n\t}\n\tbase64CustomZkScriptData := base64.StdEncoding.EncodeToString(scriptZkData)\n\tbase64CustomZkScriptPath := path.Join(dd.deployDir, \"custom-zk-stardogscript.base64\")\n\terr = ioutil.WriteFile(base64CustomZkScriptPath, []byte(base64CustomZkScriptData), 0644)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to create the base 64 encoded custom zk script\")\n\t}\n\n\tinstance := Ec2Instance{\n\t\tDeploymentName: dd.Name,\n\t\tRegion: dd.Region,\n\t\tKeyName: dd.AwsKeyName,\n\t\tVersion: dd.Version,\n\t\tZkInstanceType: dd.ZkInstanceType,\n\t\tSdInstanceType: dd.SdInstanceType,\n\t\tAmiID: dd.AmiID,\n\t\tPrivateKey: dd.PrivateKeyPath,\n\t\tDeployDir: dd.deployDir,\n\t\tCustomScript: base64CustomScriptPath,\n\t\tCustomZkScript: base64CustomZkScriptPath,\n\t\tCtx: ctx,\n\t\tCustomPropsData: customData,\n\t\tCustomLog4JData: customLog4J,\n\t\tEnvironment: envBuffer.String(),\n\t}\n\tif dd.disableSecurity {\n\t\tinstance.StartOpts = \"--disable-security\"\n\t}\n\treturn &instance, nil\n}", "func (c *Client) CreateInstance(name, zone, machineType, ipxeURL string) error {\n\treq := &packngo.DeviceCreateRequest{\n\t\tHostname: name,\n\t\tPlan: machineType,\n\t\tProjectID: c.projectID,\n\t\tFacility: []string{zone},\n\t\tIPXEScriptURL: ipxeURL,\n\t\tOS: \"custom_ipxe\",\n\t\tDescription: \"eden test vm\",\n\t\tBillingCycle: \"hourly\",\n\t}\n\t_, _, err := c.client.Devices.Create(req)\n\treturn err\n}", "func (s *API) CreateInstance(req *CreateInstanceRequest, opts ...scw.RequestOption) (*Instance, error) {\n\tvar err error\n\n\tdefaultProjectID, exist := s.client.GetDefaultProjectID()\n\tif exist && req.OrganizationID == nil && req.ProjectID == nil {\n\t\treq.ProjectID = &defaultProjectID\n\t}\n\n\tdefaultOrganizationID, exist := s.client.GetDefaultOrganizationID()\n\tif exist && req.OrganizationID == nil && req.ProjectID == nil {\n\t\treq.OrganizationID = &defaultOrganizationID\n\t}\n\n\tif req.Region == \"\" {\n\t\tdefaultRegion, _ := s.client.GetDefaultRegion()\n\t\treq.Region = defaultRegion\n\t}\n\n\tif req.Name == \"\" {\n\t\treq.Name = namegenerator.GetRandomName(\"ins\")\n\t}\n\n\tif fmt.Sprint(req.Region) == \"\" {\n\t\treturn nil, errors.New(\"field Region cannot be empty in request\")\n\t}\n\n\tscwReq := &scw.ScalewayRequest{\n\t\tMethod: \"POST\",\n\t\tPath: \"/rdb/v1/regions/\" + fmt.Sprint(req.Region) + \"/instances\",\n\t\tHeaders: http.Header{},\n\t}\n\n\terr = scwReq.SetBody(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resp Instance\n\n\terr = s.client.Do(scwReq, &resp, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (p *ProxMox) StopInstance(ctx *lepton.Context, instanceID string) error {\n\n\treq, err := http.NewRequest(\"POST\", p.apiURL+\"/api2/json/nodes/\"+p.nodeNAME+\"/qemu/\"+instanceID+\"/status/stop\", nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\treq.Header.Add(\"Authorization\", \"PVEAPIToken=\"+p.tokenID+\"=\"+p.secret)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\t_, err = io.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CreateInstance(computeService *compute.Service) (*compute.Operation, error) {\n\tstartupMetadata := fmt.Sprintf(\"#! /bin/bash\\n \\n echo FILESHARE_MOUNT_PRIMARY=\\\"%s\\\" >> /root/.bashrc \\n echo FILESTORE_IP_PRIMARY=\\\"%s\\\" >> /root/.bashrc \\n echo FILESHARE_NAME_PRIMARY=\\\"%s\\\" >> /root/.bashrc \\n echo FILESHARE_MOUNT_SECONDARY=\\\"%s\\\" >> /root/.bashrc \\n echo FILESHARE_NAME_SECONDARY=\\\"%s\\\" >> /root/.bashrc \\n echo FILESTORE_IP_SECONDARY=\\\"%s\\\" >> /root/.bashrc \\n echo GCP_BUCKET_NAME=\\\"%s\\\" >> /root/.bashrc \\n source /root/.bashrc \\n wget -O /root/google-filestore-backup.sh https://raw.githubusercontent.com/sreesanpd/google-filestore-backup-cloud-function/master/resources/google-filestore-backup.sh \\n chmod +x /root/google-filestore-backup.sh \\n /bin/bash /root/google-filestore-backup.sh \\necho \\\"I am STARTING some work at $(date)\\\" | sudo tee -a $HOME/work.txt\", FileshareMountPrimary, FilestoreIpPrimary, FileshareNamePrimary, FileshareMountSecondary, FileshareNameSecondary, FilestoreIpSecondary, GcpBucketName)\n\tshutdownMetadata := fmt.Sprintf(\"#! /bin/bash\\n\\necho \\\"I am FINISHING some work on %s at $(date)\\\" | sudo tee -a $(HOME)/work.txt\", InstanceName)\n\n\tinstance := &compute.Instance{\n\t\tName: InstanceName,\n\t\tMachineType: fmt.Sprintf(\"zones/%s/machineTypes/f1-micro\", Zone),\n\t\tNetworkInterfaces: []*compute.NetworkInterface{\n\t\t\t{\n\t\t\t\tName: VPCName,\n\t\t\t\tSubnetwork: fmt.Sprintf(\"projects/%s/regions/%s/subnetworks/%s\", ProjectID, Region, SubnetName),\n\t\t\t\tAccessConfigs: []*compute.AccessConfig{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"External NAT\",\n\t\t\t\t\t\tType: \"ONE_TO_ONE_NAT\",\n\t\t\t\t\t\tNetworkTier: \"PREMIUM\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tScheduling: &compute.Scheduling{\n\t\t\tPreemptible: true,\n\t\t},\n\t\tDisks: []*compute.AttachedDisk{\n\t\t\t{\n\t\t\t\tBoot: true, // The first disk must be a boot disk.\n\t\t\t\tAutoDelete: true, //Optional\n\t\t\t\tMode: \"READ_WRITE\", //Mode should be READ_WRITE or READ_ONLY\n\t\t\t\tInterface: \"SCSI\", //SCSI or NVME - NVME only for SSDs\n\t\t\t\tInitializeParams: &compute.AttachedDiskInitializeParams{\n\t\t\t\t\tDiskName: \"worker-instance-boot-disk\",\n\t\t\t\t\tSourceImage: \"projects/debian-cloud/global/images/family/debian-9\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tMetadata: &compute.Metadata{\n\t\t\tItems: []*compute.MetadataItems{\n\t\t\t\t{\n\t\t\t\t\tKey: \"startup-script\",\n\t\t\t\t\tValue: &startupMetadata,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tKey: \"shutdown-script\",\n\t\t\t\t\tValue: &shutdownMetadata,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tServiceAccounts: []*compute.ServiceAccount{\n\t\t\t{\n\t\t\t\tEmail: \"filestorebackups123-gcs-sa@learn-gcp-173102.iam.gserviceaccount.com\",\n\t\t\t\tScopes: []string{\"https://www.googleapis.com/auth/cloud-platform\"},\n\t\t\t\t\n\t\t\t},\n\t\t\t},\n\n\t\t\n\t}\n\treturn computeService.Instances.Insert(ProjectID, Zone, instance).Do()\n}", "func NewInstance(ctx *pulumi.Context,\n\tname string, args *InstanceArgs, opts ...pulumi.ResourceOption) (*Instance, error) {\n\tif args == nil || args.AvailabilityZone == nil {\n\t\treturn nil, errors.New(\"missing required argument 'AvailabilityZone'\")\n\t}\n\tif args == nil || args.BlueprintId == nil {\n\t\treturn nil, errors.New(\"missing required argument 'BlueprintId'\")\n\t}\n\tif args == nil || args.BundleId == nil {\n\t\treturn nil, errors.New(\"missing required argument 'BundleId'\")\n\t}\n\tif args == nil {\n\t\targs = &InstanceArgs{}\n\t}\n\tvar resource Instance\n\terr := ctx.RegisterResource(\"aws:lightsail/instance:Instance\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func startHandler(r *http.Request) (interface{}, HTTPError) {\n\t// Spin up a container\n\tinfo, err := startContainer(image)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn StartResponse{\n\t\tEndpoint: info.IP + \":\" + servicePort,\n\t\tContainerID: info.ID,\n\t}, nil\n}", "func WaitForASGInstancesAndNodesReady(ctx context.Context, f *framework.Framework, describeASGsInput *autoscaling.DescribeAutoScalingGroupsInput) error {\n\tvar asgInstanceIDs []*string\n\n\tBy(\"wait until ASG instances are ready\")\n\terr := f.Cloud.AutoScaling().WaitUntilAutoScalingGroupInService(aws.BackgroundContext(), describeASGsInput)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get instance IDs\n\tasgInstances, err := f.Cloud.AutoScaling().DescribeInServiceAutoScalingGroupInstancesAsList(aws.BackgroundContext(), describeASGsInput)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tBy(\"wait nodes ready\")\n\tfor i, asgInstance := range asgInstances {\n\t\tlog.Debugf(\"Instance %d/%d (id: %s) is in service\", i+1, len(asgInstances), *(asgInstance.InstanceId))\n\t\tasgInstanceIDs = append(asgInstanceIDs, asgInstance.InstanceId)\n\t}\n\tdescribeInstancesInput := &ec2.DescribeInstancesInput{\n\t\tInstanceIds: asgInstanceIDs,\n\t}\n\tinstancesList, err := f.Cloud.EC2().DescribeInstancesAsList(aws.BackgroundContext(), describeInstancesInput)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tdefault:\n\t\t\t\tlog.Debug(aerr)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Debug(err)\n\t\t}\n\t\treturn err\n\t}\n\n\t// Wait until nodes exist and are ready\n\tfor i, instance := range instancesList {\n\t\tnodeName := instance.PrivateDnsName\n\t\tlog.Debugf(\"Wait until node %d/%d (%s) exists\", i+1, len(instancesList), *nodeName)\n\t\tnode := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: *nodeName}}\n\t\tnode, err = f.ResourceManager.WaitNodeExists(ctx, node)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Debugf(\"Wait until node %d/%d (%s) ready\", i+1, len(instancesList), *nodeName)\n\t\t_, err = f.ResourceManager.WaitNodeReady(ctx, node)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (vp *scalewayProvider) CreateInstance(log *logging.Logger, options providers.CreateInstanceOptions, dnsProvider providers.DnsProvider) (providers.ClusterInstance, error) {\n\t// Create server\n\tid, err := vp.createServer(options)\n\tif err != nil {\n\t\treturn providers.ClusterInstance{}, maskAny(err)\n\t}\n\n\t// Wait for the server to be active\n\tserver, err := vp.waitUntilServerActive(id, false)\n\tif err != nil {\n\t\treturn providers.ClusterInstance{}, maskAny(err)\n\t}\n\n\tif options.RoleLoadBalancer {\n\t\tpublicIpv4 := server.PublicAddress.IP\n\t\tpublicIpv6 := \"\"\n\t\tif err := providers.RegisterInstance(vp.Logger, dnsProvider, options, server.Name, options.RoleLoadBalancer, publicIpv4, publicIpv6); err != nil {\n\t\t\treturn providers.ClusterInstance{}, maskAny(err)\n\t\t}\n\t}\n\n\tvp.Logger.Infof(\"Server '%s' is ready\", server.Name)\n\n\treturn vp.clusterInstance(server, false), nil\n}", "func start() error {\n\tcfg, err := config.NewConfig()\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"get config: %w\", err)\n\t}\n\n\trestclientCfg, apiShutdown, err := k8sapiserver.StartAPIServer(cfg.EtcdURL)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"start API server: %w\", err)\n\t}\n\tdefer apiShutdown()\n\n\tclient := clientset.NewForConfigOrDie(restclientCfg)\n\n\tpvshutdown, err := pvcontroller.StartPersistentVolumeController(client)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"start pv controller: %w\", err)\n\t}\n\tdefer pvshutdown()\n\n\tsched := scheduler.NewSchedulerService(client, restclientCfg)\n\n\tsc, err := defaultconfig.DefaultSchedulerConfig()\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"create scheduler config\")\n\t}\n\n\tif err := sched.StartScheduler(sc); err != nil {\n\t\treturn xerrors.Errorf(\"start scheduler: %w\", err)\n\t}\n\tdefer sched.ShutdownScheduler()\n\n\terr = scenario(client)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"start scenario: %w\", err)\n\t}\n\n\treturn nil\n}", "func (s *Server) RunTestInstance() (url string, port int) {\n\t// Critical Section\n\tmx.Lock()\n\t{\n\t\tportToUse++\n\t\ts.Port = portToUse\n\t}\n\tmx.Unlock()\n\n\tgo s.Run()\n\n\t// Give the server 50ms to fire up\n\ttime.Sleep(50 * time.Millisecond)\n\n\treturn fmt.Sprintf(\"http://localhost:%d\", s.Port), s.Port\n}", "func (provider *ResourceProvider) EC2Instance(id string) (*reachAWS.EC2Instance, error) {\n\tinput := &ec2.DescribeInstancesInput{\n\t\tInstanceIds: []*string{\n\t\t\taws.String(id),\n\t\t},\n\t}\n\tresult, err := provider.ec2.DescribeInstances(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstances, err := extractEC2Instances(result.Reservations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(instances) == 0 {\n\t\treturn nil, fmt.Errorf(\"AWS API returned no instances for ID '%s'\", id)\n\t}\n\n\tif len(instances) > 1 {\n\t\treturn nil, fmt.Errorf(\"AWS API returned more than one instance for ID '%s'\", id)\n\t}\n\n\tinstance := instances[0]\n\treturn &instance, nil\n}", "func instanceController() {\n\t// terminate is used for killing an instance of a task.\n\tcommands := map[string]*exec.Cmd{}\n\tvar terminate = func(name string, cmd *exec.Cmd) {\n\t\tif cmd.Process == nil {\n\t\t\treturn\n\t\t}\n\n\t\tpid := cmd.Process.Pid\n\t\terr := cmd.Process.Kill()\n\t\tif err == nil {\n\t\t\tcmd.Process.Wait()\n\t\t}\n\t\tdelete(commands, name)\n\t\tlog.Trace.Printf(`Active instance of \"%s\" (PID %d) has been terminated.`, name, pid)\n\t}\n\n\t// Clean up on termination.\n\tdefer func() {\n\t\tfor name, cmd := range commands {\n\t\t\tterminate(name, cmd)\n\t\t}\n\t\tstopped <- true\n\t}()\n\n\t// Waiting till we are asked to run/restart some tasks or exit\n\t// and following the orders.\n\tfor {\n\t\tswitch m := <-channel; m.action {\n\t\tcase \"start\":\n\t\t\t// Check whether we have already had an instance of the\n\t\t\t// requested task.\n\t\t\tcmd, ok := commands[m.name]\n\t\t\tif ok {\n\t\t\t\t// If so, terminate it first.\n\t\t\t\tterminate(m.name, cmd)\n\t\t\t}\n\n\t\t\t// If this is the first time this command is requested\n\t\t\t// to be run, initialize things.\n\t\t\tn, as := parseTask(m.task)\n\t\t\tlog.Trace.Printf(`Preparing \"%s\"...`, n)\n\t\t\tcmd = exec.Command(n, as...)\n\t\t\tcmd.Stderr = os.Stderr\n\t\t\tcmd.Stdout = os.Stdout\n\n\t\t\t// Starting the task.\n\t\t\tlog.Trace.Printf(\"Starting a new instance of `%s` (%v)...\", n, as)\n\t\t\terr := cmd.Start()\n\t\t\tif err != nil {\n\t\t\t\tlog.Error.Printf(\"Failed to start a command `%s`, error: %v.\", n, err)\n\t\t\t}\n\t\t\tcommands[m.name] = cmd // Register the command so we can terminate it.\n\t\tcase \"exit\":\n\t\t\treturn\n\t\t}\n\t}\n}", "func (v *VMInstances) StartVMInstances(project string, zone string, name string) {\n\t_, err := v.computeService.Instances.Start(project, zone, name).Context(v.Ctx).Do()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"Started instance %s\", name)\n}", "func (h *HealthCheck) createInstance() error {\n\tif h.frameworkError != nil {\n\t\treturn h.frameworkError\n\t}\n\tglog.V(4).Info(\"Creating a ServiceInstance\")\n\tinstance := &v1beta1.ServiceInstance{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: h.instanceName,\n\t\t\tNamespace: h.namespace.Name,\n\t\t},\n\t\tSpec: v1beta1.ServiceInstanceSpec{\n\t\t\tPlanReference: v1beta1.PlanReference{\n\t\t\t\tClusterServiceClassExternalName: h.serviceclassName,\n\t\t\t\tClusterServicePlanExternalName: \"default\",\n\t\t\t},\n\t\t},\n\t}\n\toperationStartTime := time.Now()\n\tvar err error\n\tinstance, err = h.serviceCatalogClientSet.ServicecatalogV1beta1().ServiceInstances(h.namespace.Name).Create(instance)\n\tif err != nil {\n\t\treturn h.setError(\"error creating instance: %v\", err.Error())\n\t}\n\n\tif instance == nil {\n\t\treturn h.setError(\"error creating instance - instance is null\")\n\t}\n\n\tglog.V(4).Info(\"Waiting for ServiceInstance to be ready\")\n\terr = util.WaitForInstanceCondition(h.serviceCatalogClientSet.ServicecatalogV1beta1(),\n\t\th.namespace.Name,\n\t\th.instanceName,\n\t\tv1beta1.ServiceInstanceCondition{\n\t\t\tType: v1beta1.ServiceInstanceConditionReady,\n\t\t\tStatus: v1beta1.ConditionTrue,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn h.setError(\"instance not ready: %v\", err.Error())\n\t}\n\tReportOperationCompleted(\"create_instance\", operationStartTime)\n\n\tglog.V(4).Info(\"Verifing references are resolved\")\n\tsc, err := h.serviceCatalogClientSet.ServicecatalogV1beta1().ServiceInstances(h.namespace.Name).Get(h.instanceName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn h.setError(\"error getting instance: %v\", err.Error())\n\t}\n\n\tif sc.Spec.ClusterServiceClassRef == nil {\n\t\treturn h.setError(\"ClusterServiceClassRef should not be null\")\n\t}\n\tif sc.Spec.ClusterServicePlanRef == nil {\n\t\treturn h.setError(\"ClusterServicePlanRef should not be null\")\n\t}\n\n\tif strings.Compare(sc.Spec.ClusterServiceClassRef.Name, h.serviceclassID) != 0 {\n\t\treturn h.setError(\"ClusterServiceClassRef.Name error: %v != %v\", sc.Spec.ClusterServiceClassRef.Name, h.serviceclassID)\n\t}\n\tif strings.Compare(sc.Spec.ClusterServicePlanRef.Name, h.serviceplanID) != 0 {\n\t\treturn h.setError(\"sc.Spec.ClusterServicePlanRef.Name error: %v != %v\", sc.Spec.ClusterServicePlanRef.Name, h.serviceplanID)\n\t}\n\treturn nil\n}", "func (d *Driver) Start() error {\n\terr := d.connectAPI()\n\tif err != nil {\n\t\treturn err\n\t}\n\ttaskid, err := d.driver.NodesNodeQemuVMIDStatusStartPost(d.Node, d.VMID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = d.driver.WaitForTaskToComplete(d.Node, taskid)\n\n\treturn err\n}", "func (client *ManagedInstancesClient) startCreateRequest(ctx context.Context, resourceGroupName string, managedInstanceName string, options *ManagedInstancesClientBeginStartOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/start\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif managedInstanceName == \"\" {\n\t\treturn nil, errors.New(\"parameter managedInstanceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{managedInstanceName}\", url.PathEscape(managedInstanceName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-08-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (executable *AWSECS) startECSContainer(messageBody *string, messageID *string) (string, error) {\n\te := &ECSMetadata{}\n\tm := &InstanceMetadata{}\n\tm.init()\n\te.init()\n\tvar ecsCluster *string\n\tvar containerInstanceID *string\n\n\tecsCluster = aws.String(e.Cluster)\n\tcontainerInstanceID = aws.String(e.ContainerInstanceArn)\n\n\t// Start ECS task on self\n\tsess, err := session.NewSession(&aws.Config{Region: aws.String(\"us-west-2\")})\n\tif err != nil {\n\t\tfmt.Println(\"failed to create session,\", err)\n\t\treturn \"\", err\n\t}\n\n\tsvc := ecs.New(sess)\n\n\tparams := &ecs.StartTaskInput{\n\t\tContainerInstances: []*string{\n\t\t\tcontainerInstanceID,\n\t\t},\n\t\tTaskDefinition: executable.ecsTaskDefinition,\n\t\tCluster: ecsCluster,\n\t\tOverrides: &ecs.TaskOverride{\n\t\t\tContainerOverrides: []*ecs.ContainerOverride{\n\t\t\t\t{\n\t\t\t\t\tEnvironment: []*ecs.KeyValuePair{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: executable.overridePayloadKey,\n\t\t\t\t\t\t\tValue: aws.String(*messageBody),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tName: executable.overrideContainerName,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tStartedBy: aws.String(\"tasque\"),\n\t}\n\tresp, err := svc.StartTask(params)\n\n\tif err != nil {\n\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t// Message from an error.\n\t\tfmt.Println(\"Error:\", err.Error())\n\t\treturn \"\", err\n\t}\n\n\t// Pretty-print the response data.\n\tfmt.Println(resp)\n\tif len(resp.Failures) > 0 {\n\t\tvar err error\n\t\t// There were errors starting the container\n\t\treason := resp.Failures[0].Reason\n\t\tif strings.Contains(*reason, \"CPU\") {\n\t\t\texecutable.result.SetExit(\"CPU\")\n\t\t\terr = fmt.Errorf(\"%s %s The cpu requested by the task is unavailable on the given container instance. You may need to add container instances to your cluster\", *reason, *resp.Failures[0].Arn)\n\t\t} else if strings.Contains(*reason, \"MEMORY\") {\n\t\t\texecutable.result.SetExit(\"MEMORY\")\n\t\t\terr = fmt.Errorf(\"%s %s The memory requested by the task is unavailable on the given container instance. You may need to add container instances to your cluster\", *reason, *resp.Failures[0].Arn)\n\t\t} else if strings.Contains(*reason, \"RESOURCE\") {\n\t\t\texecutable.result.SetExit(\"RESOURCE\")\n\t\t\terr = fmt.Errorf(\"%s %s The resource or resources requested by the task are unavailable on the given container instance. If the resource is CPU or memory, you may need to add container instances to your cluster\", *reason, *resp.Failures[0].Arn)\n\t\t} else if strings.Contains(*reason, \"AGENT\") {\n\t\t\texecutable.result.SetExit(\"AGENT\")\n\t\t\terr = fmt.Errorf(\"%s %s The container instance that you attempted to launch a task onto has an agent which is currently disconnected. In order to prevent extended wait times for task placement, the request was rejected\", *reason, *resp.Failures[0].Arn)\n\t\t} else if strings.Contains(*reason, \"ATTRIBUTE\") {\n\t\t\texecutable.result.SetExit(\"ATTRIBUTE\")\n\t\t\terr = fmt.Errorf(\"%s %s Your task definition contains a parameter that requires a specific container instance attribute that is not available on your container instances. For more information on which attributes are required for specific task definition parameters and agent configuration variables, see Task Definition Parameters and Amazon ECS Container Agent Configuration\", *reason, *resp.Failures[0].Arn)\n\t\t} else {\n\t\t\t// Unrecognized error\n\t\t\texecutable.result.SetExit(\"UNKNOWN\")\n\t\t\terr = fmt.Errorf(\"Unrecognized error: '%s' %+v\", *reason, resp)\n\t\t}\n\t\treturn \"\", err\n\t}\n\ttaskArn := resp.Tasks[0].Containers[0].TaskArn\n\treturn *taskArn, nil\n}", "func (l *EC2) Start(ctx context.Context) {\n\tgo l.periodicUpdateLabels(ctx)\n}", "func (inst *Instance) Start() error {\n\t// pre-check\n\tgo func() {\n\t\tvar err error\n\t\t// create inst.command first\n\t\tinst.createProcess()\n\t\tif err = inst.start(); err != nil {\n\t\t\treturn\n\t\t}\n\t\t// wait for process finish\n\t\terr = inst.wait()\n\t\tinst.afterWait(err)\n\t\t// close event handle\n\t\tinst.eventHandle.close()\n\t}()\n\treturn nil\n}", "func GetEC2InstanceStatus(experimentsDetails *experimentTypes.ExperimentDetails) (string, error) {\n\n\tvar err error\n\t// Load session from shared config\n\tsess := session.Must(session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t\tConfig: aws.Config{Region: aws.String(experimentsDetails.Region)},\n\t}))\n\n\tif experimentsDetails.Ec2InstanceID == \"\" {\n\t\tlog.Infof(\"[PreChaos]: Instance id is not provided, selecting a random instance from %v region\", experimentsDetails.Region)\n\t\texperimentsDetails.Ec2InstanceID, err = GetRandomInstance(experimentsDetails.Region, sess)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Errorf(\"fail to select a random running instance from %v region, err: %v\", experimentsDetails.Region, err)\n\t\t}\n\t}\n\n\t// Create new EC2 client\n\tec2Svc := ec2.New(sess)\n\n\t// Call to get detailed information on each instance\n\tresult, err := ec2Svc.DescribeInstances(nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, reservationDetails := range result.Reservations {\n\n\t\tfor _, instanceDetails := range reservationDetails.Instances {\n\n\t\t\tif *instanceDetails.InstanceId == experimentsDetails.Ec2InstanceID {\n\t\t\t\treturn *instanceDetails.State.Name, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", errors.Errorf(\"failed to get the status of ec2 instance with instanceID %v\", experimentsDetails.Ec2InstanceID)\n\n}", "func (a *AliyunInstanceAttribute) createBastionHostInstance(sshPublicKey []byte) {\n\tres, err := ExecCmdReturnOutput(\"bash\", \"-c\", \"aliyun ecs DescribeInstances --VpcId=\"+a.VpcID)\n\tcheckError(err)\n\tdecodedQuery := decodeAndQueryFromJSONString(res)\n\n\tinstances, err := decodedQuery.Array(\"Instances\", \"Instance\")\n\tcheckError(err)\n\tbastionServerExists := false\n\tfor _, iter := range instances {\n\t\tinstance := jsonq.NewQuery(iter)\n\t\tinstanceName, err := instance.String(\"InstanceName\")\n\t\tcheckError(err)\n\t\tif instanceName == a.BastionInstanceName {\n\t\t\tbastionServerExists = true\n\t\t\ta.BastionInstanceID, err = instance.String(\"InstanceId\")\n\t\t\tcheckError(err)\n\t\t\tif checkIsThereGardenerUser(a.BastionInstanceID) {\n\t\t\t\ta.BastionSSHUser = \"gardener\"\n\t\t\t} else {\n\t\t\t\t// The bastion is created before `gardener-user` change\n\t\t\t\ta.BastionSSHUser = \"root\"\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !bastionServerExists {\n\t\tuserData := getBastionUserData(sshPublicKey)\n\t\tencodedUserData := base64.StdEncoding.EncodeToString(userData)\n\n\t\targuments := \"aliyun ecs CreateInstance --ImageId=\" + a.ImageID + \" --InstanceType=\" + a.InstanceType + \" --RegionId=\" + a.RegionID + \" --ZoneId=\" + a.ZoneID + \" --VSwitchId=\" + a.VSwitchID + \" --InstanceChargeType=\" + a.InstanceChargeType + \" --InternetChargeType=\" + a.InternetChargeType + \" --InternetMaxBandwidthIn=\" + a.InternetMaxBandwidthIn + \" --InternetMaxBandwidthOut=\" + a.InternetMaxBandwidthOut + \" --IoOptimized=\" + a.IoOptimized + \" --InstanceName=\" + a.BastionInstanceName + \" --SecurityGroupId=\" + a.BastionSecurityGroupID + \" --UserData=\" + encodedUserData\n\t\tres, err = ExecCmdReturnOutput(\"bash\", \"-c\", arguments)\n\t\tcheckError(err)\n\t\tdecodedQuery = decodeAndQueryFromJSONString(res)\n\t\ta.BastionInstanceID, err = decodedQuery.String(\"InstanceId\")\n\t\ta.BastionSSHUser = \"gardener\"\n\t\tcheckError(err)\n\t\tattemptCnt := 0\n\t\tfor attemptCnt < 60 {\n\t\t\tres, err = ExecCmdReturnOutput(\"bash\", \"-c\", \"aliyun ecs DescribeInstances --InstanceIds=\\\"['\"+a.BastionInstanceID+\"']\\\"\")\n\t\t\tcheckError(err)\n\t\t\tdecodedQuery = decodeAndQueryFromJSONString(res)\n\t\t\ttotalCount, err := decodedQuery.Int(\"TotalCount\")\n\t\t\tcheckError(err)\n\t\t\tif totalCount == 1 {\n\t\t\t\ttime.Sleep(time.Second * 30)\n\t\t\t\tfmt.Println(\"Bastion host created.\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfmt.Println(\"Creating bastion host...\")\n\t\t\ttime.Sleep(time.Second * 2)\n\t\t\tattemptCnt++\n\t\t}\n\t\tif attemptCnt == 60 {\n\t\t\tfmt.Println(\"Bastion host creation time out. Please try again.\")\n\t\t\tos.Exit(2)\n\t\t}\n\t}\n}", "func createRDSInstance(rdsClientSess *rds.RDS, restoreParams map[string]string) error {\n\trdsClusterName := restoreParams[\"restoreRDS\"]\n\trdsInstanceName := restoreParams[\"restoreRDS\"] + \"-0\" // TODO: this should be handled better\n\n\tinput := &rds.CreateDBInstanceInput{\n\t\tDBClusterIdentifier: aws.String(rdsClusterName),\n\t\tDBInstanceIdentifier: aws.String(rdsInstanceName),\n\t\tDBInstanceClass: aws.String(restoreParams[\"rdsInstanceType\"]),\n\t\tEngine: aws.String(restoreParams[\"rdsEngine\"]),\n\t\t//AvailabilityZone:\t aws.String(\"us-east-1a\"), // TODO: this doesn't help the terraform issue \n\t}\n\n\tfmt.Printf(\"Creating RDS Instance [%v] in RDS cluster [%v]\\n\", rdsInstanceName, rdsClusterName)\n\n\t_, err := rdsClientSess.CreateDBInstance(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase rds.ErrCodeDBInstanceAlreadyExistsFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBInstanceAlreadyExistsFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeInsufficientDBInstanceCapacityFault:\n\t\t\t\tfmt.Println(rds.ErrCodeInsufficientDBInstanceCapacityFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeDBParameterGroupNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBParameterGroupNotFoundFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeDBSecurityGroupNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBSecurityGroupNotFoundFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeInstanceQuotaExceededFault:\n\t\t\t\tfmt.Println(rds.ErrCodeInstanceQuotaExceededFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeStorageQuotaExceededFault:\n\t\t\t\tfmt.Println(rds.ErrCodeStorageQuotaExceededFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeDBSubnetGroupNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBSubnetGroupNotFoundFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeDBSubnetGroupDoesNotCoverEnoughAZs:\n\t\t\t\tfmt.Println(rds.ErrCodeDBSubnetGroupDoesNotCoverEnoughAZs, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeInvalidDBClusterStateFault:\n\t\t\t\tfmt.Println(rds.ErrCodeInvalidDBClusterStateFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeInvalidSubnet:\n\t\t\t\tfmt.Println(rds.ErrCodeInvalidSubnet, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeInvalidVPCNetworkStateFault:\n\t\t\t\tfmt.Println(rds.ErrCodeInvalidVPCNetworkStateFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeProvisionedIopsNotAvailableInAZFault:\n\t\t\t\tfmt.Println(rds.ErrCodeProvisionedIopsNotAvailableInAZFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeOptionGroupNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeOptionGroupNotFoundFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeDBClusterNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDBClusterNotFoundFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeStorageTypeNotSupportedFault:\n\t\t\t\tfmt.Println(rds.ErrCodeStorageTypeNotSupportedFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeAuthorizationNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeAuthorizationNotFoundFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeKMSKeyNotAccessibleFault:\n\t\t\t\tfmt.Println(rds.ErrCodeKMSKeyNotAccessibleFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeDomainNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeDomainNotFoundFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tcase rds.ErrCodeBackupPolicyNotFoundFault:\n\t\t\t\tfmt.Println(rds.ErrCodeBackupPolicyNotFoundFault, aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t\treturn fmt.Errorf(\"Error creating RDS instance [%v] in RDS cluster [%v]\", rdsInstanceName, rdsClusterName)\n\t\t}\n\t}\n\n\t// TODO: DEBUG - fmt.Println(result)\n\treturn nil\n}", "func (c *EC2) WaitUntilInstanceStatusOk(input *DescribeInstanceStatusInput) error {\n\treturn c.WaitUntilInstanceStatusOkWithContext(aws.BackgroundContext(), input)\n}", "func (broker *Broker) Start() error {\n\tif broker.inbox != nil { // Start has been called at least twice\n\t\tlog.Error(\"Could not start instance\")\n\t\treturn StartInstanceError(errors.New(\"instance already started\"))\n\t}\n\tbroker.inbox = broker.network.RegisterGossipProtocol(ProtoName)\n\tgo broker.dispatcher()\n\n\treturn nil\n}", "func NewInstance(projectID string, metaData map[string]string, secGroup []map[string]interface{}) openstack.InstanceClient {\n\treturn &Instance{\n\t\tprojectID: projectID,\n\t\tmetaData: metaData,\n\t\tsecGroup: secGroup,\n\t\tcreated: time.Now(),\n\t}\n}", "func (instance *Instance) Start() error {\n\t// Init Twitter Streaming API client\n\tclient, err := createTwitterClient(instance.config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinstance.client = client\n\n\treturn nil\n}", "func isServiceInstanceReady(instance *v1beta1.ServiceInstance) bool {\n\treturn isServiceInstanceConditionTrue(instance, v1beta1.ServiceInstanceConditionReady)\n}", "func getBkupInstances(svc *ec2.EC2, tagname string) chan *faBkupInstance {\n\n\tc := make(chan *faBkupInstance)\n\n\tgo func(c chan *faBkupInstance, tn string) {\n\t\tdefer close(c)\n\n\t\tparams := &ec2.DescribeInstancesInput{\n\t\t\tFilters: []*ec2.Filter{\n\t\t\t\t{\n\t\t\t\t\tName: aws.String(\"tag-key\"),\n\t\t\t\t\tValues: []*string{\n\t\t\t\t\t\taws.String(tn),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\tresp, err := svc.DescribeInstances(params)\n\n\t\tif err != nil {\n\t\t\tc <- &faBkupInstance{ii: nil, e: err}\n\t\t\treturn\n\t\t}\n\n\t\t// for any instance found extract tag name and instanceid\n\t\tfor reservation := range resp.Reservations {\n\t\t\tfor _, inst := range resp.Reservations[reservation].Instances {\n\t\t\t\t// Create a new theInstance variable for each run through the loop\n\t\t\t\tnewImage := &ec2.CreateImageInput{}\n\t\t\t\tnewImage.NoReboot = aws.Bool(true)\n\n\t\t\t\tfor _, t := range inst.Tags {\n\t\t\t\t\tswitch *t.Key {\n\t\t\t\t\tcase \"Name\":\n\t\t\t\t\t\tnewImage.Name = aws.String(\n\t\t\t\t\t\t\t*t.Value + \"-\" + strconv.FormatInt(time.Now().Unix(), 10))\n\t\t\t\t\tcase \"bkupReboot\":\n\t\t\t\t\t\t// value in tag is reboot so if tag not present default is no reboot\n\t\t\t\t\t\tif b, err := strconv.ParseBool(*t.Value); err == nil {\n\t\t\t\t\t\t\t// swap value as the question is NoReboot?\n\t\t\t\t\t\t\tnewImage.NoReboot = aws.Bool(!b)\n\t\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif *newImage.Name == \"\" {\n\t\t\t\t\tnewImage.Name = aws.String(\n\t\t\t\t\t\t*inst.InstanceId + \"-\" + strconv.FormatInt(time.Now().Unix(), 10))\n\t\t\t\t}\n\t\t\t\tnewImage.Description = aws.String(\"Auto backup of instance \" + *inst.InstanceId)\n\t\t\t\tnewImage.InstanceId = inst.InstanceId\n\t\t\t\t// append details on this instance to the slice\n\t\t\t\t//fmt.Printf(\"found new: %s\\n\", *newImage.InstanceId)\n\t\t\t\tc <- &faBkupInstance{ii: newImage, e: nil}\n\t\t\t}\n\t\t}\n\t}(c, tagname)\n\treturn c\n}", "func start(c *cli.Context) error {\n\tif !isSystemRunning() {\n\t\treturn nil\n\t}\n\n\t_, _, _, controllers := getIPAddresses()\n\tsendCommandToControllers(controllers, \"StartReaders\", \"\")\n\tsendCommandToControllers(controllers, \"StartWriters\", \"\")\n\t//\tsendCommandToControllers(controllers, \"StartServers\", \"\")\n\treturn nil\n}", "func Start() *bigmachine.B {\n\tsys := bigmachine.Local\n\tswitch *systemFlag {\n\tdefault:\n\t\tlog.Fatalf(\"unrecognized system %s\", *systemFlag)\n\tcase \"ec2\":\n\t\tsys = &ec2system.System{\n\t\t\tInstanceType: *instanceType,\n\t\t\tOnDemand: *ondemand,\n\t\t}\n\tcase \"local\":\n\t}\n\tb := bigmachine.Start(sys)\n\tb.HandleDebug(http.DefaultServeMux)\n\treturn b\n}", "func (vm *VirtualMachine) Start(args *DomainXML, reply *bool) error {\n\t// Passing the false parameter to ensure the start vm task is not added to waitgroup if there is pending signal termination on rpc\n\t_, err := proc.AddTask(false)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"rpc/server:Start() Could not add task for vm start\")\n\t}\n\tdefer proc.TaskDone()\n\tlog.Trace(\"rpc/server:Start() Entering\")\n\tdefer log.Trace(\"rpc/server:Start() Leaving\")\n\n\tif err = validation.ValidateXMLString(args.XML); err != nil {\n\t\tsecLog.Errorf(\"rpc:server() Start: %s, Invalid domain XML format\", message.InvalidInputBadParam)\n\t\treturn nil\n\t}\n\n\t// pass in vm.Watcher to get the instance to the File System Watcher\n\t*reply = wlavm.Start(args.XML, vm.Watcher)\n\treturn nil\n}", "func (i *InstanceServiceHandler) MassStart(ctx context.Context, instanceList []string) error {\n\turi := fmt.Sprintf(\"%s/start\", instancePath)\n\n\treqBody := RequestBody{\"instance_ids\": instanceList}\n\treq, err := i.client.NewRequest(ctx, http.MethodPost, uri, reqBody)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn i.client.DoWithContext(ctx, req, nil)\n}", "func (i *Instance) Start() {\n\tvar err error\n\tvar router = mux.NewRouter()\n\n\t// Establish database connection\n\n\trepo, err := repository.NewMySQLRepository(i.Config.DB)\n\tif err != nil {\n\t\tlogrus.WithError(err).Fatal(\"Could not create mysql repository\")\n\t}\n\n\ti.Service, err = service.NewProvider(i.Config.Service, repo)\n\tif err != nil {\n\t\tlogrus.WithError(err).Fatal(\"Could not create service provider\")\n\t}\n\n\t// Initialize API\n\ti.API, err = api.New(i.Config.API, i.Service, router)\n\tif err != nil {\n\t\tlogrus.WithError(err).Fatal(\"Could not create API instance\")\n\t}\n\n\t// Startup the HTTP Server in a way that we can gracefully shut it down again\n\ti.httpServer = &http.Server{\n\t\tAddr: i.Config.ListenAddress,\n\t\tHandler: router,\n\t}\n\n\terr = i.httpServer.ListenAndServe()\n\tif err != http.ErrServerClosed {\n\t\tlogrus.WithError(err).Error(\"HTTP Server stopped unexpected\")\n\t\ti.Shutdown()\n\t} else {\n\t\tlogrus.WithError(err).Info(\"HTTP Server stopped\")\n\t}\n}", "func createTestEC2InstanceMock() *ec2.EC2 {\n\tconn := ec2.New(session.New(), nil)\n\tconn.Handlers.Clear()\n\n\tconn.Handlers.Send.PushBack(func(r *request.Request) {\n\t\tswitch p := r.Params.(type) {\n\t\tcase *ec2.DescribeImagesInput:\n\t\t\tout, err := testDescribeImages(p)\n\t\t\tif out != nil {\n\t\t\t\t*r.Data.(*ec2.DescribeImagesOutput) = *out\n\t\t\t}\n\t\t\tr.Error = err\n\t\tcase *ec2.DescribeInstancesInput:\n\t\t\tout, err := testDescribeInstances(p)\n\t\t\tif out != nil {\n\t\t\t\t*r.Data.(*ec2.DescribeInstancesOutput) = *out\n\t\t\t}\n\t\t\tr.Error = err\n\t\tcase *ec2.RunInstancesInput:\n\t\t\tout, err := testRunInstances(p)\n\t\t\tif out != nil {\n\t\t\t\t*r.Data.(*ec2.Reservation) = *out\n\t\t\t}\n\t\t\tr.Error = err\n\t\tcase *ec2.TerminateInstancesInput:\n\t\t\tout, err := testTerminateInstances(p)\n\t\t\tif out != nil {\n\t\t\t\t*r.Data.(*ec2.TerminateInstancesOutput) = *out\n\t\t\t}\n\t\t\tr.Error = err\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"Unsupported input type %T\", p))\n\t\t}\n\t})\n\treturn conn\n}", "func Start(numInstances int) error {\n\t// Ideally we should let the socket choose the port, but then\n\t// some things like the logger will not be set correctly.\n\tvar peers []gubernator.PeerInfo\n\tport := 1111\n\tfor i := 0; i < numInstances; i++ {\n\t\tpeers = append(peers, gubernator.PeerInfo{\n\t\t\tHTTPAddress: fmt.Sprintf(\"localhost:%d\", port),\n\t\t\tGRPCAddress: fmt.Sprintf(\"localhost:%d\", port+1),\n\t\t})\n\t\tport += 2\n\t}\n\treturn StartWith(peers)\n}", "func (server *TempestServer) Start() {\n\tif server.running {\n\t\treturn\n\t}\n\n\tserver.running = true\n\n\tserver.serverWaitGroup.Add(1)\n\tgo server.startServer()\n\tserver.serverWaitGroup.Wait()\n}", "func NewInstance(name string, opts ...Option) (Instance, error) {\n\tif name == \"\" {\n\t\treturn nil, ErrNoName\n\t}\n\ti := &instance{\n\t\tname: name,\n\t\tbindAddr: \"127.0.0.1\",\n\t\tbindPort: 8100,\n\t\tshutdownCh: make(chan struct{}),\n\t\tpeers: make(map[string]*Peer),\n\t\tcaches: make(map[string]*cache),\n\t\tlogger: log.New(os.Stdout, \"huton\", log.LstdFlags),\n\t\traftApplicationTimeout: 10 * time.Second,\n\t\traftTransportTimeout: 10 * time.Second,\n\t\traftRetainSnapshotCount: 2,\n\t\tserfEventChannel: make(chan serf.Event, 256),\n\t}\n\tfor _, opt := range opts {\n\t\topt(i)\n\t}\n\ti.logger.Println(\"Initializing RPC server...\")\n\tif err := i.setupRPC(); err != nil {\n\t\ti.Shutdown()\n\t\treturn i, err\n\t}\n\ti.logger.Println(\"Initializing Raft cluster...\")\n\tif err := i.setupRaft(); err != nil {\n\t\ti.Shutdown()\n\t\treturn i, err\n\t}\n\tip := net.ParseIP(i.bindAddr)\n\traftAddr := &net.TCPAddr{\n\t\tIP: ip,\n\t\tPort: i.bindPort + 1,\n\t}\n\trpcAddr := &net.TCPAddr{\n\t\tIP: ip,\n\t\tPort: i.bindPort + 2,\n\t}\n\n\ti.logger.Println(\"Initializing Serf cluster...\")\n\tif err := i.setupSerf(raftAddr, rpcAddr); err != nil {\n\t\ti.Shutdown()\n\t\treturn i, err\n\t}\n\tgo i.handleEvents()\n\treturn i, nil\n}", "func InstanceHandler(w http.ResponseWriter, request *http.Request) {\n\tvars := mux.Vars(request)\n\tlog.Trace(fmt.Sprintf(\"%s /v2/service_instances/:instance_id :: %+v\", request.Method, vars))\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\n\tswitch request.Method {\n\tcase \"PUT\":\n\t\ttype instanceRequest struct {\n\t\t\tServiceId string `json:\"service_id\"`\n\t\t\tPlan string `json:\"plan_id\"`\n\t\t\tOrganizationId string `json:\"organization_guid\"`\n\t\t\tSpaceId string `json:\"space_guid\"`\n\t\t}\n\t\tir := instanceRequest{}\n\t\tbody, err := ioutil.ReadAll(request.Body)\n\t\tif err != nil {\n\t\t\tlog.Error(fmt.Sprintf(\"%s /v2/service_instances/:instance_id %s\", request.Method, err))\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, `{\"status\": %d,\"description\": %s}`, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\t\terr = json.Unmarshal(body, &ir)\n\t\tif err != nil {\n\t\t\tlog.Error(fmt.Sprintf(\"%s /v2/service_instances/:instance_id %s\", request.Method, err))\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, `{\"status\": %d,\"description\": %s}`, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\n\t\tinstance, err := NewInstance(\n\t\t\tvars[\"instance_id\"],\n\t\t\tir.ServiceId,\n\t\t\tir.Plan,\n\t\t\tir.OrganizationId,\n\t\t\tir.SpaceId,\n\t\t)\n\t\tif err != nil {\n\t\t\tlog.Error(fmt.Sprintf(\"%s /v2/service_instances/:instance_id %s\", request.Method, err))\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, `{\"status\": %d,\"description\": %s}`, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\n\t\terr = instance.Provision()\n\t\tif err != nil {\n\t\t\tlog.Error(fmt.Sprintf(\"%s /v2/service_instances/:instance_id %s\", request.Method, err))\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, `{\"status\": %d,\"description\": %s}`, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusOK)\n\t\tfmt.Fprintf(w, `{\"status\": %d,\"description\": \"Instance Provisioned Successfully\"}`, http.StatusOK)\n\t\treturn\n\tcase \"DELETE\":\n\t\tinstance, err := FindInstance(vars[\"instance_id\"])\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, `{\"status\": %d,\"description\": %s}`, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\n\t\terr = instance.Remove()\n\t\tif err != nil {\n\t\t\tlog.Error(fmt.Sprintf(\"%s /v2/service_instances/:instance_id %s\", request.Method, err))\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, `{\"status\": %d,\"description\": %s}`, http.StatusInternalServerError, err)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusOK)\n\t\tfmt.Fprintf(w, `{\"status\": %d,\"description\": \"Successfully Deprovisioned %s\"}`, http.StatusOK, instance.InstanceId)\n\tdefault:\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\tfmt.Fprintf(w, `{\"status\": %d,\"description\": \"Allowed Methods: PUT, DELETE\"}`, http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n}", "func (d *conntrackInstallerInUbuntu) WaitForStart() (ok bool, err error) {\n\tok = true\n\treturn\n}", "func SetupRDSInstance(mgr ctrl.Manager, l logging.Logger) error {\n\tname := managed.ControllerName(v1alpha1.RDSInstanceGroupKind)\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tNamed(name).\n\t\tFor(&v1alpha1.RDSInstance{}).\n\t\tComplete(managed.NewReconciler(mgr,\n\t\t\tresource.ManagedKind(v1alpha1.RDSInstanceGroupVersionKind),\n\t\t\tmanaged.WithExternalConnecter(&connector{\n\t\t\t\treader: &kube2ConnectorReader{kube: mgr.GetClient()},\n\t\t\t\tnewRDSClient: rds.NewClient,\n\t\t\t}),\n\t\t\tmanaged.WithInitializers(managed.NewNameAsExternalName(mgr.GetClient())),\n\t\t\tmanaged.WithLogger(l.WithValues(\"controller\", name)),\n\t\t\tmanaged.WithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name)))))\n}", "func (w *InstanceExistsWaiter) Wait(ctx context.Context, params *DescribeInstancesInput, maxWaitDur time.Duration, optFns ...func(*InstanceExistsWaiterOptions)) error {\n\t_, err := w.WaitForOutput(ctx, params, maxWaitDur, optFns...)\n\treturn err\n}", "func (d *Driver) Start() error {\n\tclient, err := d.getClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn client.StartVirtualMachine(d.vmName())\n}" ]
[ "0.7815959", "0.7357949", "0.727267", "0.6916077", "0.67272824", "0.67272824", "0.6538799", "0.6479852", "0.6445755", "0.64103496", "0.63575953", "0.6284689", "0.6194204", "0.61448747", "0.6061127", "0.6014265", "0.5959917", "0.59404624", "0.5913093", "0.5892486", "0.5862958", "0.5859508", "0.58519626", "0.58454216", "0.5823654", "0.58076525", "0.5757179", "0.5735845", "0.56998944", "0.5646794", "0.56429386", "0.56167024", "0.56053615", "0.555087", "0.552445", "0.5519088", "0.5516242", "0.54863626", "0.54855055", "0.5481179", "0.5477517", "0.5462956", "0.54413223", "0.5412248", "0.53957725", "0.5394775", "0.5381679", "0.5367522", "0.53478456", "0.5340402", "0.53094655", "0.5302666", "0.5283721", "0.5268463", "0.52563304", "0.52559143", "0.52423954", "0.5199534", "0.51966625", "0.51908773", "0.5189306", "0.51890486", "0.5168851", "0.51509994", "0.51504624", "0.51417685", "0.51412696", "0.51399463", "0.51285684", "0.5126173", "0.51074725", "0.51072735", "0.5098433", "0.508554", "0.50801706", "0.5070967", "0.506891", "0.50660497", "0.50553995", "0.5054702", "0.50540364", "0.5034152", "0.50330216", "0.5022238", "0.5020248", "0.50180906", "0.5015447", "0.50043", "0.49969614", "0.49911255", "0.4984403", "0.49760178", "0.49680936", "0.49630955", "0.4959074", "0.4948871", "0.4942169", "0.4928957", "0.49268645", "0.49240938" ]
0.819455
0
getIPAddress retrieves the public IP address from AWS. Returns error if no address found
func (ins *EC2RemoteClient) getIPAddress() error { result, err := ins.ec2Client.DescribeInstances(&ec2.DescribeInstancesInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})}) if err != nil { return fmt.Errorf("Error getting instance details : %s", err) } ins.instanceIP = net.ParseIP(*result.Reservations[0].Instances[0].PublicIpAddress) if ins.instanceIP == nil { return fmt.Errorf("Error parsing IP address") } return err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetPublicIPAddress() (string, error) {\n\tresp, err := http.Get(\"http://checkip.amazonaws.com/\")\n\tif resp != nil {\n\t\tdefer resp.Body.Close()\n\t\tresp.Close = true\n\t}\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), err\n}", "func getIP() (net.IP, error) {\n\tres, err := http.Get(\"http://checkip.amazonaws.com/\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer res.Body.Close()\n\tresData, err := ioutil.ReadAll(res.Body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawIP := strings.Trim(string(resData), \"\\n\")\n\n\treturn net.ParseIP(rawIP), nil\n}", "func (c *Client) GetIPAddress(id, compartmentID string) (string, error) {\n\tvnics, err := c.computeClient.ListVnicAttachments(context.Background(), core.ListVnicAttachmentsRequest{\n\t\tInstanceId: &id,\n\t\tCompartmentId: &compartmentID,\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(vnics.Items) == 0 {\n\t\treturn \"\", errors.New(\"instance does not have any configured VNICs\")\n\t}\n\n\tvnic, err := c.virtualNetworkClient.GetVnic(context.Background(), core.GetVnicRequest{VnicId: vnics.Items[0].VnicId})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif vnic.PublicIp == nil {\n\t\treturn *vnic.PrivateIp, nil\n\t}\n\n\treturn *vnic.PublicIp, nil\n}", "func (e *ec2_t) getIpAddr() {\n\tsvc := ec2.New(session.New(&aws.Config{Region: aws.String(e.Region)}))\n\tparams := &ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t/*\n\t\t\t\t&ec2.Filter{\n\t\t\t\t\tName: aws.String(\"instance-state-name\"),\n\t\t\t\t\tValues: []*string{\n\t\t\t\t\t\taws.String(\"running\"),\n\t\t\t\t\t\taws.String(\"pending\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t*/\n\t\t\t&ec2.Filter{\n\t\t\t\tName: aws.String(\"instance-id\"),\n\t\t\t\tValues: []*string{\n\t\t\t\t\taws.String(e.InstanceId),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tresp, err := svc.DescribeInstances(params)\n\tif err != nil {\n\t\tlog.Println(\"fail to get public and private IP address of ec2 instance. error: \", err)\n\t\treturn\n\t}\n\n\tinstance := resp.Reservations[0].Instances[0]\n\te.PrivateIp = *instance.PrivateIpAddress\n\te.PublicIp = *instance.PublicIpAddress\n\tlog.Println(\"successfully get ec2 instance's IP address. public ip: \", e.PublicIp, \" private ip: \", e.PrivateIp)\n\treturn\n\n}", "func (s *Service) GetPublicIPAddress(resourceGroup string, IPName string) (armada.PublicIPAddress, error) {\n\t//JEB return s.scope.AirshipClients.PublicIPAddresses.Get(s.scope.Context, resourceGroup, IPName, \"\")\n\treturn armada.PublicIPAddress{}, nil\n}", "func (c *Client) GetIPAddress(ctx context.Context, id string) (*InstanceIP, error) {\n\te, err := c.IPAddresses.Endpoint()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\te = fmt.Sprintf(\"%s/%s\", e, id)\n\tr, err := coupleAPIErrors(c.R(ctx).SetResult(&InstanceIP{}).Get(e))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.Result().(*InstanceIP), nil\n}", "func (s Service) GetIPAddress() string {\n\treturn s.container.NetworkSettings.IPAddress\n}", "func GetPublicIP() (*net.IPAddr, error) {\n\n\t// make a request to IPGetURL to get the public ip address\n\tresp, err := http.Get(IPGetURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// process the response\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// convert the response into the ip address\n\treturn net.ResolveIPAddr(\"\", string(body))\n}", "func (irkit *Irkit) GetIPAddress() string {\n\treturn irkit.Address\n}", "func (ip *IPAddress)GetIpAddress() (ipAddress string, err error){\n\tnetInterfaces, err := net.Interfaces()\n\tif err != nil{\n\t\tlog4go.Error(err)\n\t\treturn\n\t}\n\tLoop:\n\tfor i := 0; i < len(netInterfaces); i++{\n\t\tif(netInterfaces[i].Flags & net.FlagUp) != 0{\n\t\t\taddrs, _ := netInterfaces[i].Addrs()\n\t\t\tfor _, address := range addrs{\n\t\t\t\tif ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback(){\n\t\t\t\t\tif ipnet.IP.To4()!=nil{\n\t\t\t\t\t\tipAddress = (ipnet.IP.String())\n\t\t\t\t\t\tip.IpAddress = ipAddress\n\t\t\t\t\t\tip.IpValid = true\n\t\t\t\t\t\tbreak Loop\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func getIP(ec2inst ec2Instance,c *ecs.Container) string{\n\tif len(c.NetworkInterfaces) > 0 {\n\t\treturn ptr.StringValue(c.NetworkInterfaces[0].PrivateIpv4Address)\n\t}\n\treturn ptr.StringValue(ec2inst.PrivateIpAddress)\n}", "func GetPublicIPAddress(client Clients, ctx context.Context,\n\tresourceGroup string, PublicIPname string, expand string) (PublicIPAddress string, err error) {\n\tvmPublicIP := client.VMPublicIP\n\tVMIP, err := vmPublicIP.Get(ctx, resourceGroup, PublicIPname, expand)\n\tif err != nil {\n\t\t\treturn\n\t}\n\tif VMIP.PublicIPAddressPropertiesFormat != nil && VMIP.PublicIPAddressPropertiesFormat.IPAddress != nil {\n\t\t\tPublicIPAddress = *VMIP.PublicIPAddressPropertiesFormat.IPAddress\n\n\t} else {\n\t\t\terr = errors.New(\"Vm has no publicIPAddress\")\n\t}\n\treturn\n\n}", "func publicIP() (net.IP, error) {\n\tresp, err := http.Get(publicEcho)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tout, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn := net.ParseIP(string(out))\n\tif n == nil {\n\t\treturn nil, fmt.Errorf(\"cannot parse ip %s\", string(out))\n\t}\n\n\treturn n, nil\n}", "func GetIPAddress(result *gocni.CNIResult, task containerd.Task) (net.IP, error) {\n\t// Get the IP of the created interface\n\tvar ip net.IP\n\tfor ifName, config := range result.Interfaces {\n\t\tif config.Sandbox == NetNamespace(task) {\n\t\t\tfor _, ipConfig := range config.IPConfigs {\n\t\t\t\tif ifName != \"lo\" && ipConfig.IP.To4() != nil {\n\t\t\t\t\tip = ipConfig.IP\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif ip == nil {\n\t\treturn nil, fmt.Errorf(\"unable to get IP address for: %s\", task.ID())\n\t}\n\treturn ip, nil\n}", "func GetIPAddress(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tplainAddress := vars[\"domainName\"]\n\tif reply, ok := servers[plainAddress]; ok {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tif enc, err := json.Marshal(reply); err == nil {\n\t\t\tw.Write([]byte(enc))\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t} else {\n\t\treply := r.RemoteAddr\n\t\tif enc, err := json.Marshal(reply); err == nil {\n\t\t\tw.Write([]byte(enc))\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t}\n}", "func (i EC2Instance) PublicIP() string {\n\tif i.publicIP == \"\" {\n\t\tlog.Printf(\"ERROR: Attempting to get public IP of %s, which is not know\\n\", i.name)\n\t}\n\treturn i.publicIP\n}", "func GetPublicAddress() (PublicAddress, error) {\n\tvar ip PublicAddress\n\tres, err := http.Get(\"http://ipinfo.io/json\")\n\tif err != nil {\n\t\treturn ip, err\n\t}\n\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn ip, err\n\t}\n\n\terr = json.Unmarshal(body, &ip)\n\tif err != nil {\n\t\treturn ip, nil\n\t}\n\n\treturn ip, nil\n}", "func GetPublicIPOfInstanceE(t *testing.T, projectID string, zone string, instanceID string) (string, error) {\n\tlogger.Logf(t, \"Getting Public IP for Compute Instance %s\", instanceID)\n\n\tctx := context.Background()\n\n\tservice, err := NewComputeServiceE(t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tinstance, err := service.Instances.Get(projectID, zone, instanceID).Context(ctx).Do()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Instances.Get(%s) got error: %v\", instanceID, err)\n\t}\n\n\t// If there are no accessConfigs specified, then this instance will have no external internet access:\n\t// https://cloud.google.com/compute/docs/reference/rest/v1/instances.\n\tif len(instance.NetworkInterfaces[0].AccessConfigs) == 0 {\n\t\treturn \"\", fmt.Errorf(\"Attempted to get public IP of Compute Instance %s, but that Compute Instance does not have a public IP address\", instanceID)\n\t}\n\n\tip := instance.NetworkInterfaces[0].AccessConfigs[0].NatIP\n\n\treturn ip, nil\n}", "func (m *ServicePrincipalRiskDetection) GetIpAddress()(*string) {\n val, err := m.GetBackingStore().Get(\"ipAddress\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (h *Ec2Handler) PublicIP() (*string, error) {\n\tinput := &ec2.DescribeNetworkInterfacesInput{\n\t\tNetworkInterfaceIds: []*string{\n\t\t\taws.String(*h.Eni),\n\t\t},\n\t}\n\n\tresult, err := h.Service.DescribeNetworkInterfaces(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tdefault:\n\t\t\t\tlog.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tlog.Println(err.Error())\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif len(result.NetworkInterfaces) > 0 {\n\t\treturn result.NetworkInterfaces[0].Association.PublicIp, err\n\t}\n\treturn nil, errors.New(\"No ENI found\")\n\t// (TODO)If public IP not found, attach an EIP\n}", "func (client *WANPPPConnection1) GetExternalIPAddress() (NewExternalIPAddress string, err error) {\n\treturn client.GetExternalIPAddressCtx(context.Background())\n}", "func (client *AwsClientWrapper) GetPrivateIP(machine *clusterv1alpha1.Machine) (string, error) {\n\tinstance, err := getRunningInstance(machine, client.client)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif *instance.PrivateIpAddress == \"\" {\n\t\treturn \"\", fmt.Errorf(\"machine instance public DNS name not set\")\n\t}\n\n\treturn *instance.PrivateIpAddress, nil\n}", "func (m *BgpConfiguration) GetIpAddress()(*string) {\n val, err := m.GetBackingStore().Get(\"ipAddress\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (client *WANIPConnection1) GetExternalIPAddress() (NewExternalIPAddress string, err error) {\n\treturn client.GetExternalIPAddressCtx(context.Background())\n}", "func (h *Hub) PublicIPAddress() (result string, err error) {\n\treturn h.client.sendXPathRequest(mySagemcomBoxDeviceInfoPublicIpv4)\n}", "func (d *Driver) GetIP() (string, error) {\n\td.connectAPI()\n\treturn d.driver.GetEth0IPv4(d.Node, d.VMID)\n}", "func (instance *Host) GetPublicIP(_ context.Context) (_ string, ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif valid.IsNil(instance) {\n\t\treturn \"\", fail.InvalidInstanceError()\n\t}\n\n\tthis, err := instance.MetadataCore.properties.UnWrap()\n\tif err != nil {\n\t\treturn \"\", fail.ConvertError(err)\n\t}\n\n\tif val, ok := this[hostproperty.NetworkV2]; !ok {\n\t\treturn \"\", fail.NewError(\"corrupted metadata\")\n\t} else {\n\t\tif val == nil {\n\t\t\treturn \"\", fail.NewError(\"corrupted metadata\")\n\t\t}\n\t}\n\n\taclo, err := this[hostproperty.NetworkV2].UnWrap()\n\tif err != nil {\n\t\treturn \"\", fail.ConvertError(err)\n\t}\n\thnV2, _ := aclo.(*propertiesv2.HostNetworking) // nolint\n\n\tpublicIP := hnV2.PublicIPv4\n\tif publicIP == \"\" {\n\t\tpublicIP = hnV2.PublicIPv6\n\t\tif publicIP == \"\" {\n\t\t\treturn \"\", fail.NotFoundError(\"failed to find Public IP of Host '%s'\", instance.GetName())\n\t\t}\n\t}\n\n\treturn publicIP, nil\n}", "func GetIPAddr() string {\n\tipList := getIPList()\n\n\t// Try to return public IP first\n\tfor _, ip := range ipList {\n\t\tprivate, err := isPrivateIP(ip)\n\t\tif err != nil || private {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn ip\n\t}\n\n\t// Return any IP if no public IP was found\n\tfor _, ip := range ipList {\n\t\treturn ip\n\t}\n\n\treturn \"\"\n}", "func PublicAddr() string {\n\tif devel() {\n\t\treturn defaultIP\n\t}\n\taddr, err := awsPublicIPv4()\n\tif err != nil {\n\t\talt.Warnf(\"env: Could not fetch instance public IPv4 from environment: %v\", err)\n\t\taddr = defaultIP // punt\n\t}\n\treturn addr\n}", "func (a *Azure) GetPublicIP(ctx context.Context, ipName string) (ip network.PublicIPAddress, err error) {\n\tipClient := a.getIPClient()\n\n\tip, err = ipClient.Get(ctx, a.groupName, ipName, \"\")\n\treturn\n}", "func (b *Box) GetPublicIp() string {\n\treturn b.PublicIp\n}", "func (req *request) getInstancePrivateIP(instanceID string) (string, error) {\n\t// check to see if we already have it\n\tutil.Mutex.Lock()\n\tif address, exists := instancePrivateIPs[instanceID]; exists {\n\t\tutil.Mutex.Unlock()\n\t\treturn address, nil\n\t}\n\tutil.Mutex.Unlock()\n\n\tparams := &ec2.DescribeInstancesInput{\n\t\tInstanceIds: []*string{\n\t\t\taws.String(instanceID),\n\t\t},\n\t}\n\tresp, err := util.EC2.DescribeInstances(params)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"ec2.DescribeInstances()\")\n\t}\n\tif len(resp.Reservations) < 1 || len(resp.Reservations[0].Instances) < 1 {\n\t\treturn \"\", errors.New(\"not instances found\")\n\t}\n\t// save for later\n\treq.debug(\"saving instance and ip: \" + instanceID + \" \" + *resp.Reservations[0].Instances[0].PrivateIpAddress)\n\tutil.Mutex.Lock()\n\tinstancePrivateIPs[instanceID] = *resp.Reservations[0].Instances[0].PrivateIpAddress\n\tutil.Mutex.Unlock()\n\treturn *resp.Reservations[0].Instances[0].PrivateIpAddress, nil\n}", "func getIP(url string) string {\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tdefer res.Body.Close()\n\tb, _ := io.ReadAll(res.Body)\n\treturn string(b)\n}", "func (c *Client) GetIP(id string, privateIPOnly bool) (string, error) {\n\tvar (\n\t\tmethod = \"GET\"\n\t\turi = fmt.Sprintf(\"%s/%s\", \"server\", id)\n\t)\n\n\tdata, err := c.newRequest(method, uri, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar s sakura.Response\n\tif err := json.Unmarshal(data, &s); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif privateIPOnly && len(s.Server.Interfaces) > 1 {\n\t\treturn s.Server.Interfaces[1].UserIPAddress, nil\n\t}\n\n\treturn s.Server.Interfaces[0].IPAddress, nil\n}", "func GetIPAddr() (string, error) {\n\tif SunnyDay {\n\t\treturn \"192.168.1.1\", nil\n\t}\n\treturn \"\", fmt.Errorf(\"No Internet\")\n\n}", "func (c *Container) IPAddress() (net.IP, error) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif err := c.syncContainer(); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error updating container %s state\", c.ID())\n\t}\n\n\tif !c.config.CreateNetNS || c.state.NetNS == nil {\n\t\treturn nil, errors.Wrapf(ErrInvalidArg, \"container %s does not have a network namespace\", c.ID())\n\t}\n\n\treturn c.runtime.getContainerIP(c)\n}", "func (b *OGame) GetPublicIP() (string, error) {\n\treturn b.getPublicIP()\n}", "func getExternalIPAddress() string {\n\tconn, err := net.Dial(\"udp\", \"8.8.8.8:80\")\n\tif err != nil {\n\t\tlog.Println(\"[IP] Error while obtaining IP address for this node\")\n\t\treturn \"\"\n\t}\n\tdefer conn.Close()\n\tlocalAddr := conn.LocalAddr().(*net.UDPAddr).String()\n\n\tipv4HostPortSplit := strings.Split(localAddr, \":\")\n\tif len(ipv4HostPortSplit) != 2 {\n\t\tlog.Printf(\"[IP] Error while parsing %s as IPv4 address\", localAddr)\n\t\treturn localAddr\n\t}\n\treturn ipv4HostPortSplit[0]\n}", "func GetEipAddress(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *EipAddressState, opts ...pulumi.ResourceOption) (*EipAddress, error) {\n\tvar resource EipAddress\n\terr := ctx.ReadResource(\"alicloud:ecs/eipAddress:EipAddress\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (instance *Host) GetAccessIP(ctx context.Context) (_ string, ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif valid.IsNil(instance) {\n\t\treturn \"\", fail.InvalidInstanceError()\n\t}\n\n\tpublicIP, _ := instance.GetPublicIP(ctx)\n\n\t// FIXME: find a better way to handle the use case (adjust SG? something else?)\n\t// Workaround for a specific use: safescaled inside a cluster, to force access to host using internal IP\n\tfromInside := os.Getenv(\"SAFESCALED_FROM_INSIDE\")\n\tif publicIP == \"\" || fromInside == \"true\" {\n\t\tprivIP, xerr := instance.GetPrivateIP(ctx)\n\t\tif xerr != nil {\n\t\t\treturn \"\", xerr\n\t\t}\n\n\t\tif privIP == \"\" {\n\t\t\treturn \"\", fail.NotFoundError(\"failed to find Access IP of Host '%s'\", instance.GetName())\n\t\t}\n\t\treturn privIP, nil\n\t} else {\n\t\tif publicIP == \"\" {\n\t\t\treturn \"\", fail.NotFoundError(\"failed to find Access IP of Host '%s'\", instance.GetName())\n\t\t}\n\t\treturn publicIP, nil\n\t}\n}", "func (o InstanceOutput) IpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.IpAddress }).(pulumi.StringOutput)\n}", "func (c *Client) GetInstanceIPAddress(ctx context.Context, linodeID int, ipaddress string) (*InstanceIP, error) {\n\te, err := c.InstanceIPs.endpointWithID(linodeID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\te = fmt.Sprintf(\"%s/%s\", e, ipaddress)\n\tr, err := coupleAPIErrors(c.R(ctx).SetResult(&InstanceIP{}).Get(e))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.Result().(*InstanceIP), nil\n}", "func GetIPAddress(r *http.Request) string {\n\tip := \"\"\n\tfor _, h := range []string{\"X-Forwarded-For\", \"X-Real-Ip\"} {\n\t\taddresses := strings.Split(r.Header.Get(h), \",\")\n\t\t// march from right to left until we get a public address\n\t\t// that will be the address right before our proxy.\n\t\tfor i := len(addresses) - 1; i >= 0; i-- {\n\t\t\tip = strings.TrimSpace(addresses[i])\n\t\t\t// header can contain spaces too, strip those out.\n\t\t\trealIP := net.ParseIP(ip)\n\t\t\tif !realIP.IsGlobalUnicast() || IsPrivateSubnet(realIP) {\n\t\t\t\t// bad address, go to next\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn ip\n\t\t}\n\t}\n\n\tip, _, _ = net.SplitHostPort(r.RemoteAddr)\n\treturn ip\n}", "func GetPublicIPOfInstance(t *testing.T, projectID string, zone string, instanceID string) string {\n\tip, err := GetPublicIPOfInstanceE(t, projectID, zone, instanceID)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn ip\n}", "func GetPublicIP(ctx context.Context, ipName string) (network.PublicIPAddress, error) {\n\tipClient := getIPClient()\n\treturn ipClient.Get(ctx, config.GroupName(), ipName, \"\")\n}", "func (o *CreateLoadBalancerRequest) GetPublicIp() string {\n\tif o == nil || o.PublicIp == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PublicIp\n}", "func (i EC2Instance) IP() string {\n\treturn i.privateIP\n}", "func (c *CloudConfiguration) GetPublicIP(ctx context.Context, ipName string) (network.PublicIPAddress, error) {\n\tipClient, err := c.GetIPClient()\n\tif err != nil {\n\t\treturn network.PublicIPAddress{}, err\n\t}\n\treturn ipClient.Get(ctx, c.GroupName, ipName, \"\")\n}", "func getIPAddress() string {\n\tvar validIP = false\n\tvar ip string\n\tfor validIP == false {\n\t\tfmt.Scanln(&ip)\n\t\tif len(ip) < 6 || !pattern.MatchString(ip) {\n\t\t\tfmt.Print(\"Enter a valid address: \")\n\t\t} else {\n\t\t\tvalidIP = true\n\t\t}\n\t}\n\treturn ip\n}", "func (c *MockAzureCloud) PublicIPAddress() azure.PublicIPAddressesClient {\n\treturn c.PublicIPAddressesClient\n}", "func (c NodeGroup) getPublicIP(i int) string {\n\tfor _, ni := range c.Nodes[i].instance.NetworkInterfaces {\n\t\tfor _, conn := range c.Connections {\n\t\t\tif conn.To == ni.Connection {\n\t\t\t\treturn toHCLStringFormat(fmt.Sprintf(\"aws_network_interface.%s.private_ip\", ni.Name))\n\t\t\t}\n\t\t}\n\t}\n\n\tpanic(errors.New(\"no possible connection possible\"))\n}", "func (instance *Host) GetPrivateIPOnSubnet(ctx context.Context, subnetID string) (_ string, ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tip := \"\"\n\tif valid.IsNil(instance) {\n\t\treturn ip, fail.InvalidInstanceError()\n\t}\n\tif subnetID = strings.TrimSpace(subnetID); subnetID == \"\" {\n\t\treturn ip, fail.InvalidParameterError(\"subnetID\", \"cannot be empty string\")\n\t}\n\n\t// instance.RLock()\n\t// defer instance.RUnlock()\n\n\txerr := instance.Inspect(ctx, func(_ data.Clonable, props *serialize.JSONProperties) fail.Error {\n\t\treturn props.Inspect(hostproperty.NetworkV2, func(clonable data.Clonable) fail.Error {\n\t\t\thostNetworkV2, ok := clonable.(*propertiesv2.HostNetworking)\n\t\t\tif !ok {\n\t\t\t\treturn fail.InconsistentError(\"'*propertiesv2.HostNetworking' expected, '%s' provided\", reflect.TypeOf(clonable).String())\n\t\t\t}\n\t\t\tif ip, ok = hostNetworkV2.IPv4Addresses[subnetID]; !ok {\n\t\t\t\treturn fail.InvalidRequestError(\"Host '%s' does not have an IP address on subnet '%s'\", instance.GetName(), subnetID)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t})\n\treturn ip, xerr\n}", "func (networkClient NetworkClient) IpAddress() net.IP {\n\treturn networkClient.ipAddress\n}", "func getIP(ip_str string) (net.IP, error) {\n\tip := net.ParseIP(ip_str)\n\tif ip != nil {\n\t\treturn ip.To4(), nil\n\t}\n\treturn nil, errors.New(\"Failed to parse ip\")\n}", "func (d *driverMock) GetInstanceIP(ctx context.Context, id string) (string, error) {\n\tif d.GetInstanceIPErr != nil {\n\t\treturn \"\", d.GetInstanceIPErr\n\t}\n\tif d.cfg.UsePrivateIP {\n\t\treturn \"private_ip\", nil\n\t}\n\treturn \"ip\", nil\n}", "func privateIPv4() (net.IP, error) {\n\tas, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, a := range as {\n\t\tipnet, ok := a.(*net.IPNet)\n\t\tif !ok || ipnet.IP.IsLoopback() {\n\t\t\tcontinue\n\t\t}\n\n\t\tip := ipnet.IP.To4()\n\t\tif isPrivateIPv4(ip) {\n\t\t\treturn ip, nil\n\t\t}\n\t}\n\n\t//change: use \"POD_IP\"\n\tip := net.ParseIP(os.Getenv(\"POD_IP\"))\n\tif ip == nil {\n\t\treturn nil, errors.New(\"no private ip address\")\n\t}\n\tif ipV4 := ip.To4(); ipV4 != nil {\n\t\treturn ipV4, nil\n\t}\n\treturn nil, errors.New(\"no pod ipv4 address\")\n}", "func getExternalAddress(t *testing.T) net.IP {\n\tt.Helper()\n\tiface, err := net.InterfaceByName(\"eth0\")\n\tskip.If(t, err != nil, \"Test not running with `make test-integration`. Interface eth0 not found: %s\", err)\n\n\tifaceAddrs, err := iface.Addrs()\n\tassert.NilError(t, err)\n\tassert.Check(t, 0 != len(ifaceAddrs))\n\n\tif len(ifaceAddrs) > 1 {\n\t\t// Prefer IPv4 address if multiple addresses found, as rootlesskit\n\t\t// does not handle IPv6 currently https://github.com/moby/moby/pull/41908#issuecomment-774200001\n\t\tfor _, a := range ifaceAddrs {\n\t\t\tifaceIP, _, err := net.ParseCIDR(a.String())\n\t\t\tassert.NilError(t, err)\n\t\t\tif ifaceIP.To4() != nil {\n\t\t\t\treturn ifaceIP\n\t\t\t}\n\t\t}\n\t}\n\tifaceIP, _, err := net.ParseCIDR(ifaceAddrs[0].String())\n\tassert.NilError(t, err)\n\n\treturn ifaceIP\n}", "func (h *Host) GetPublicIP() string {\n\thostNetworkV1 := propsv1.NewHostNetwork()\n\terr := h.Properties.Get(HostProperty.NetworkV1, hostNetworkV1)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tip := hostNetworkV1.PublicIPv4\n\tif ip == \"\" {\n\t\tip = hostNetworkV1.PublicIPv6\n\t}\n\treturn ip\n}", "func (o *CreateClientGatewayRequest) GetPublicIp() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.PublicIp\n}", "func (m *OutboundMock) GetIPAddress() (r packets.NodeAddress) {\n\tcounter := atomic.AddUint64(&m.GetIPAddressPreCounter, 1)\n\tdefer atomic.AddUint64(&m.GetIPAddressCounter, 1)\n\n\tif len(m.GetIPAddressMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.GetIPAddressMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to OutboundMock.GetIPAddress.\")\n\t\t\treturn\n\t\t}\n\n\t\tresult := m.GetIPAddressMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the OutboundMock.GetIPAddress\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.GetIPAddressMock.mainExpectation != nil {\n\n\t\tresult := m.GetIPAddressMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the OutboundMock.GetIPAddress\")\n\t\t}\n\n\t\tr = result.r\n\n\t\treturn\n\t}\n\n\tif m.GetIPAddressFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to OutboundMock.GetIPAddress.\")\n\t\treturn\n\t}\n\n\treturn m.GetIPAddressFunc()\n}", "func getExternalIP() string {\n\tresp, err := http.Get(\"https://api.ipify.org?format=json\")\n\tif (err != nil) {\n\t\tlog.Fatal(\"Do: \", err)\n\t\treturn \"\"\n\t}\n\tdefer resp.Body.Close()\n\n\tvar record IPFy\n\n\tif err := json.NewDecoder(resp.Body).Decode(&record); err != nil {\n\t\tlog.Fatal(\"Decode \", err)\n\t\treturn \"\"\n\t}\n\treturn record.IP\n\n}", "func (client *SdnClient) GetEveIfIP(eveIfName string) (ip string, err error) {\n\tmac, err := client.GetEveIfMAC(eveIfName)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get MAC address for EVE interface %s: %v\",\n\t\t\teveIfName, err)\n\t}\n\tcommand := exec.Command(\"ssh\", client.sshArgs(\"/bin/get-eve-ip.sh\", mac)...)\n\toutput, err := command.CombinedOutput()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"get-eve-ip.sh failed: %v\", string(output))\n\t}\n\tip = strings.TrimSpace(string(output))\n\treturn ip, nil\n}", "func (o ExternalVpnGatewayInterfaceResponseOutput) IpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ExternalVpnGatewayInterfaceResponse) string { return v.IpAddress }).(pulumi.StringOutput)\n}", "func (test *Test) GetIP(projectName string, ip string) (models.IP, error) {\n\treturn tests.NormalIPs[0], nil\n}", "func (instance *Host) GetPrivateIP(_ context.Context) (_ string, ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif valid.IsNil(instance) {\n\t\treturn \"\", fail.InvalidInstanceError()\n\t}\n\n\tthis, err := instance.MetadataCore.properties.UnWrap()\n\tif err != nil {\n\t\treturn \"\", fail.ConvertError(err)\n\t}\n\n\tif val, ok := this[hostproperty.NetworkV2]; !ok {\n\t\treturn \"\", fail.NewError(\"corrupted metadata\")\n\t} else {\n\t\tif val == nil {\n\t\t\treturn \"\", fail.NewError(\"corrupted metadata\")\n\t\t}\n\t}\n\n\taclo, err := this[hostproperty.NetworkV2].UnWrap()\n\tif err != nil {\n\t\treturn \"\", fail.ConvertError(err)\n\t}\n\thnV2, _ := aclo.(*propertiesv2.HostNetworking) // nolint\n\n\tvar privateIP string\n\tif len(hnV2.IPv4Addresses) > 0 {\n\t\tprivateIP = hnV2.IPv4Addresses[hnV2.DefaultSubnetID]\n\t\tif privateIP == \"\" {\n\t\t\tprivateIP = hnV2.IPv6Addresses[hnV2.DefaultSubnetID]\n\t\t}\n\t}\n\n\tif privateIP == \"\" {\n\t\treturn \"\", fail.NotFoundError(\"failed to find Private IP of Host '%s'\", instance.GetName())\n\t}\n\treturn privateIP, nil\n}", "func (c *Connection) PublicIP() string {\n\tif c.ipAddress == \"\" {\n\t\tc.getPublicIP()\n\t}\n\treturn c.ipAddress\n}", "func (o NetworkEndpointResponseOutput) IpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v NetworkEndpointResponse) string { return v.IpAddress }).(pulumi.StringOutput)\n}", "func evaluateIPAddress(req *http.Request) (*ipAddress, error) {\n\tresult := ipAddress{}\n\tip, _, err := net.SplitHostPort(req.RemoteAddr)\n\tif err != nil {\n\t\treturn &result, fmt.Errorf(\"The user IP: %q is not IP:port\", req.RemoteAddr)\n\t}\n\n\t// If the client is behind a non-anonymous proxy, the IP address is in the X-Forwarded-For header.\n\t// req.Header.Get is case-insensitive.\n\tresult.IPAddressV4 = req.Header.Get(\"X-Forwarded-For\")\n\tif result.IPAddressV4 == \"\" {\n\t\t// If no header can be read, directly extract the address for the request.\n\t\tuserIP := net.ParseIP(ip)\n\t\tif userIP == nil {\n\t\t\treturn &result, fmt.Errorf(\"The user IP: %q is not IP:port\", req.RemoteAddr)\n\t\t}\n\t\tresult.IPAddressV4 = userIP.String()\n\t\tresult.Source = \"Remote address\"\n\t} else {\n\t\tresult.Source = \"X-Forwarded-For\"\n\t}\n\treturn &result, nil\n}", "func (m *EntityDTO_StorageData) GetIpAddress() string {\n\tif m != nil && m.IpAddress != nil {\n\t\treturn *m.IpAddress\n\t}\n\treturn \"\"\n}", "func (m *UserSimulationEventInfo) GetIpAddress()(*string) {\n return m.ipAddress\n}", "func (c *Composition) GetIPAddressForComposeService(composeService string) (ipAddress string, err error) {\n\terrRetFunc := func() error {\n\t\treturn fmt.Errorf(\"error getting IPAddress for compose service '%s': %w\", composeService, err)\n\t}\n\n\tvar apiContainer *docker.APIContainers\n\n\tif apiContainer, err = c.GetAPIContainerForComposeService(composeService); err != nil {\n\t\treturn \"\", errRetFunc()\n\t}\n\n\t// Now get the IPAddress\n\treturn apiContainer.Networks.Networks[\"bridge\"].IPAddress, nil\n}", "func GetExternalIP() (string, error) {\n\tresp, err := http.Get(\"http://myexternalip.com/raw\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tbodyStrings := strings.Split(string(body), \"\\n\")\n\treturn bodyStrings[0], err\n}", "func (c *Container) GetPrivateAddress(t *testing.T) string {\n\tcontainer := c.parentContainer\n\tif container == \"\" {\n\t\tcontainer = c.container\n\t}\n\tresult := icmd.RunCommand(dockerCli.path, \"inspect\", container, \"-f\", \"{{.NetworkSettings.IPAddress}}\").Assert(t, icmd.Success)\n\treturn fmt.Sprintf(\"%s:%d\", strings.TrimSpace(result.Stdout()), c.privatePort)\n}", "func (c *Client) GetPrivateIP(id, compartmentID string) (string, error) {\n\tvnics, err := c.computeClient.ListVnicAttachments(context.Background(), core.ListVnicAttachmentsRequest{\n\t\tInstanceId: &id,\n\t\tCompartmentId: &compartmentID,\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(vnics.Items) == 0 {\n\t\treturn \"\", errors.New(\"instance does not have any configured VNICs\")\n\t}\n\n\tvnic, err := c.virtualNetworkClient.GetVnic(context.Background(), core.GetVnicRequest{VnicId: vnics.Items[0].VnicId})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn *vnic.PrivateIp, nil\n}", "func FindMyPublicIP() (string, error) {\n\turl := \"https://api.ipify.org?format=text\"\n\n\tfmt.Printf(\"Getting IP address from ipify ...\\n\")\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tip, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfmt.Printf(\"My IP is:%s\\n\", ip)\n\treturn string(ip), nil\n}", "func get_ip(hostname string) (host_ip string, err error) {\n\tr, _ := regexp.Compile(\"^\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}$\")\n\tis_ip := r.MatchString(hostname)\n\n\thost_ip = hostname\n\n\tif !is_ip {\n\t\tIPAddr, err := net.ResolveIPAddr(\"ip\", hostname)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.New(\"Error in resolving IP\")\n\t\t}\n\n\t\taddr := net.ParseIP(IPAddr.String())\n\n\t\tif addr == nil {\n\t\t\treturn \"\", errors.New(\"Invalid address\")\n\t\t}\n\n\t\thost_ip = addr.String()\n\t}\n\n\treturn host_ip, nil\n}", "func (o *IamIpAddress) GetAddress() string {\n\tif o == nil || o.Address == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Address\n}", "func (o EipAddressOutput) IpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *EipAddress) pulumi.StringOutput { return v.IpAddress }).(pulumi.StringOutput)\n}", "func GetExternalIP() string {\n\tresp, err := http.Get(\"http://myexternalip.com/raw\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn string(bytes)\n}", "func GetIpAddress(s string) (result []string) {\n\tlist := make([]string, 0)\n\tif len(s) < 4 || len(s) > 12 {\n\t\treturn\n\t}\n\thelper(&result, &list, s, 0)\n\treturn\n}", "func (p *DockerPod) GetIPAddr() string {\n\treturn \"\"\n}", "func getInstancePublicDns(instance ec2.Instance) (string, error) {\n\treturn *instance.PublicDnsName, nil\n}", "func (o LookupServerResultOutput) IpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupServerResult) string { return v.IpAddress }).(pulumi.StringOutput)\n}", "func (o GetBackendAddressPoolBackendAddressOutput) IpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetBackendAddressPoolBackendAddress) string { return v.IpAddress }).(pulumi.StringOutput)\n}", "func (o InstanceOutput) EgressPublicIp() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.EgressPublicIp }).(pulumi.StringOutput)\n}", "func (o VpnGatewayVpnGatewayInterfaceResponseOutput) IpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v VpnGatewayVpnGatewayInterfaceResponse) string { return v.IpAddress }).(pulumi.StringOutput)\n}", "func (o ExternalVpnGatewayInterfaceOutput) IpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ExternalVpnGatewayInterface) *string { return v.IpAddress }).(pulumi.StringPtrOutput)\n}", "func (sqlDb *SqliteDB) GetIp(ipAddr string) (*model.IP, error) {\n\trow := db.QueryRow(\"SELECT * FROM ip WHERE ip_address = ?\", ipAddr)\n\tip := model.IP{}\n\n\terr := row.Scan(&ip.IPAddress, &ip.UUID, &ip.CreatedAt, &ip.UpdatedAt, &ip.ResponseCode)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\treturn &ip, nil\n\n}", "func getIp() (string){\n\tconn, err := net.Dial(\"udp\", \"google.com:80\")\n if err != nil {\n\t fmt.Println(err.Error())\n\t log.Debugf(\"getIp udp error \", err.Error())\n\t return \"\"\n }\n defer conn.Close()\n // fmt.Println(\"conn.LocalAddr().String(),\", conn.LocalAddr().String())\n //log.Debugf(\"conn.LocalAddr().String(),\", conn.LocalAddr().String())\n // fmt.Println(strings.Split(conn.LocalAddr().String(), \":\")[0])\n return strings.Split(conn.LocalAddr().String(), \":\")[0]\n}", "func (i *Client) GetIP() (string, error) {\n\thttpClient := i.HTTPClient\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\n\tres, err := httpClient.Get(baseURL)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer res.Body.Close()\n\n\tip, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(ip), nil\n}", "func MyIPAddress() string {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn \"127.0.0.1\"\n\t}\n\treturn DNSResolve(hostname)\n}", "func (m *BgpConfiguration) GetPeerIpAddress()(*string) {\n val, err := m.GetBackingStore().Get(\"peerIpAddress\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func GetIP() (ip string) {\n\n\thost, _ := os.Hostname()\n\taddrs, _ := net.LookupIP(host)\n\tfor _, addr := range addrs {\n\t\tif ipv4 := addr.To4(); ipv4 != nil && !ipv4.IsLoopback() {\n\t\t\t//fmt.Println(\"IPv4: \", ipv4.String())\n\t\t\tip = ipv4.String()\n\t\t}\n\t}\n\treturn ip\n}", "func (o ElastigroupNetworkInterfaceOutput) PrivateIpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupNetworkInterface) *string { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)\n}", "func (h *Host) GetAccessIP() string {\n\tip := h.GetPublicIP()\n\tif ip == \"\" {\n\t\tip = h.GetPrivateIP()\n\t}\n\treturn ip\n}", "func (o LookupGroupResultOutput) IpAddress() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupGroupResult) string { return v.IpAddress }).(pulumi.StringOutput)\n}", "func (o CustomerGatewayOutput) IpAddress() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *CustomerGateway) pulumi.StringPtrOutput { return v.IpAddress }).(pulumi.StringPtrOutput)\n}", "func GetServiceVersionIPAddress(serviceName string, versionTag string) (string, string) {\n\tfoundInstances := GetServiceInstances(serviceName)\n\tfor _, instance := range foundInstances {\n\t\tif listContains(instance.Tags, versionTag) == true {\n\t\t\tipport := strings.Split(instance.Endpoint.Value, \":\")\n\t\t\treturn ipport[0], ipport[1]\n\t\t}\n\t}\n\treturn \"\", \"\"\n}", "func (o *WafEventNetwork) GetIp() string {\n\tif o == nil || o.Ip == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Ip\n}", "func GetServerExternalIPAddress() (string, error) {\n\tif Conf.Settings.System.IPAddress != \"\" {\n\t\treturn Conf.Settings.System.IPAddress, nil\n\t}\n\n\t// Create the default consensus, using the default configuration and no sphlog.\n\tconsensus := externalip.DefaultConsensus(nil, nil)\n\n\t// Get your IP, which is never <nil> when err is <nil>.\n\tip, err := consensus.ExternalIP()\n\tif err != nil {\n\t\treturn \"\", errors.New(\"connection to external network could not be detected\")\n\t}\n\n\treturn TrimSpaceNewlineInString(ip.String()), nil // return IPv4/IPv6 in string format\n}" ]
[ "0.7920907", "0.72071975", "0.71239483", "0.6998655", "0.69610465", "0.6900017", "0.67306906", "0.67055154", "0.667737", "0.6630442", "0.65781665", "0.65764624", "0.65495", "0.65411216", "0.6536848", "0.6535142", "0.6501289", "0.64331317", "0.6390965", "0.6369778", "0.634591", "0.63449883", "0.6329122", "0.63267285", "0.63181126", "0.6286289", "0.6274113", "0.6267141", "0.6259409", "0.6248431", "0.6234889", "0.62200737", "0.62092596", "0.61790794", "0.6154084", "0.61326337", "0.6099907", "0.60410523", "0.6037637", "0.60336685", "0.6022948", "0.6012263", "0.60110474", "0.59923744", "0.5975214", "0.5967306", "0.5961601", "0.59611785", "0.59428823", "0.59425676", "0.593536", "0.59327203", "0.59314317", "0.59287727", "0.59112847", "0.5908841", "0.59055066", "0.5905168", "0.5900941", "0.58981985", "0.58907133", "0.58811396", "0.5879791", "0.58755124", "0.587386", "0.58710426", "0.5851538", "0.5848984", "0.58426386", "0.5822956", "0.5821802", "0.5816989", "0.5808074", "0.5793515", "0.5790437", "0.57740974", "0.57717097", "0.5767639", "0.5761796", "0.5757073", "0.57540834", "0.5748288", "0.57457244", "0.5736984", "0.5735399", "0.5732114", "0.57167125", "0.5696646", "0.56784046", "0.5674731", "0.56741023", "0.5667355", "0.5662577", "0.56620824", "0.5659427", "0.56573945", "0.5650474", "0.5643571", "0.56392735", "0.56259596" ]
0.7475399
1
makeReady prepares an EC2 instance for running remote SSH commands
func (ins *EC2RemoteClient) makeReady() error { // Check Instance is running - will error if instance doesn't exist result, err := ins.ec2Client.DescribeInstanceStatus(&ec2.DescribeInstanceStatusInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})}) if err != nil { return fmt.Errorf("Error getting instance status : %s", err) } // Start instance if needed if len(result.InstanceStatuses) == 0 || *result.InstanceStatuses[0].InstanceState.Name != "running" { err = ins.startInstance() if err != nil { return fmt.Errorf("Error starting instance : %s", err) } } // Get Public IP address from ec2 err = ins.getIPAddress() if err != nil { return fmt.Errorf("Error getting IP address : %s", err) } // Set up SSH connection ins.cmdClient, err = sshCmdClient.NewSSHCmdClient(ins.instanceIP, ins.sshCredentials) if err != nil { return err } // Check we can at least run a trivial command exitStatus, err := ins.RunCommand("true") if err != nil || exitStatus != 0 { return fmt.Errorf("Error running commands on instance : %s", err) } return err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func setupServer(c *cli.Context) {\n started := time.Now()\n\n config := deployConfig()\n logger := &logger{Prefix: config.Host}\n ssh := newSSHClient(config.Host, config.User)\n\n ssh.execute(fmt.Sprintf(\"mkdir -p %s\", config.DeployTo))\n\n for _, t := range config.Setup {\n ssh.execute(t)\n }\n\n ssh.close()\n\n logger.infof(\"Done in %f.\", time.Now().Sub(started).Seconds())\n}", "func (instance *Host) WaitSSHReady(ctx context.Context, timeout time.Duration) (_ string, ferr fail.Error) {\n\tdefer fail.OnPanic(&ferr)\n\n\tif valid.IsNil(instance) {\n\t\treturn \"\", fail.InvalidInstanceError()\n\t}\n\tif ctx == nil {\n\t\treturn \"\", fail.InvalidParameterCannotBeNilError(\"ctx\")\n\t}\n\n\treturn instance.waitInstallPhase(ctx, userdata.PHASE5_FINAL, timeout)\n}", "func (ins *EC2RemoteClient) startInstance() error {\n\tlog.Printf(\"Starting EC2 Instance %s\", ins.InstanceID)\n\t_, err := ins.ec2Client.StartInstances(&ec2.StartInstancesInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error starting instance : %s\", err)\n\t}\n\tlog.Printf(\"Waiting for Instance %s to become ready (may take a few minutes)\", ins.InstanceID)\n\terr = ins.ec2Client.WaitUntilInstanceStatusOk(&ec2.DescribeInstanceStatusInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error waiting for instance to become available : %s\", err)\n\t}\n\treturn err\n}", "func (i EC2Instance) Setup() error {\n\tlog.Printf(\"DEBUG:aws: Setting up a compute instance\\n\")\n\t// must be able to deal with the exit status of script is 255 b/c of reboot command\n\tconf := utils.Config(\"partitions\").Lookup(i.partition).Contains()\n\tsetup, ok := conf[\"setup\"]\n\tif !ok {\n\t\tlog.Printf(\"DEBUG:aws: No setup required\\n\")\n\t\treturn nil\n\t}\n\tdirSplit := strings.SplitAfter(setup.Self(), \"/\")\n\tdir := strings.Join(dirSplit[:len(dirSplit)-1], \"\")\n\terr := exec.Command(setup.Self(), i.Name(), dir, conf[\"router\"].Self(), conf[\"salt\"].Self()).Run()\n\tif err != nil && !strings.Contains(err.Error(), \"255\") {\n\t\treturn fmt.Errorf(\"WARNING:aws: could not setup instance %s due to %v\", i.Name(), err)\n\t}\n\treturn nil\n}", "func ConnectEC2(sshEntries lib.SSHEntries, sshConfigPath string, args []string) {\n\t// get the pub key from the ssh agent first\n\tsshAgent, err := net.Dial(\"unix\", os.Getenv(\"SSH_AUTH_SOCK\"))\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"can't connect to ssh agent, maybe SSH_AUTH_SOCK is unset?\")\n\t}\n\n\tkeys, err := agent.NewClient(sshAgent).List()\n\tif err != nil || len(keys) < 1 {\n\t\tlog.Fatal(\"Can't get public keys from ssh agent. Please ensure you have the ssh-agent running and have at least one identity added (with ssh-add)\")\n\t}\n\tpubkey := keys[0].String()\n\n\t// push the pub key to those instances one after each other\n\t// TODO: maybe make it parallel\n\tfor _, sshEntry := range sshEntries {\n\t\tvar instanceName = sshEntry.InstanceID\n\t\tif len(sshEntry.Names) > 0 {\n\t\t\tinstanceName = sshEntry.Names[0]\n\t\t}\n\t\tlog.WithField(\"instance\", instanceName).Info(\"trying to do ec2 connect...\")\n\t\tinstanceIPAddress, instanceUser, err := pushEC2Connect(sshEntry.ProfileConfig.Name, sshEntry.InstanceID, sshEntry.User, pubkey)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Fatal(\"can't push ssh key to the instance\")\n\t\t}\n\t\t// if the address is empty we set to the value we got from ec2 connect push\n\t\tif sshEntry.Address == \"\" {\n\t\t\tsshEntry.Address = instanceIPAddress\n\t\t}\n\t\tif sshEntry.User == \"\" {\n\t\t\tsshEntry.User = instanceUser\n\t\t}\n\t}\n\n\t// then generate ssh config for all instances in sshEntries\n\t// save the dynamic ssh config first\n\tif err := sshEntries.SaveConfig(sshConfigPath); err != nil {\n\t\tlog.WithError(err).Fatal(\"can't save ssh config for ec2 connect\")\n\t}\n\n\tvar instanceName = sshEntries[0].InstanceID\n\tif len(sshEntries[0].Names) > 0 {\n\t\tinstanceName = sshEntries[0].Names[0]\n\t}\n\t// connect to the first instance in sshEntry, as the other will be bastion(s)\n\tif len(args) == 0 {\n\t\t// construct default args\n\t\targs = []string{\n\t\t\t\"ssh\",\n\t\t\t\"-tt\",\n\t\t\tinstanceName,\n\t\t}\n\t}\n\n\tcommand, err := exec.LookPath(args[0])\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Can't find the binary in the PATH\")\n\t}\n\n\tvar replacer = strings.NewReplacer(\n\t\t\"{host}\", instanceName,\n\t\t\"{user}\", sshEntries[0].User,\n\t)\n\tvar newArgs []string\n\tfor _, arg := range args {\n\t\tnewArgs = append(newArgs, replacer.Replace(arg))\n\t}\n\tlog.WithField(\"instance_id\", sshEntries[0].InstanceID).Infof(\"Connecting to the instance using '%s'\", strings.Join(newArgs, \" \"))\n\n\tif err := syscall.Exec(command, newArgs, os.Environ()); err != nil {\n\t\tlog.WithFields(log.Fields{\"command\": command}).WithError(err).Fatal(\"can't run the command\")\n\t}\n}", "func AWSCreate() {\n\tSetClusterName()\n\tif _, err := os.Stat(\"./inventory/\" + common.Name + \"/provisioner/.terraform\"); err == nil {\n\t\tfmt.Println(\"Configuration folder already exists\")\n\t} else {\n\t\tsshUser, osLabel := distSelect()\n\t\tfmt.Printf(\"Prepairing Setup for user %s on %s\\n\", sshUser, osLabel)\n\t\tos.MkdirAll(\"./inventory/\"+common.Name+\"/provisioner\", 0755)\n\t\terr := exec.Command(\"cp\", \"-rfp\", \"./kubespray/contrib/terraform/aws/.\", \"./inventory/\"+common.Name+\"/provisioner\").Run()\n\t\tcommon.ErrorCheck(\"provisioner could not provided: %v\", err)\n\t\tprepareConfigFiles(osLabel)\n\t\tprovisioner.ExecuteTerraform(\"init\", \"./inventory/\"+common.Name+\"/provisioner/\")\n\t}\n\n\tprovisioner.ExecuteTerraform(\"apply\", \"./inventory/\"+common.Name+\"/provisioner/\")\n\n\t// waiting for Loadbalancer and other not completed stuff\n\tfmt.Println(\"Infrastructure is upcoming.\")\n\ttime.Sleep(15 * time.Second)\n\treturn\n\n}", "func (e *SSHExecutor) Initialize(config SSHConfig) {\n\t// set default values\n\tif config.Port <= 0 {\n\t\tconfig.Port = 22\n\t}\n\n\tif config.Timeout == 0 {\n\t\tconfig.Timeout = time.Second * 5 // default timeout is 5 sec\n\t}\n\n\t// build easyssh config\n\te.Config = &easyssh.MakeConfig{\n\t\tServer: config.Host,\n\t\tPort: strconv.Itoa(config.Port),\n\t\tUser: config.User,\n\t\tTimeout: config.Timeout, // timeout when connecting to remote\n\t}\n\n\t// prefer private key authentication\n\tif len(config.KeyFile) > 0 {\n\t\te.Config.KeyPath = config.KeyFile\n\t\te.Config.Passphrase = config.Passphrase\n\t} else if len(config.Password) > 0 {\n\t\te.Config.Password = config.Password\n\t}\n}", "func (p *EC2Provisioner) CreateInstance(opts EC2CreateInstanceOptions) (*cfg.Remote, error) {\n\t// Set requested region\n\tp.WithRegion(opts.Region)\n\n\t// set highlighter\n\tvar highlight = out.NewColorer(out.CY)\n\n\t// Generate authentication\n\tvar keyName = fmt.Sprintf(\"%s_%s_inertia_key_%d\", opts.Name, p.user, time.Now().UnixNano())\n\tout.Fprintf(p.out, highlight.Sf(\":key: Generating key pair '%s'...\\n\", keyName))\n\tkeyResp, err := p.client.CreateKeyPair(&ec2.CreateKeyPairInput{\n\t\tKeyName: aws.String(keyName),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thomeDir, err := os.UserHomeDir()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Save key\n\tvar keyPath = filepath.Join(homeDir, \".ssh\", *keyResp.KeyName)\n\tout.Fprintf(p.out, highlight.Sf(\":inbox_tray: Saving key to '%s'...\\n\", keyPath))\n\tif err = local.SaveKey(*keyResp.KeyMaterial, keyPath); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create security group for network configuration\n\tvar secGroup = fmt.Sprintf(\"%s-%d\", opts.Name, time.Now().UnixNano())\n\tout.Fprintf(p.out, highlight.Sf(\":circus_tent: Creating security group '%s'...\\n\", secGroup))\n\tgroup, err := p.client.CreateSecurityGroup(&ec2.CreateSecurityGroupInput{\n\t\tGroupName: aws.String(secGroup),\n\t\tDescription: aws.String(\n\t\t\tfmt.Sprintf(\"Rules for project %s on %s\", opts.ProjectName, opts.Name),\n\t\t),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Set rules for ports\n\tout.Fprintf(p.out, highlight.Sf(\":electric_plug: Exposing ports '%s'...\\n\", secGroup))\n\tif err = p.exposePorts(*group.GroupId, opts.DaemonPort, opts.Ports); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Start up instance\n\tout.Fprintf(p.out, highlight.Sf(\":boat: Requesting instance '%s'...\\n\", secGroup))\n\trunResp, err := p.client.RunInstances(&ec2.RunInstancesInput{\n\t\tImageId: aws.String(opts.ImageID),\n\t\tInstanceType: aws.String(opts.InstanceType),\n\t\tMinCount: aws.Int64(1),\n\t\tMaxCount: aws.Int64(1),\n\n\t\t// Security options\n\t\tKeyName: keyResp.KeyName,\n\t\tSecurityGroupIds: []*string{group.GroupId},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check response validity\n\tif runResp.Instances == nil || len(runResp.Instances) == 0 {\n\t\treturn nil, errors.New(\"Unable to start instances: \" + runResp.String())\n\t}\n\tout.Fprintf(p.out, highlight.Sf(\"A %s instance has been provisioned\", opts.InstanceType))\n\n\t// Loop until intance is running\n\tvar instance ec2.Instance\n\tfor {\n\t\t// Wait briefly between checks\n\t\ttime.Sleep(3 * time.Second)\n\n\t\t// Request instance status\n\t\tout.Fprintf(p.out, \"Checking status of the requested instance...\\n\")\n\t\tresult, err := p.client.DescribeInstances(&ec2.DescribeInstancesInput{\n\t\t\tInstanceIds: []*string{runResp.Instances[0].InstanceId},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Check if reservations are present\n\t\tif result.Reservations == nil || len(result.Reservations) == 0 ||\n\t\t\tlen(result.Reservations[0].Instances) == 0 {\n\t\t\t// A reservation corresponds to a command to start instances\n\t\t\t// If nothing is here... we gotta keep waiting\n\t\t\tfmt.Fprintln(p.out, \"No reservations found yet.\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get status\n\t\ts := result.Reservations[0].Instances[0].State\n\t\tif s == nil {\n\t\t\tfmt.Println(p.out, \"Status unknown.\")\n\t\t\tcontinue\n\t\t}\n\n\t\t// Code 16 means instance has started, and we can continue!\n\t\tif s.Code != nil && *s.Code == codeEC2InstanceStarted {\n\t\t\tfmt.Fprintln(p.out, \"Instance is running!\")\n\t\t\tinstance = *result.Reservations[0].Instances[0]\n\t\t\tbreak\n\t\t}\n\n\t\t// Otherwise, keep polling\n\t\tif s.Name != nil {\n\t\t\tfmt.Fprintln(p.out, \"Instance status: \"+*s.Name)\n\t\t} else {\n\t\t\tfmt.Fprintln(p.out, \"Instance status: \"+s.String())\n\t\t}\n\t\tcontinue\n\t}\n\n\t// Check instance validity\n\tif instance.PublicDnsName == nil {\n\t\treturn nil, errors.New(\"Unable to find public IP address for instance: \" + instance.String())\n\t}\n\n\t// Set tags\n\tout.Fprintf(p.out, \"Setting tags on instance...\\n\")\n\tif _, err = p.client.CreateTags(&ec2.CreateTagsInput{\n\t\tResources: []*string{instance.InstanceId},\n\t\tTags: []*ec2.Tag{\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Name\"),\n\t\t\t\tValue: aws.String(opts.Name),\n\t\t\t},\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Purpose\"),\n\t\t\t\tValue: aws.String(\"Inertia Continuous Deployment\"),\n\t\t\t},\n\t\t},\n\t}); err != nil {\n\t\tfmt.Fprintln(p.out, \"Failed to set tags: \"+err.Error())\n\t}\n\n\t// Poll for SSH port to open\n\tfmt.Fprintln(p.out, \"Waiting for ports to open...\")\n\tfor {\n\t\ttime.Sleep(3 * time.Second)\n\t\tfmt.Fprintln(p.out, \"Checking ports...\")\n\t\tif conn, err := net.Dial(\"tcp\", *instance.PublicDnsName+\":22\"); err == nil {\n\t\t\tfmt.Fprintln(p.out, \"Connection established!\")\n\t\t\tconn.Close()\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Generate webhook secret\n\tout.Fprintf(p.out, \"Generating a webhook secret...\\n\")\n\twebhookSecret, err := common.GenerateRandomString()\n\tif err != nil {\n\t\tfmt.Fprintln(p.out, err.Error())\n\t\tfmt.Fprintln(p.out, \"Using default secret 'inertia'\")\n\t\twebhookSecret = \"interia\"\n\t} else {\n\t\tfmt.Fprintf(p.out, \"Generated webhook secret: '%s'\\n\", webhookSecret)\n\t}\n\n\t// Return remote configuration\n\treturn &cfg.Remote{\n\t\tName: opts.Name,\n\t\tIP: *instance.PublicDnsName,\n\t\tSSH: &cfg.SSH{\n\t\t\tUser: p.user,\n\t\t\tIdentityFile: keyPath,\n\t\t\tSSHPort: \"22\",\n\t\t},\n\t\tDaemon: &cfg.Daemon{\n\t\t\tPort: strconv.FormatInt(opts.DaemonPort, 10),\n\t\t\tWebHookSecret: webhookSecret,\n\t\t},\n\t\tProfiles: make(map[string]string),\n\t}, nil\n}", "func waitForHosts(path string) {\n\toldPwd := sh.Pwd()\n\tsh.Cd(path)\n\tlog.Debug(\"Ensuring ansible-playbook can be executed properly\")\n\tsh.SetE(exec.Command(\"ansible-playbook\", \"--version\"))\n\tpathToPlaybook := \"./playbooks/wait-for-hosts.yml\"\n\tansibleCommand := []string{\n\t\t\"-i\", \"plugins/inventory/terraform.py\",\n\t\t\"-e\", \"ansible_python_interpreter=\" + strings.TrimSpace(pythonBinary),\n\t\t\"-e\", \"@security.yml\",\n\t\tpathToPlaybook,\n\t}\n\tcmd := exec.Command(\"ansible-playbook\", ansibleCommand...)\n\tlog.Info(\"Waiting for SSH access to hosts...\")\n\toutStr, err := ExecuteWithOutput(cmd)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"command\": cmd.Args,\n\t\t\t\"output\": outStr,\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatalf(\"Couldn't execute playbook %s\", pathToPlaybook)\n\t}\n\tsh.Cd(oldPwd)\n}", "func (m *InfrastructureProviderAWS) Bootstrap() {\n\tm.createInstances()\n\tfor i := 0; i < 50; i++ {\n\t\ttime.Sleep(5 * time.Second)\n\t\tif m.assureRunning() {\n\t\t\tlog.Info(\"all instances are running\")\n\t\t\tbreak\n\t\t}\n\t}\n\tm.collectPublicAddresses()\n\tm.dumpPrivateKeys()\n\t// TODO: general retry function, even if VM is in state \"running\" ssh may be unavailable,\n\t// has no flag to know it for sure\n\tlog.Infof(\"awaiting ssh is available\")\n\ttime.Sleep(60 * time.Second)\n\tm.provision()\n}", "func runAndWaitForInstance(svc *ec2.EC2, name string, params *ec2.RunInstancesInput) (ec2.Instance, error) {\n\trunResult, err := svc.RunInstances(params)\n\tif err != nil {\n\t\treturn ec2.Instance{}, gruntworkerrors.WithStackTrace(err)\n\t}\n\n\tif len(runResult.Instances) == 0 {\n\t\terr := errors.New(\"Could not create test EC2 instance\")\n\t\treturn ec2.Instance{}, gruntworkerrors.WithStackTrace(err)\n\t}\n\n\terr = svc.WaitUntilInstanceExists(&ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t&ec2.Filter{\n\t\t\t\tName: awsgo.String(\"instance-id\"),\n\t\t\t\tValues: []*string{runResult.Instances[0].InstanceId},\n\t\t\t},\n\t\t},\n\t})\n\n\tif err != nil {\n\t\treturn ec2.Instance{}, gruntworkerrors.WithStackTrace(err)\n\t}\n\n\t// Add test tag to the created instance\n\t_, err = svc.CreateTags(&ec2.CreateTagsInput{\n\t\tResources: []*string{runResult.Instances[0].InstanceId},\n\t\tTags: []*ec2.Tag{\n\t\t\t{\n\t\t\t\tKey: awsgo.String(\"Name\"),\n\t\t\t\tValue: awsgo.String(name),\n\t\t\t},\n\t\t},\n\t})\n\n\tif err != nil {\n\t\treturn ec2.Instance{}, gruntworkerrors.WithStackTrace(err)\n\t}\n\n\t// EC2 Instance must be in a running before this function returns\n\terr = svc.WaitUntilInstanceRunning(&ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t&ec2.Filter{\n\t\t\t\tName: awsgo.String(\"instance-id\"),\n\t\t\t\tValues: []*string{runResult.Instances[0].InstanceId},\n\t\t\t},\n\t\t},\n\t})\n\n\tif err != nil {\n\t\treturn ec2.Instance{}, gruntworkerrors.WithStackTrace(err)\n\t}\n\n\treturn *runResult.Instances[0], nil\n\n}", "func (s *ssh) WaitReady(hostName string, timeout time.Duration) error {\n\tif timeout < utils.TimeoutCtxHost {\n\t\ttimeout = utils.TimeoutCtxHost\n\t}\n\thost := &host{session: s.session}\n\tcfg, err := host.SSHConfig(hostName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn conv.ToSystemSshConfig(cfg).WaitServerReady(timeout)\n}", "func (svc *SSHService) WaitServerReady(hostParam interface{}, timeout time.Duration) error {\n\tvar err error\n\tsshSvc := NewSSHService(svc.provider)\n\tssh, err := sshSvc.GetConfig(hostParam)\n\tif err != nil {\n\t\treturn logicErrf(err, \"Failed to read SSH config\")\n\t}\n\twaitErr := ssh.WaitServerReady(timeout)\n\treturn infraErr(waitErr)\n}", "func pushEC2Connect(profile, instanceID, instanceUser, pubKey string) (string, string, error) {\n\tctx := log.WithField(\"instance_id\", instanceID)\n\tcfg, err := config.LoadDefaultConfig(context.TODO(),\n\t\tconfig.WithSharedConfigProfile(profile))\n\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"can't get aws session: %s\", err)\n\t}\n\tec2Svc := ec2.NewFromConfig(cfg)\n\tec2Result, err := ec2Svc.DescribeInstances(context.TODO(), &ec2.DescribeInstancesInput{\n\t\tInstanceIds: []string{instanceID},\n\t})\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"can't get ec2 instance: %s\", err)\n\t}\n\n\tif len(ec2Result.Reservations) == 0 || len(ec2Result.Reservations[0].Instances) == 0 {\n\t\treturn \"\", \"\", fmt.Errorf(\"Couldn't find the instance %s\", instanceID)\n\t}\n\n\tec2Instance := ec2Result.Reservations[0].Instances[0]\n\tec2ICSvc := ec2instanceconnect.NewFromConfig(cfg)\n\n\t// no username has been provided, so we try to get it fom the instance tag first\n\tif instanceUser == \"\" {\n\t\tctx.Debug(\"no user has been set provided, trying to get it from the tags\")\n\t\t// next try to get username from the instance tags\n\t\tif instanceUser = lib.GetUserFromTags(ec2Instance.Tags); instanceUser == \"\" {\n\t\t\t// otherwise fallback to default\n\t\t\tctx.WithField(\"user\", defaultUser).Debugf(\"got no user from the instance tags, setting to default\")\n\t\t\tinstanceUser = defaultUser\n\t\t} else {\n\t\t\tctx.WithField(\"user\", instanceUser).Debugf(\"got username from tags\")\n\t\t}\n\t}\n\n\tctx.WithField(\"user\", instanceUser).Info(\"pushing SSH key...\")\n\n\tif _, err := ec2ICSvc.SendSSHPublicKey(context.TODO(), &ec2instanceconnect.SendSSHPublicKeyInput{\n\t\tInstanceId: ec2Instance.InstanceId,\n\t\tInstanceOSUser: aws.String(instanceUser),\n\t\tAvailabilityZone: ec2Instance.Placement.AvailabilityZone,\n\t\tSSHPublicKey: aws.String(pubKey),\n\t}); err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"can't push ssh key: %s\", err)\n\t}\n\tvar address = aws.ToString(ec2Instance.PrivateIpAddress)\n\tif aws.ToString(ec2Instance.PublicIpAddress) != \"\" {\n\t\taddress = aws.ToString(ec2Instance.PublicIpAddress)\n\t}\n\treturn address, instanceUser, nil\n}", "func cmdSSH() {\n\tswitch state := status(B2D.VM); state {\n\tcase vmUnregistered:\n\t\tlog.Fatalf(\"%s is not registered.\", B2D.VM)\n\tcase vmRunning:\n\t\tcmdParts := append(strings.Fields(B2D.SSHPrefix), fmt.Sprintf(\"%d\", B2D.SSHPort), \"docker@localhost\")\n\t\tif err := cmd(cmdParts[0], cmdParts[1:]...); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\tdefault:\n\t\tlog.Fatalf(\"%s is not running.\", B2D.VM)\n\t}\n}", "func testSSHToPublicHost(t *testing.T, terraformOptions *terraform.Options) {\n\t//get the GCP instance\n\tproject := terraformOptions.Vars[\"project\"].(string)\n\tinstanceName := terraformOptions.Vars[\"name\"].(string)\n\tinstance := gcp.FetchInstance(t, project, instanceName)\n\n\t// generate a ssh key pair\n\tkeyPair := ssh.GenerateRSAKeyPair(t, 2048)\n\n\t// add the public ssh key to the compute engine metadata\n\tsshUsername := \"terratest\"\n\tpublicKey := keyPair.PublicKey\n\tinstance.AddSshKey(t, sshUsername, publicKey)\n\n\t// Run `terraform output` to get the value of an output variable\n\tpublicInstanceIP := terraform.Output(t, terraformOptions, \"compute_engine_public_ip\")\n\n\t// We're going to try to SSH to the instance IP, using the Key Pair we created earlier, and the user \"terratest\",\n\t// as we know the Instance is running an Ubuntu AMI that has such a user\n\tpublicHost := ssh.Host{\n\t\tHostname: publicInstanceIP,\n\t\tSshKeyPair: keyPair,\n\t\tSshUserName: sshUsername,\n\t}\n\n\t// It can take a minute or so for the Instance to boot up, so retry a few times\n\tmaxRetries := 10\n\ttimeBetweenRetries := 5 * time.Second\n\tdescription := fmt.Sprintf(\"SSH to public host %s\", publicInstanceIP)\n\n\t// Run a simple echo command on the server\n\texpectedText := \"Hello, World\"\n\tcommand := fmt.Sprintf(\"echo -n '%s'\", expectedText)\n\n\t// Verify that we can SSH to the Instance and run commands\n\tretry.DoWithRetry(t, description, maxRetries, timeBetweenRetries, func() (string, error) {\n\t\tactualText, err := ssh.CheckSshCommandE(t, publicHost, command)\n\n\t\tif err != nil {\n\t\t\tlogger.Log(t, emoji.Sprint(\"--- :cross_mark: FAIL: testSSHToPublicHost\"))\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif strings.TrimSpace(actualText) != expectedText {\n\t\t\tlogger.Log(t, emoji.Sprint(\"--- :cross_mark: FAIL: testSSHToPublicHost\"))\n\t\t\treturn \"\", fmt.Errorf(\"Expected SSH command to return '%s' but got '%s'\", expectedText, actualText)\n\t\t}\n\n\t\tlogger.Log(t, emoji.Sprint(\"--- :check_mark_button: PASS: testSSHToPublicHost\"))\n\t\treturn \"\", nil\n\t})\n}", "func (a *AliyunInstanceAttribute) createBastionHostInstance(sshPublicKey []byte) {\n\tres, err := ExecCmdReturnOutput(\"bash\", \"-c\", \"aliyun ecs DescribeInstances --VpcId=\"+a.VpcID)\n\tcheckError(err)\n\tdecodedQuery := decodeAndQueryFromJSONString(res)\n\n\tinstances, err := decodedQuery.Array(\"Instances\", \"Instance\")\n\tcheckError(err)\n\tbastionServerExists := false\n\tfor _, iter := range instances {\n\t\tinstance := jsonq.NewQuery(iter)\n\t\tinstanceName, err := instance.String(\"InstanceName\")\n\t\tcheckError(err)\n\t\tif instanceName == a.BastionInstanceName {\n\t\t\tbastionServerExists = true\n\t\t\ta.BastionInstanceID, err = instance.String(\"InstanceId\")\n\t\t\tcheckError(err)\n\t\t\tif checkIsThereGardenerUser(a.BastionInstanceID) {\n\t\t\t\ta.BastionSSHUser = \"gardener\"\n\t\t\t} else {\n\t\t\t\t// The bastion is created before `gardener-user` change\n\t\t\t\ta.BastionSSHUser = \"root\"\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !bastionServerExists {\n\t\tuserData := getBastionUserData(sshPublicKey)\n\t\tencodedUserData := base64.StdEncoding.EncodeToString(userData)\n\n\t\targuments := \"aliyun ecs CreateInstance --ImageId=\" + a.ImageID + \" --InstanceType=\" + a.InstanceType + \" --RegionId=\" + a.RegionID + \" --ZoneId=\" + a.ZoneID + \" --VSwitchId=\" + a.VSwitchID + \" --InstanceChargeType=\" + a.InstanceChargeType + \" --InternetChargeType=\" + a.InternetChargeType + \" --InternetMaxBandwidthIn=\" + a.InternetMaxBandwidthIn + \" --InternetMaxBandwidthOut=\" + a.InternetMaxBandwidthOut + \" --IoOptimized=\" + a.IoOptimized + \" --InstanceName=\" + a.BastionInstanceName + \" --SecurityGroupId=\" + a.BastionSecurityGroupID + \" --UserData=\" + encodedUserData\n\t\tres, err = ExecCmdReturnOutput(\"bash\", \"-c\", arguments)\n\t\tcheckError(err)\n\t\tdecodedQuery = decodeAndQueryFromJSONString(res)\n\t\ta.BastionInstanceID, err = decodedQuery.String(\"InstanceId\")\n\t\ta.BastionSSHUser = \"gardener\"\n\t\tcheckError(err)\n\t\tattemptCnt := 0\n\t\tfor attemptCnt < 60 {\n\t\t\tres, err = ExecCmdReturnOutput(\"bash\", \"-c\", \"aliyun ecs DescribeInstances --InstanceIds=\\\"['\"+a.BastionInstanceID+\"']\\\"\")\n\t\t\tcheckError(err)\n\t\t\tdecodedQuery = decodeAndQueryFromJSONString(res)\n\t\t\ttotalCount, err := decodedQuery.Int(\"TotalCount\")\n\t\t\tcheckError(err)\n\t\t\tif totalCount == 1 {\n\t\t\t\ttime.Sleep(time.Second * 30)\n\t\t\t\tfmt.Println(\"Bastion host created.\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfmt.Println(\"Creating bastion host...\")\n\t\t\ttime.Sleep(time.Second * 2)\n\t\t\tattemptCnt++\n\t\t}\n\t\tif attemptCnt == 60 {\n\t\t\tfmt.Println(\"Bastion host creation time out. Please try again.\")\n\t\t\tos.Exit(2)\n\t\t}\n\t}\n}", "func (ssh *SSHConfig) WaitServerReady(timeout time.Duration) error {\n\terr := retry.WhileUnsuccessfulDelay5Seconds(\n\t\tfunc() error {\n\t\t\tcmd, err := ssh.Command(\"sudo cat /var/tmp/user_data.done\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tretcode, _, stderr, err := cmd.Run()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif retcode != 0 {\n\t\t\t\tif retcode == 255 {\n\t\t\t\t\treturn fmt.Errorf(\"ssh not ready\")\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"%s\", stderr)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\ttimeout,\n\t)\n\tif err != nil {\n\t\toriginalErr := err\n\t\tlogCmd, err := ssh.Command(\"sudo cat /var/tmp/user_data.log\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tretcode, stdout, stderr, logErr := logCmd.Run()\n\t\tif logErr == nil {\n\t\t\tif retcode == 0 {\n\t\t\t\treturn fmt.Errorf(\"server '%s' is not ready yet : %s, Log content of file user_data.log: %s\", ssh.Host, originalErr.Error(), stdout)\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"server '%s' is not ready yet : %s, Error reading user_data.log: %s\", ssh.Host, originalErr.Error(), stderr)\n\t\t}\n\n\t\treturn fmt.Errorf(\"server '%s' is not ready yet : %s\", ssh.Host, originalErr.Error())\n\t}\n\treturn nil\n}", "func (s *DockerSandbox) MakeReady() (err error) {\n\t// make sure image is pulled\n\timgExists, err := s.mgr.DockerImageExists(s.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !imgExists {\n\t\tif err := s.mgr.dockerPull(s.name); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// make sure container is created\n\tcontExists, err := s.mgr.dockerContainerExists(s.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !contExists {\n\t\tif _, err := s.mgr.dockerCreate(s.name, []string{}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetConfiguredAndRunningSSHServer(t *testing.T, serverID string, localMode bool, instanceState *terraform.InstanceState, output terraform.UIOutput) *TestingSSHServer {\n\tauthUser := &TestingSSHUser{\n\t\tUsername: instanceState.Ephemeral.ConnInfo[\"user\"],\n\t\tPublicKey: TestSSHUserKeyPublic,\n\t}\n\tsshConfig := &TestingSSHServerConfig{\n\t\tServerID: serverID,\n\t\tHostKey: TestSSHHostKeyPrivate,\n\t\tHostPort: fmt.Sprintf(\"%s:%s\", instanceState.Ephemeral.ConnInfo[\"host\"], instanceState.Ephemeral.ConnInfo[\"port\"]),\n\t\tAuthenticatedUsers: []*TestingSSHUser{authUser},\n\t\tListeners: 5,\n\t\tOutput: output,\n\t\tLogPrintln: true,\n\t\tLocalMode: localMode,\n\t}\n\tsshServer := NewTestingSSHServer(t, sshConfig)\n\tgo sshServer.Start()\n\n\tselect {\n\tcase <-sshServer.ReadyNotify():\n\tcase <-time.After(ServerWaitTimeoutDuration):\n\t\tt.Fatal(\"Expected the TestingSSHServer to be running.\")\n\t}\n\n\t// we need to update the instance info with the address the SSH server is bound on:\n\th, p, err := sshServer.ListeningHostPort()\n\tif err != nil {\n\t\tt.Fatal(\"Expected the SSH server to return an address it is bound on but got an error\", err)\n\t}\n\n\t// set connection details based on where the SSH server is bound:\n\tinstanceState.Ephemeral.ConnInfo[\"host\"] = h\n\tinstanceState.Ephemeral.ConnInfo[\"port\"] = p\n\n\treturn sshServer\n}", "func (v *Vagrant) setup(start bool, env []string, numNodes int) error {\n\tv.nodes = map[string]TestbedNode{}\n\n\tvCmd := &VagrantCommand{ContivNodes: numNodes}\n\tvCmd.Env = append(vCmd.Env, env...)\n\n\tif start {\n\t\toutput, err := vCmd.RunWithOutput(\"up\")\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Vagrant up failed. Error: %s Output: \\n%s\\n\",\n\t\t\t\terr, output)\n\t\t\treturn err\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif err != nil {\n\t\t\t\tv.Teardown()\n\t\t\t}\n\t\t}()\n\t}\n\n\tv.expectedNodes = numNodes\n\n\toutput, err := vCmd.RunWithOutput(\"status\")\n\tif err != nil {\n\t\tlog.Errorf(\"Vagrant status failed. Error: %s Output: \\n%s\\n\",\n\t\t\terr, output)\n\t\treturn err\n\t}\n\n\t// now some hardwork of finding the names of the running nodes from status output\n\tre, err := regexp.Compile(\"[a-zA-Z0-9_\\\\- ]*running \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tnodeNamesBytes := re.FindAll(output, -1)\n\tif nodeNamesBytes == nil {\n\t\terr = fmt.Errorf(\"No running nodes found in vagrant status output: \\n%s\\n\",\n\t\t\toutput)\n\t\treturn err\n\t}\n\tnodeNames := []string{}\n\tfor _, nodeNameByte := range nodeNamesBytes {\n\t\tnodeName := strings.Fields(string(nodeNameByte))[0]\n\t\tnodeNames = append(nodeNames, nodeName)\n\t}\n\n\tif len(nodeNames) != numNodes {\n\t\terr = fmt.Errorf(\"Number of running node(s) (%d) is not equal to number of expected node(s) (%d) in vagrant status output: \\n%s\\n\",\n\t\t\tlen(nodeNames), numNodes, output)\n\t\treturn err\n\t}\n\n\t// some more work to figure the ssh port and private key details\n\t// XXX: vagrant ssh-config --host <> seems to be broken as-in it doesn't\n\t// correctly filter the output based on passed host-name. So filtering\n\t// the output ourselves below.\n\tif output, err = vCmd.RunWithOutput(\"ssh-config\"); err != nil {\n\t\treturn fmt.Errorf(\"Error running vagrant ssh-config. Error: %s. Output: \\n%s\\n\", err, output)\n\t}\n\n\tif re, err = regexp.Compile(\"Host [a-zA-Z0-9_-]+|HostName.*|Port [0-9]+|IdentityFile .*\"); err != nil {\n\t\treturn err\n\t}\n\n\tnodeInfosBytes := re.FindAll(output, -1)\n\tif nodeInfosBytes == nil {\n\t\treturn fmt.Errorf(\"Failed to find node info in vagrant ssh-config output: \\n%s\\n\", output)\n\t}\n\n\t// got the names, now fill up the vagrant-nodes structure\n\tfor _, nodeName := range nodeNames {\n\t\tnodeInfoPos := -1\n\t\t// nodeInfos is a slice of node info orgranised as nodename, it's port and identity-file in that order per node\n\t\tfor j := range nodeInfosBytes {\n\t\t\tif string(nodeInfosBytes[j]) == fmt.Sprintf(\"Host %s\", nodeName) {\n\t\t\t\tnodeInfoPos = j\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif nodeInfoPos == -1 {\n\t\t\treturn fmt.Errorf(\"Failed to find %q info in vagrant ssh-config output: \\n%s\\n\", nodeName, output)\n\t\t}\n\n\t\thostnameInfo := string(nodeInfosBytes[nodeInfoPos+1])\n\t\tportInfo := string(nodeInfosBytes[nodeInfoPos+2])\n\t\tidInfo := string(nodeInfosBytes[nodeInfoPos+3])\n\n\t\thostname := strings.Split(hostnameInfo, \" \")\n\t\tif len(hostname) != 2 {\n\t\t\treturn fmt.Errorf(\"Failed to find hostname in vagrant ssh-config output:\\n%s\\n\", nodeName)\n\t\t}\n\n\t\tport := portRegexp.FindStringSubmatch(portInfo)\n\t\tif port == nil || len(port) < 2 {\n\t\t\treturn fmt.Errorf(\"Failed to find %q port info in vagrant ssh-config output: \\n%s\\n\",\n\t\t\t\tnodeName, portInfo)\n\t\t}\n\n\t\tprivKeyFile := identityFileRegexp.FindStringSubmatch(idInfo)\n\t\tif privKeyFile == nil || len(port) < 2 {\n\t\t\treturn fmt.Errorf(\"Failed to find %q identity file info in vagrant ssh-config output: \\n%s\\n.\", nodeName, idInfo)\n\t\t}\n\n\t\tlog.Infof(\"Adding node: %q(%s:%s)\", nodeName, port[1], privKeyFile[1])\n\t\tvar node *SSHNode\n\t\tif node, err = NewSSHNode(nodeName, \"vagrant\", env, hostname[1], port[1], privKeyFile[1]); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tv.nodes[node.GetName()] = TestbedNode(node)\n\t}\n\n\treturn nil\n}", "func waitForAWSInstances(api *ec2.EC2, ids []*string, d time.Duration) error {\n\tafter := time.After(d)\n\n\tonline := make(map[string]bool)\n\n\tfor len(ids) != len(online) {\n\t\tselect {\n\t\tcase <-after:\n\t\t\treturn fmt.Errorf(\"timed out waiting for instances to run\")\n\t\tdefault:\n\t\t}\n\n\t\t// don't make api calls too quickly, or we will hit the rate limit\n\n\t\ttime.Sleep(10 * time.Second)\n\n\t\tgetinst := &ec2.DescribeInstancesInput{\n\t\t\tInstanceIds: ids,\n\t\t}\n\n\t\tinsts, err := api.DescribeInstances(getinst)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, r := range insts.Reservations {\n\t\t\tfor _, i := range r.Instances {\n\t\t\t\t// skip instances known to be up\n\t\t\t\tif online[*i.InstanceId] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// \"running\"\n\t\t\t\tif *i.State.Code == int64(16) {\n\t\t\t\t\t// XXX: ssh is a terrible way to check this, but it is all we have.\n\t\t\t\t\tc, err := net.DialTimeout(\"tcp\", *i.PublicIpAddress+\":22\", 10*time.Second)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tc.Close()\n\n\t\t\t\t\tonline[*i.InstanceId] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *InfrastructureProviderAWS) Bootstrap() *CreatedInstances {\n\tinstances, err := m.createInstances()\n\tif err != nil {\n\t\tlog.Error(\"failed to create instances: %s\", err)\n\t}\n\tfor i := 0; i < 50; i++ {\n\t\ttime.Sleep(5 * time.Second)\n\t\tif m.assureRunning() {\n\t\t\tlog.Info(\"all instances are running\")\n\t\t\tbreak\n\t\t}\n\t}\n\tm.collectPublicAddresses(instances)\n\tm.dumpPrivateKeysToFile(instances)\n\t// TODO: general retry function, even if VM is in state \"running\" ssh may be unavailable,\n\t// has no flag to know it for sure\n\treturn instances\n}", "func (a *AliyunInstanceAttribute) startBastionHostInstance() {\n\tattemptCnt := 0\n\tfor attemptCnt < 60 {\n\t\tres, err := ExecCmdReturnOutput(\"bash\", \"-c\", \"aliyun ecs DescribeInstanceAttribute --InstanceId=\"+a.BastionInstanceID)\n\t\tcheckError(err)\n\t\tdecodedQuery := decodeAndQueryFromJSONString(res)\n\t\tstatus, err := decodedQuery.String(\"Status\")\n\t\tcheckError(err)\n\t\tif status == \"Running\" {\n\t\t\ttime.Sleep(time.Second * 30)\n\t\t\tfmt.Println(\"Bastion host started.\")\n\t\t\tbreak\n\t\t} else if status == \"Stopped\" {\n\t\t\tfmt.Println(\"Starting bastion host...\")\n\t\t\t_, err = ExecCmdReturnOutput(\"bash\", \"-c\", \"aliyun ecs StartInstance --InstanceId=\"+a.BastionInstanceID)\n\t\t\tcheckError(err)\n\t\t} else if status == \"Starting\" {\n\t\t\tfmt.Println(\"Waiting for bastion host to start...\")\n\t\t} else if status == \"Stopping\" {\n\t\t\tfmt.Println(\"Bastion host is currently stopping...\")\n\t\t}\n\t\ttime.Sleep(time.Second * 2)\n\t\tattemptCnt++\n\t}\n\tif attemptCnt == 60 {\n\t\tfmt.Println(\"Bastion host starting time out. Please try again.\")\n\t\tos.Exit(2)\n\t}\n\tfmt.Println(\"Allocating bastion host IP address...\")\n\tres, err := ExecCmdReturnOutput(\"bash\", \"-c\", \"aliyun ecs AllocatePublicIpAddress --InstanceId=\"+a.BastionInstanceID)\n\tcheckError(err)\n\tdecodedQuery := decodeAndQueryFromJSONString(res)\n\ta.BastionIP, err = decodedQuery.String(\"IpAddress\")\n\tcheckError(err)\n\ttime.Sleep(time.Second * 10)\n\tfmt.Println(\"Bastion host IP address allocated.\")\n}", "func prepareInitCommand(terragruntOptions *options.TerragruntOptions, terragruntConfig *config.TerragruntConfig, allowSourceDownload bool) error {\n\tif terragruntConfig.RemoteState != nil {\n\t\t// Initialize the remote state if necessary (e.g. create S3 bucket and DynamoDB table)\n\t\tremoteStateNeedsInit, err := remoteStateNeedsInit(terragruntConfig.RemoteState, terragruntOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif remoteStateNeedsInit {\n\t\t\tif err := terragruntConfig.RemoteState.Initialize(terragruntOptions); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// Add backend config arguments to the command\n\t\tterragruntOptions.InsertTerraformCliArgs(terragruntConfig.RemoteState.ToTerraformInitArgs()...)\n\t}\n\treturn nil\n}", "func cmdInit() {\n\tif state := status(B2D.VM); state != vmUnregistered {\n\t\tlog.Fatalf(\"%s already exists.\\n\")\n\t}\n\n\tif ping(fmt.Sprintf(\"localhost:%d\", B2D.DockerPort)) {\n\t\tlog.Fatalf(\"DOCKER_PORT=%d on localhost is occupied. Please choose another none.\", B2D.DockerPort)\n\t}\n\n\tif ping(fmt.Sprintf(\"localhost:%d\", B2D.SSHPort)) {\n\t\tlog.Fatalf(\"SSH_HOST_PORT=%d on localhost is occupied. Please choose another one.\", B2D.SSHPort)\n\t}\n\n\tlog.Printf(\"Creating VM %s...\", B2D.VM)\n\tif err := vbm(\"createvm\", \"--name\", B2D.VM, \"--register\"); err != nil {\n\t\tlog.Fatalf(\"failed to create vm: %s\", err)\n\t}\n\n\tif err := vbm(\"modifyvm\", B2D.VM,\n\t\t\"--ostype\", \"Linux26_64\",\n\t\t\"--cpus\", fmt.Sprintf(\"%d\", runtime.NumCPU()),\n\t\t\"--memory\", fmt.Sprintf(\"%d\", B2D.Memory),\n\t\t\"--rtcuseutc\", \"on\",\n\t\t\"--acpi\", \"on\",\n\t\t\"--ioapic\", \"on\",\n\t\t\"--hpet\", \"on\",\n\t\t\"--hwvirtex\", \"on\",\n\t\t\"--vtxvpid\", \"on\",\n\t\t\"--largepages\", \"on\",\n\t\t\"--nestedpaging\", \"on\",\n\t\t\"--firmware\", \"bios\",\n\t\t\"--bioslogofadein\", \"off\",\n\t\t\"--bioslogofadeout\", \"off\",\n\t\t\"--bioslogodisplaytime\", \"0\",\n\t\t\"--biosbootmenu\", \"disabled\",\n\t\t\"--boot1\", \"dvd\"); err != nil {\n\t\tlog.Fatal(\"failed to modify vm: %s\", err)\n\t}\n\n\tlog.Printf(\"Setting VM networking\")\n\tif err := vbm(\"modifyvm\", B2D.VM, \"--nic1\", \"nat\", \"--nictype1\", \"virtio\", \"--cableconnected1\", \"on\"); err != nil {\n\t\tlog.Fatalf(\"failed to modify vm: %s\", err)\n\t}\n\n\tif err := vbm(\"modifyvm\", B2D.VM,\n\t\t\"--natpf1\", fmt.Sprintf(\"ssh,tcp,127.0.0.1,%d,,22\", B2D.SSHPort),\n\t\t\"--natpf1\", fmt.Sprintf(\"docker,tcp,127.0.0.1,%d,,4243\", B2D.DockerPort)); err != nil {\n\t\tlog.Fatalf(\"failed to modify vm: %s\", err)\n\t}\n\tlog.Printf(\"Port forwarding [ssh]: host tcp://127.0.0.1:%d --> guest tcp://0.0.0.0:22\", B2D.SSHPort)\n\tlog.Printf(\"Port forwarding [docker]: host tcp://127.0.0.1:%d --> guest tcp://0.0.0.0:4243\", B2D.DockerPort)\n\n\tif _, err := os.Stat(B2D.ISO); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tcmdDownload()\n\t\t} else {\n\t\t\tlog.Fatalf(\"failed to open ISO image: %s\", err)\n\t\t}\n\t}\n\n\tif _, err := os.Stat(B2D.Disk); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\terr := makeDiskImage(B2D.Disk, B2D.DiskSize)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"failed to create disk image: %s\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Fatalf(\"failed to open disk image: %s\", err)\n\t\t}\n\t}\n\n\tlog.Printf(\"Setting VM disks\")\n\tif err := vbm(\"storagectl\", B2D.VM, \"--name\", \"SATA\", \"--add\", \"sata\", \"--hostiocache\", \"on\"); err != nil {\n\t\tlog.Fatalf(\"failed to add storage controller: %s\", err)\n\t}\n\n\tif err := vbm(\"storageattach\", B2D.VM, \"--storagectl\", \"SATA\", \"--port\", \"0\", \"--device\", \"0\", \"--type\", \"dvddrive\", \"--medium\", B2D.ISO); err != nil {\n\t\tlog.Fatalf(\"failed to attach storage device: %s\", err)\n\t}\n\n\tif err := vbm(\"storageattach\", B2D.VM, \"--storagectl\", \"SATA\", \"--port\", \"1\", \"--device\", \"0\", \"--type\", \"hdd\", \"--medium\", B2D.Disk); err != nil {\n\t\tlog.Fatalf(\"failed to attach storage device: %s\", err)\n\t}\n\n\tlog.Printf(\"Done.\")\n\tlog.Printf(\"You can now type `%s up` and wait for the VM to start.\", os.Args[0])\n}", "func (s *web) ready() {\n\tif s.instance == nil {\n\t\ts.instance = echo.New()\n\t}\n}", "func sshToAlicloudNode(targetReader TargetReader, nodeName, path, user, pathSSKeypair string, sshPublicKey []byte, myPublicIP string, flagProviderID string) {\n\t// Check if this is a cleanup command\n\tif nodeName == \"cleanup\" {\n\t\tcleanupAliyunBastionHost(targetReader)\n\t\treturn\n\t}\n\n\tfmt.Println(\"(1/5) Configuring aliyun cli\")\n\tconfigureAliyunCLI()\n\tvar target Target\n\tReadTarget(pathTarget, &target)\n\tfmt.Println(\"Aliyun cli configured.\")\n\n\ta := &AliyunInstanceAttribute{}\n\ta.MyPublicIP = myPublicIP + \"/32\"\n\ta.FlagProviderID = flagProviderID\n\tfmt.Println(\"\")\n\tfmt.Println(\"(2/5) Fetching data from target shoot cluster\")\n\ta.fetchAttributes(targetReader, nodeName)\n\tfmt.Println(\"Data fetched from target shoot cluster.\")\n\n\tfmt.Println(\"\")\n\tfmt.Println(\"(3/5) Setting up bastion host security group\")\n\ta.createBastionHostSecurityGroup()\n\tfmt.Println(\"Bastion host security group set up.\")\n\n\tdefer checkIsDeletionWanted(targetReader, a.BastionInstanceID)\n\n\tfmt.Println(\"\")\n\tfmt.Println(\"(4/5) Setting up bastion host\")\n\ta.createBastionHostInstance(sshPublicKey)\n\tfmt.Println(\"Bastion host set up.\")\n\n\tfmt.Println(\"\")\n\tfmt.Println(\"(5/5) Starting bastion host\")\n\ta.startBastionHostInstance()\n\tfmt.Println(\"Bastion host started.\")\n\n\tkey := filepath.Join(pathSSKeypair, \"key\")\n\tsshCmd := \"ssh -i \" + key + \" -o \\\"ProxyCommand ssh -i \" + key + \" -o StrictHostKeyChecking=no -W \" + a.PrivateIP + \":22 \" + a.BastionSSHUser + \"@\" + a.BastionIP + \"\\\" \" + user + \"@\" + a.PrivateIP + \" -o StrictHostKeyChecking=no\"\n\tcmd := exec.Command(\"bash\", \"-c\", sshCmd)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (vp *scalewayProvider) createServer(options providers.CreateInstanceOptions) (string, error) {\n\t// Fetch SSH keys\n\tsshKeys, err := providers.FetchSSHKeys(options.SSHKeyGithubAccount)\n\tif err != nil {\n\t\treturn \"\", maskAny(err)\n\t}\n\n\t// Create cloud-config\n\t// user-data\n\tccOpts := options.NewCloudConfigOptions()\n\tccOpts.PrivateIPv4 = \"$private_ipv4\"\n\tccOpts.SshKeys = sshKeys\n\t_ /*userData*/, err = templates.Render(cloudConfigTemplate, ccOpts)\n\tif err != nil {\n\t\treturn \"\", maskAny(err)\n\t}\n\n\tvar arch string\n\tswitch options.TypeID[:2] {\n\tcase \"C1\":\n\t\tarch = \"arm\"\n\tcase \"C2\", \"VC\":\n\t\tarch = \"x86_64\"\n\t}\n\n\t// Find image\n\timageIdentifier, err := vp.client.GetImageID(options.ImageID, arch)\n\tif err != nil {\n\t\tvp.Logger.Errorf(\"GetImageID failed: %#v\", err)\n\t\treturn \"\", maskAny(err)\n\t}\n\n\tname := options.InstanceName\n\timage := &imageIdentifier.Identifier\n\tdynamicIPRequired := true\n\t//bootscript := \"\"\n\n\tvolID := \"\"\n\t/*if options.TypeID != commercialTypeVC1 {\n\t\tvolDef := api.ScalewayVolumeDefinition{\n\t\t\tName: vp.volumeName(name),\n\t\t\tSize: volumeSize,\n\t\t\tType: volumeType,\n\t\t\tOrganization: vp.organization,\n\t\t}\n\t\tvolID, err = vp.client.PostVolume(volDef)\n\t\tif err != nil {\n\t\t\tvp.Logger.Errorf(\"PostVolume failed: %#v\", err)\n\t\t\treturn \"\", maskAny(err)\n\t\t}\n\t}*/\n\n\tpublicIPIdentifier := \"\"\n\tif options.RoleLoadBalancer {\n\t\tip, err := vp.getFreeIP()\n\t\tif err != nil {\n\t\t\treturn \"\", maskAny(err)\n\t\t}\n\t\tpublicIPIdentifier = ip.ID\n\t}\n\n\topts := api.ScalewayServerDefinition{\n\t\tName: name,\n\t\tImage: image,\n\t\tVolumes: map[string]string{},\n\t\tDynamicIPRequired: &dynamicIPRequired,\n\t\t//Bootscript: &bootscript,\n\t\tTags: []string{\n\t\t\toptions.ClusterInfo.ID,\n\t\t\toptions.TincIpv4,\n\t\t},\n\t\tOrganization: vp.organization,\n\t\tCommercialType: options.TypeID,\n\t\tPublicIP: publicIPIdentifier,\n\t}\n\tif volID != \"\" {\n\t\topts.Volumes[\"0\"] = volID\n\t}\n\tvp.Logger.Debugf(\"Creating server %s: %#v\\n\", name, opts)\n\tid, err := vp.client.PostServer(opts)\n\tif err != nil {\n\t\tvp.Logger.Errorf(\"PostServer failed: %#v\", err)\n\t\t// Delete volume\n\t\tif volID != \"\" {\n\t\t\tif err := vp.client.DeleteVolume(volID); err != nil {\n\t\t\t\tvp.Logger.Errorf(\"DeleteVolume failed: %#v\", err)\n\t\t\t}\n\t\t}\n\t\treturn \"\", maskAny(err)\n\t}\n\n\t// Start server\n\tif err := vp.client.PostServerAction(id, \"poweron\"); err != nil {\n\t\tvp.Logger.Errorf(\"poweron failed: %#v\", err)\n\t\treturn \"\", maskAny(err)\n\t}\n\n\t// Wait until server starts\n\tserver, err := vp.waitUntilServerActive(id, true)\n\tif err != nil {\n\t\treturn \"\", maskAny(err)\n\t}\n\n\t// Bootstrap\n\tbootstrap, err := templates.Render(bootstrapTemplate, nil)\n\tif err != nil {\n\t\treturn \"\", maskAny(err)\n\t}\n\tinstance := vp.clusterInstance(server, true)\n\tvp.Logger.Infof(\"Running bootstrap on %s. This may take a while...\", server.Name)\n\tif err := instance.RunScript(vp.Logger, bootstrap, \"/root/pulcy-bootstrap.sh\"); err != nil {\n\t\t// Failed expected because of a reboot\n\t\tvp.Logger.Debugf(\"bootstrap failed (expected): %#v\", err)\n\t}\n\n\tvp.Logger.Infof(\"Done running bootstrap on %s, rebooting...\", server.Name)\n\tif err := vp.client.PostServerAction(id, \"reboot\"); err != nil {\n\t\tvp.Logger.Errorf(\"reboot failed: %#v\", err)\n\t\treturn \"\", maskAny(err)\n\t}\n\ttime.Sleep(time.Second * 5)\n\tif _, err := vp.waitUntilServerActive(id, false); err != nil {\n\t\treturn \"\", maskAny(err)\n\t}\n\n\tvp.Logger.Infof(\"Created server %s %s\\n\", id, name)\n\n\treturn id, nil\n}", "func SSH(params *SSHInput) error {\n\t// read the manifest\n\tzoneManifest, err := ReadManifest(params.ManifestPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tborderEIP, err := getTerraformOutput(\"border_eip\", zoneManifest.TerraformState)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\targs := []string{\n\t\t\"-q\",\n\t\t\"-o\",\n\t\tfmt.Sprintf(\n\t\t\t\"ProxyCommand=ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -W %%h:%%p ubuntu@%s\", borderEIP),\n\t\t\"-o\", \"UserKnownHostsFile=/dev/null\",\n\t\t\"-o\", \"StrictHostKeyChecking=no\",\n\t\tfmt.Sprintf(\"ubuntu@%s\", params.Host),\n\t}\n\targs = append(args, params.Args...)\n\n\tcmd := exec.Command(\"ssh\", args...)\n\tcmd.Env = os.Environ()\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}", "func WaitReady(ctx *util.Context) error {\n\tif !ctx.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\tctx.Logger.Infoln(\"Waiting for machine-controller to come up…\")\n\n\t// Wait a bit to let scheduler to react\n\ttime.Sleep(10 * time.Second)\n\n\tif err := WaitForWebhook(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller-webhook did not come up\")\n\t}\n\n\tif err := WaitForMachineController(ctx.DynamicClient); err != nil {\n\t\treturn errors.Wrap(err, \"machine-controller did not come up\")\n\t}\n\treturn nil\n}", "func setupServer() (sL net.Listener, ip string, port int, pubKey ssh.PublicKey) {\n\tssh.Handle(func(s ssh.Session) {\n\t\tfmt.Fprintln(s, \"test\")\n\t\ts.Exit(0)\n\t})\n\tvar (\n\t\tl net.Listener\n\t\tlIP string\n\t\tlPort int\n\t\tsigner ssh2.Signer\n\t\terrC = make(chan error, 1)\n\t\t// WaitGroup to know when to start error timer. Key\n\t\t// generation can take longer than the timeout duration, so without\n\t\t// this, the test can fail.\n\t\twg sync.WaitGroup\n\t)\n\twg.Add(1)\n\n\tgo func() {\n\t\tvar err error\n\t\tl, err = net.Listen(\"tcp\", \":\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ttcpAddr := l.Addr().(*net.TCPAddr)\n\t\tlIP = tcpAddr.IP.String()\n\t\tlPort = tcpAddr.Port\n\t\tlPort = l.Addr().(*net.TCPAddr).Port\n\t\tpriv, err := rsa.GenerateKey(rand.Reader, 1024)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tsigner, err = ssh2.NewSignerFromKey(priv)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\twg.Done()\n\n\t\tsrv := &ssh.Server{\n\t\t\tHandler: nil,\n\t\t\tPasswordHandler: func(user, password string) bool {\n\t\t\t\t// For example only, this is not secure.\n\t\t\t\treturn user == \"test\" && password == \"password123\"\n\t\t\t},\n\t\t}\n\t\tsrv.AddHostKey(signer.(ssh.Signer))\n\t\tsrv.Serve(l)\n\t\terrC <- ssh.Serve(l,\n\t\t\tnil,\n\t\t\tssh.PasswordAuth(func(user, password string) bool {\n\t\t\t\t// For example only, this is not secure.\n\t\t\t\treturn user == \"test\" && password == \"password123\"\n\t\t\t}))\n\t}()\n\ttimer := time.NewTimer(100 * time.Millisecond)\n\tdefer timer.Stop()\n\n\twg.Wait()\n\tselect {\n\tcase err := <-errC:\n\t\tpanic(err)\n\tcase <-timer.C:\n\t}\n\treturn l, lIP, lPort, signer.PublicKey()\n}", "func waitForInit() error {\n\tstart := time.Now()\n\tmaxEnd := start.Add(time.Minute)\n\tfor {\n\t\t// Check for existence of vpcCniInitDonePath\n\t\tif _, err := os.Stat(vpcCniInitDonePath); err == nil {\n\t\t\t// Delete the done file in case of a reboot of the node or restart of the container (force init container to run again)\n\t\t\tif err := os.Remove(vpcCniInitDonePath); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t// If file deletion fails, log and allow retry\n\t\t\tlog.Errorf(\"Failed to delete file: %s\", vpcCniInitDonePath)\n\t\t}\n\t\tif time.Now().After(maxEnd) {\n\t\t\treturn errors.Errorf(\"time exceeded\")\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func (c App) EstablishSSHConnection() revel.Result {\n\tsshIPHostname := strings.TrimSpace(c.Params.Get(\"ssh_ip\"))\n\tsshUser := strings.TrimSpace(c.Params.Get(\"ssh_user\"))\n\tsshPassword := c.Params.Get(\"ssh_password\")\n\tsshPort := strings.TrimSpace(c.Params.Get(\"ssh_port\"))\n\n\tvar err error\n\n\tif sshIPHostname == \"\" {\n\t\tresponse := CompileJSONResult(false, \"SSH IP is empty\")\n\t\treturn c.RenderJSON(response)\n\t} else if sshIPHostname == MockSSHHostString {\n\t\tif !MockSSHServer {\n\t\t\tgo createMockSSHServer()\n\t\t\ttime.Sleep(time.Second)\n\t\t\tMockSSHServer = true\n\t\t}\n\t\tsshIPHostname = \"127.0.0.1\"\n\t}\n\n\tif sshUser == \"\" {\n\t\tusername, err := user.Current()\n\t\tif err != nil {\n\t\t\tresponse := CompileJSONResult(false, \"You didn't specify SSH user and we were not able to determine it from your system\")\n\t\t\treturn c.RenderJSON(response)\n\t\t}\n\t\tsshUser = username.Username\n\t}\n\n\tif sshPort == \"\" {\n\t\tsshPort = \"22\"\n\t} else {\n\t\tif _, err := strconv.Atoi(sshPort); err != nil {\n\t\t\tresponse := CompileJSONResult(false, \"You specified wrong SSH port\")\n\t\t\treturn c.RenderJSON(response)\n\t\t}\n\t}\n\n\tSSHclient, SSHsession, err = createSSHSession(sshIPHostname, sshUser, sshPassword, sshPort)\n\n\tif err != nil {\n\t\tswitch err.Error() {\n\t\tcase \"cannot dial\":\n\t\t\tresponse := CompileJSONResult(false, \"We could not reach '\"+sshIPHostname+\":\"+sshPort+\"' OR login/password is incorrect\")\n\t\t\treturn c.RenderJSON(response)\n\t\tcase \"unable to create session\":\n\t\t\tresponse := CompileJSONResult(false, \"We reached '\"+sshIPHostname+\":\"+sshPort+\"' but could not create a test session\")\n\t\t\treturn c.RenderJSON(response)\n\t\tdefault:\n\t\t\tresponse := CompileJSONResult(false, err.Error())\n\t\t\treturn c.RenderJSON(response)\n\t\t}\n\t}\n\treturn nil\n}", "func waitForApiServerToBeUp(svcMasterIp string, sshClientConfig *ssh.ClientConfig,\n\ttimeout time.Duration) error {\n\tkubeConfigPath := GetAndExpectStringEnvVar(gcKubeConfigPath)\n\twaitErr := wait.PollImmediate(poll, timeout, func() (bool, error) {\n\t\tcmd := fmt.Sprintf(\"kubectl get ns,sc --kubeconfig %s\",\n\t\t\tkubeConfigPath)\n\t\tframework.Logf(\"Invoking command '%v' on host %v\", cmd,\n\t\t\tsvcMasterIp)\n\t\tcmdResult, err := sshExec(sshClientConfig, svcMasterIp,\n\t\t\tcmd)\n\t\tframework.Logf(\"result %v\", cmdResult)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif err == nil {\n\t\t\tframework.Logf(\"Apiserver is fully up\")\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\treturn waitErr\n}", "func waitUntilRDSInstanceCreated(rdsClientSess *rds.RDS, restoreParams map[string]string) error {\n\trdsClusterName := restoreParams[\"restoreRDS\"]\n\trdsInstanceName := rdsClusterName + \"-0\" // TODO: this should be handled better\n\n\tinput := &rds.DescribeDBInstancesInput{\n\t\tDBInstanceIdentifier: aws.String(rdsInstanceName),\n\t}\n\n\tstart := time.Now()\n\tmaxWaitAttempts := 120\n\n\tfmt.Printf(\"Wait until RDS instance [%v] in cluster [%v] is fully created ...\\n\", rdsInstanceName, rdsClusterName)\n\n\tfor waitAttempt := 0; waitAttempt < maxWaitAttempts; waitAttempt++ {\n\t\telapsedTime := time.Since(start)\n\t\tif waitAttempt > 0 {\n\t\t\tformattedTime := strings.Split(fmt.Sprintf(\"%6v\", elapsedTime), \".\")\n\t\t\tfmt.Printf(\"Instance creation elapsed time: %vs\\n\", formattedTime[0])\n\t\t}\n\n\t\tresp, err := rdsClientSess.DescribeDBInstances(input)\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Wait RDS instance create err %v\", err)\n\t\t}\n\n\t\tfmt.Printf(\"Instance status: [%s]\\n\", *resp.DBInstances[0].DBInstanceStatus)\n\t\tif *resp.DBInstances[0].DBInstanceStatus== \"available\" {\n\t\t\tfmt.Printf(\"RDS instance [%v] created successfully\\n\", rdsClusterName)\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(30 * time.Second)\n\t}\n\tfmt.Printf(\"RDS instance [%v] created successfully in RDS cluster [%v]\\n\", rdsInstanceName, rdsClusterName)\n\treturn nil\n}", "func main() {\n\t// Reads in the credentials.json\n\tb, err := ioutil.ReadFile(\"./secrets/credentials.json\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to read client secret file: %v\", err)\n\t}\n\n\t// Creates OAuth config\n\t// If modifying these scopes, delete your previously saved token.json.\n\tconfig, err := google.ConfigFromJSON(b, cloudshell.CloudPlatformScope)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to parse client secret file to config: %v\", err)\n\t}\n\n\t// Creates client based off the config\n\tclient := getClient(config)\n\n\t// Get cloudShellService\n\tcloudshellService, err := cloudshell.New(client)\n\n\t// Get the Enviroments subservice\n\tuserEnviromentsService := cloudshell.NewUsersEnvironmentsService(cloudshellService)\n\n\t// Generate a brand-new SSH key pair, and save them in secrets/rsa-id.pub and secrets/rsa-id.private\n\t// publicKey := generateSSHKey()\n\n\t// Start Cloudshell enviroment\n\tstartRequest := userEnviromentsService.Start(defaultCloudShellResource, &cloudshell.StartEnvironmentRequest{\n\t\t// PublicKeys: []string{publicKey},\n\t})\n\t_, err = startRequest.Do()\n\tif err != nil {\n\t\tlog.Panicf(\"Could not start cloudshell environment: %v\\n\", err)\n\t}\n\n\tcall := userEnviromentsService.Get(\"users/me/environments/default\")\n\tvar environment *cloudshell.Environment\n\n\tfor {\n\t\ttime.Sleep(time.Second)\n\n\t\tlog.Println(\"Checking status of Cloud Shell environment\")\n\t\tenvironment, err = call.Do()\n\t\tif err != nil {\n\t\t\tlog.Println(\"Could not get environment: %v\\n\", err)\n\t\t}\n\n\t\tif environment.State == \"RUNNING\" {\n\t\t\tlog.Println(\"Cloud Shell environment started\")\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Generate the ansible-playbook/inventory.yaml\n\terr = generateInventory(Inventory{\n\t\tUserName: environment.SshUsername,\n\t\tHost: environment.SshHost,\n\t\tPort: int(environment.SshPort),\n\t\tPrivateKey: \"./secrets/id_rsa\",\n\t})\n\tif err != nil {\n\t\tlog.Panicf(\"Could not generate inventory: %v\\n\", err)\n\t}\n\n}", "func CreateNodes(client *rancher.Client, rolesPerPool []string, quantityPerPool []int32) (ec2Nodes []*nodes.Node, err error) {\n\tec2Client, err := client.GetEC2Client()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trunningReservations := []*ec2.Reservation{}\n\treservationConfigs := []*rancherEc2.AWSEC2Config{}\n\t// provisioning instances in reverse order to allow windows instances time to become ready\n\tfor i := len(quantityPerPool) - 1; i >= 0; i-- {\n\t\tconfig := MatchRoleToConfig(rolesPerPool[i], ec2Client.ClientConfig.AWSEC2Config)\n\t\tif config == nil {\n\t\t\treturn nil, errors.New(\"No matching nodesAndRole for AWSEC2Config with role:\" + rolesPerPool[i])\n\t\t}\n\t\tsshName := getSSHKeyName(config.AWSSSHKeyName)\n\t\trunInstancesInput := &ec2.RunInstancesInput{\n\t\t\tImageId: aws.String(config.AWSAMI),\n\t\t\tInstanceType: aws.String(config.InstanceType),\n\t\t\tMinCount: aws.Int64(int64(quantityPerPool[i])),\n\t\t\tMaxCount: aws.Int64(int64(quantityPerPool[i])),\n\t\t\tKeyName: aws.String(sshName),\n\t\t\tBlockDeviceMappings: []*ec2.BlockDeviceMapping{\n\t\t\t\t{\n\t\t\t\t\tDeviceName: aws.String(\"/dev/sda1\"),\n\t\t\t\t\tEbs: &ec2.EbsBlockDevice{\n\t\t\t\t\t\tVolumeSize: aws.Int64(int64(config.VolumeSize)),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tIamInstanceProfile: &ec2.IamInstanceProfileSpecification{\n\t\t\t\tName: aws.String(config.AWSIAMProfile),\n\t\t\t},\n\t\t\tPlacement: &ec2.Placement{\n\t\t\t\tAvailabilityZone: aws.String(config.AWSRegionAZ),\n\t\t\t},\n\t\t\tNetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{\n\t\t\t\t{\n\t\t\t\t\tDeviceIndex: aws.Int64(0),\n\t\t\t\t\tAssociatePublicIpAddress: aws.Bool(true),\n\t\t\t\t\tGroups: aws.StringSlice(config.AWSSecurityGroups),\n\t\t\t\t},\n\t\t\t},\n\t\t\tTagSpecifications: []*ec2.TagSpecification{\n\t\t\t\t{\n\t\t\t\t\tResourceType: aws.String(\"instance\"),\n\t\t\t\t\tTags: []*ec2.Tag{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tKey: aws.String(\"Name\"),\n\t\t\t\t\t\t\tValue: aws.String(nodeBaseName),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tKey: aws.String(\"CICD\"),\n\t\t\t\t\t\t\tValue: aws.String(config.AWSCICDInstanceTag),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\treservation, err := ec2Client.SVC.RunInstances(runInstancesInput)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// instead of waiting on each node pool to complete provisioning, add to a queue and check run status later\n\t\trunningReservations = append(runningReservations, reservation)\n\t\treservationConfigs = append(reservationConfigs, config)\n\t}\n\n\tfor i := 0; i < len(quantityPerPool); i++ {\n\t\tvar listOfInstanceIds []*string\n\n\t\tfor _, instance := range runningReservations[i].Instances {\n\t\t\tlistOfInstanceIds = append(listOfInstanceIds, instance.InstanceId)\n\t\t}\n\n\t\t//wait until instance is running\n\t\terr = ec2Client.SVC.WaitUntilInstanceRunning(&ec2.DescribeInstancesInput{\n\t\t\tInstanceIds: listOfInstanceIds,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t//wait until instance status is ok\n\t\terr = ec2Client.SVC.WaitUntilInstanceStatusOk(&ec2.DescribeInstanceStatusInput{\n\t\t\tInstanceIds: listOfInstanceIds,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// describe instance to get attributes\n\t\tdescribe, err := ec2Client.SVC.DescribeInstances(&ec2.DescribeInstancesInput{\n\t\t\tInstanceIds: listOfInstanceIds,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treadyInstances := describe.Reservations[0].Instances\n\n\t\tsshKey, err := nodes.GetSSHKey(reservationConfigs[i].AWSSSHKeyName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, readyInstance := range readyInstances {\n\t\t\tec2Node := &nodes.Node{\n\t\t\t\tNodeID: *readyInstance.InstanceId,\n\t\t\t\tPublicIPAddress: *readyInstance.PublicIpAddress,\n\t\t\t\tPrivateIPAddress: *readyInstance.PrivateIpAddress,\n\t\t\t\tSSHUser: reservationConfigs[i].AWSUser,\n\t\t\t\tSSHKey: sshKey,\n\t\t\t}\n\t\t\t// re-reverse the list so that the order is corrected\n\t\t\tec2Nodes = append([]*nodes.Node{ec2Node}, ec2Nodes...)\n\t\t}\n\t}\n\n\tclient.Session.RegisterCleanupFunc(func() error {\n\t\treturn DeleteNodes(client, ec2Nodes)\n\t})\n\n\treturn ec2Nodes, nil\n}", "func (p *Plugin) Exec() error {\n\tif len(p.Config.Key) == 0 && len(p.Config.Password) == 0 && len(p.Config.KeyPath) == 0 {\n\t\treturn errMissingPasswordOrKey\n\t}\n\n\tif len(p.Config.Source) == 0 || len(p.Config.Target) == 0 {\n\t\treturn errMissingSourceOrTarget\n\t}\n\n\thosts := trimValues(p.Config.Host)\n\tif len(hosts) == 0 {\n\t\treturn errMissingHost\n\t}\n\n\tp.DestFile = fmt.Sprintf(\"%s.tar.gz\", random.String(10))\n\n\t// create a temporary file for the archive\n\tdir := os.TempDir()\n\tsrc := filepath.Join(dir, p.DestFile)\n\n\t// show current version\n\tfmt.Println(\"drone-scp version: \" + Version)\n\t// run archive command\n\tfmt.Println(\"tar all files into \" + src)\n\targs := p.buildTarArgs(src)\n\tcmd := exec.Command(p.Config.TarExec, args...)\n\tif p.Config.Debug {\n\t\tfmt.Println(\"$\", strings.Join(cmd.Args, \" \"))\n\t}\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn err\n\t}\n\n\twg := sync.WaitGroup{}\n\twg.Add(len(p.Config.Host))\n\terrChannel := make(chan error)\n\tfinished := make(chan struct{})\n\tfor _, host := range hosts {\n\t\tgo func(h string) {\n\t\t\tdefer wg.Done()\n\t\t\thost, port := p.hostPort(h)\n\t\t\t// Create MakeConfig instance with remote username, server address and path to private key.\n\t\t\tssh := &easyssh.MakeConfig{\n\t\t\t\tServer: host,\n\t\t\t\tUser: p.Config.Username,\n\t\t\t\tPassword: p.Config.Password,\n\t\t\t\tPort: port,\n\t\t\t\tKey: p.Config.Key,\n\t\t\t\tKeyPath: p.Config.KeyPath,\n\t\t\t\tPassphrase: p.Config.Passphrase,\n\t\t\t\tTimeout: p.Config.Timeout,\n\t\t\t\tCiphers: p.Config.Ciphers,\n\t\t\t\tFingerprint: p.Config.Fingerprint,\n\t\t\t\tUseInsecureCipher: p.Config.UseInsecureCipher,\n\t\t\t\tProxy: easyssh.DefaultConfig{\n\t\t\t\t\tServer: p.Config.Proxy.Server,\n\t\t\t\t\tUser: p.Config.Proxy.User,\n\t\t\t\t\tPassword: p.Config.Proxy.Password,\n\t\t\t\t\tPort: p.Config.Proxy.Port,\n\t\t\t\t\tKey: p.Config.Proxy.Key,\n\t\t\t\t\tKeyPath: p.Config.Proxy.KeyPath,\n\t\t\t\t\tPassphrase: p.Config.Proxy.Passphrase,\n\t\t\t\t\tTimeout: p.Config.Proxy.Timeout,\n\t\t\t\t\tCiphers: p.Config.Proxy.Ciphers,\n\t\t\t\t\tFingerprint: p.Config.Proxy.Fingerprint,\n\t\t\t\t\tUseInsecureCipher: p.Config.Proxy.UseInsecureCipher,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tsystemType := \"unix\"\n\t\t\t_, _, _, err := ssh.Run(\"ver\", p.Config.CommandTimeout)\n\t\t\tif err == nil {\n\t\t\t\tsystemType = \"windows\"\n\t\t\t}\n\n\t\t\t// upload file to the tmp path\n\t\t\tp.DestFile = fmt.Sprintf(\"%s%s\", p.Config.TarTmpPath, p.DestFile)\n\n\t\t\tp.log(host, \"remote server os type is \"+systemType)\n\t\t\t// Call Scp method with file you want to upload to remote server.\n\t\t\tp.log(host, \"scp file to server.\")\n\t\t\terr = ssh.Scp(src, p.DestFile)\n\t\t\tif err != nil {\n\t\t\t\terrChannel <- copyError{host, err.Error()}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, target := range p.Config.Target {\n\t\t\t\ttarget = strings.Replace(target, \" \", \"\\\\ \", -1)\n\t\t\t\t// remove target folder before upload data\n\t\t\t\tif p.Config.Remove {\n\t\t\t\t\tp.log(host, \"Remove target folder:\", target)\n\n\t\t\t\t\t_, _, _, err := ssh.Run(rmcmd(systemType, target), p.Config.CommandTimeout)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terrChannel <- err\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tp.log(host, \"create folder\", target)\n\t\t\t\t_, errStr, _, err := ssh.Run(mkdircmd(systemType, target), p.Config.CommandTimeout)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrChannel <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif len(errStr) != 0 {\n\t\t\t\t\terrChannel <- fmt.Errorf(errStr)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// untar file\n\t\t\t\tp.log(host, \"untar file\", p.DestFile)\n\t\t\t\tcommamd := strings.Join(p.buildUnTarArgs(target), \" \")\n\t\t\t\tif p.Config.Debug {\n\t\t\t\t\tfmt.Println(\"$\", commamd)\n\t\t\t\t}\n\t\t\t\toutStr, errStr, _, err := ssh.Run(commamd, p.Config.CommandTimeout)\n\n\t\t\t\tif outStr != \"\" {\n\t\t\t\t\tp.log(host, \"output: \", outStr)\n\t\t\t\t}\n\n\t\t\t\tif errStr != \"\" {\n\t\t\t\t\tp.log(host, \"error: \", errStr)\n\t\t\t\t}\n\n\t\t\t\tif err != nil {\n\t\t\t\t\terrChannel <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// remove tar file\n\t\t\terr = p.removeDestFile(systemType, ssh)\n\t\t\tif err != nil {\n\t\t\t\terrChannel <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}(host)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(finished)\n\t}()\n\n\tselect {\n\tcase <-finished:\n\tcase err := <-errChannel:\n\t\tif err != nil {\n\t\t\tc := color.New(color.FgRed)\n\t\t\tc.Println(\"drone-scp error: \", err)\n\t\t\tif _, ok := err.(copyError); !ok {\n\t\t\t\tfmt.Println(\"drone-scp rollback: remove all target tmp file\")\n\t\t\t\tif err := p.removeAllDestFile(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfmt.Println(\"===================================================\")\n\tfmt.Println(\"✅ Successfully executed transfer data to all host\")\n\tfmt.Println(\"===================================================\")\n\n\treturn nil\n}", "func (p *ecsProvisioner) Provision(instance *models.Instance) *provisioners.PushServiceProvisionResult {\n\tp.logger.Info(\"starting provision for instance\", zap.Any(\"instance\", instance))\n\n\tvar err error\n\tfailureResult := &provisioners.PushServiceProvisionResult{\n\t\tInstance: instance,\n\t\tStatus: provisioners.PushServiceProvisionStatusFailure,\n\t\tEnvVars: map[string]string{},\n\t}\n\n\trole, err := getIamRole(p.provisionerConfig.iam)\n\tif err != nil {\n\t\tp.logger.Error(\"failed while provisioning instance, failed to get iam role\", zap.Any(\"instance\", instance), zap.Error(err))\n\t\treturn failureResult\n\t}\n\n\t/*\n\t\tpush-redis\n\t*/\n\tchRedis := make(chan provisionPushRedisResult)\n\tgo p.pushRedisProvisioner.Provision(instance, chRedis)\n\tresultPushRedis := <-chRedis\n\tif resultPushRedis.err != nil {\n\t\tp.logger.Error(\"push-redis: provision failure\", zap.Any(\"instance\", instance), zap.Error(resultPushRedis.err))\n\t\t// TODO deprovision\n\t\treturn failureResult\n\t}\n\tp.logger.Info(\"push-redis: provision success\", zap.Any(\"instance\", instance))\n\n\t/*\n\t\tpush-stream\n\t*/\n\tchStream := make(chan provisionPushStreamResult)\n\tgo p.pushStreamProvisioner.Provision(instance, role, chStream)\n\tresultPushStream := <-chStream\n\tif resultPushStream.err != nil {\n\t\tp.logger.Error(\"push-stream: provision failure\", zap.Any(\"instance\", instance), zap.Error(resultPushStream.err))\n\t\t// TODO deprovision\n\t\treturn failureResult\n\t}\n\tp.logger.Info(\"push-stream: provision success\", zap.Any(\"instance\", instance))\n\n\t/*\n\t\tpush-api\n\t*/\n\tchApi := make(chan provisionPushApiResult)\n\t// TODO technical debt\n\tpushStreamPublicIp := *resultPushStream.eni.NetworkInterfaces[0].Association.PublicIp\n\tusername := \"app\"\n\tpassword := uniuri.New()\n\tgo p.pushApiProvisioner.Provision(instance, role, username, password, pushStreamPublicIp, chApi)\n\tresultPushApi := <-chApi\n\tif resultPushApi.err != nil {\n\t\tp.logger.Error(\"push-api: provision failure\", zap.Any(\"instance\", instance), zap.Error(resultPushApi.err))\n\t\t// TODO deprovision\n\t\treturn failureResult\n\t}\n\tp.logger.Info(\"push-api: provision success\", zap.Any(\"instance\", instance))\n\n\tp.logger.Info(\n\t\t\"finishing provision for instance\",\n\t\tzap.Any(\"instance\", instance),\n\t\tzap.Any(\"resultPushRedis\", resultPushRedis),\n\t\tzap.Any(\"resultPushStream\", resultPushStream),\n\t\tzap.Any(\"resultPushApi\", resultPushApi),\n\t)\n\n\t// TODO technical debt\n\tpushApiPrivateIp := *resultPushApi.eni.NetworkInterfaces[0].PrivateIpAddress\n\n\tenvVars := map[string]string{\n\t\tprovisioners.EnvVarEndpoint: fmt.Sprintf(\"http://%s:%s\", pushApiPrivateIp, pushApiPort),\n\t\tprovisioners.EnvVarPassword: password,\n\t\tprovisioners.EnvVarUsername: username,\n\t}\n\n\treturn &provisioners.PushServiceProvisionResult{\n\t\tInstance: instance,\n\t\tEnvVars: envVars,\n\t\tStatus: provisioners.PushServiceProvisionStatusSuccess,\n\t}\n}", "func cmdStart() {\n\tswitch state := status(B2D.VM); state {\n\tcase vmUnregistered:\n\t\tlog.Fatalf(\"%s is not registered.\", B2D.VM)\n\tcase vmRunning:\n\t\tlog.Printf(\"%s is already running.\", B2D.VM)\n\tcase vmPaused:\n\t\tlog.Printf(\"Resuming %s\", B2D.VM)\n\t\tif err := vbm(\"controlvm\", B2D.VM, \"resume\"); err != nil {\n\t\t\tlog.Fatalf(\"Failed to resume vm: %s\", err)\n\t\t}\n\t\taddr := fmt.Sprintf(\"localhost:%d\", B2D.SSHPort)\n\t\tif err := read(addr); err != nil {\n\t\t\tlog.Fatalf(\"Failed to connect to SSH port at %s: %s\", addr, err)\n\t\t}\n\t\tlog.Printf(\"Resumed.\")\n\tcase vmSaved, vmPoweroff, vmAborted:\n\t\tlog.Printf(\"Starting %s...\", B2D.VM)\n\t\tif err := vbm(\"startvm\", B2D.VM, \"--type\", \"headless\"); err != nil {\n\t\t\tlog.Fatalf(\"Failed to start vm: %s\", err)\n\t\t}\n\t\tlog.Printf(\"Waiting for SSH server to start...\")\n\t\taddr := fmt.Sprintf(\"localhost:%d\", B2D.SSHPort)\n\t\tif err := read(addr); err != nil {\n\t\t\tlog.Fatalf(\"Failed to connect to SSH port at %s: %s\", addr, err)\n\t\t}\n\t\tlog.Printf(\"Started.\")\n\tdefault:\n\t\tlog.Fatalf(\"Cannot start %s from state %.\", B2D.VM, state)\n\t}\n\n\t// Check if $DOCKER_HOST ENV var is properly configured.\n\tDockerHost := getenv(\"DOCKER_HOST\", \"\")\n\tif DockerHost != fmt.Sprintf(\"tcp://localhost:%d\", B2D.DockerPort) {\n\t\tfmt.Printf(\"\\nTo connect the docker client to the Docker daemon, please set:\\n\")\n\t\tfmt.Printf(\"export DOCKER_HOST=tcp://localhost:%d\\n\\n\", B2D.DockerPort)\n\t}\n}", "func main() {\n\tif len(os.Args) != 3 {\n\t\texitErrorf(\"AMI ID and Instance Type are required\"+\n\t\t\t\"\\nUsage: %s image_id instance_type\", os.Args[0])\n\t}\n\n\n\t//Initialize the session that the SDK uses to load credentials from the shared credentials file ~/.aws/credentials\n\tsess, err := session.NewSession(&aws.Config{Region: aws.String(\"eu-west-1\")}, )\n\tsvc := ec2.New(sess)\n\tif err != nil {\n\t\texitErrorf(\"Error creating session, %v\", err)\n\t}\n\n}", "func waitForStart(server *Server) {\n\treader := bufio.NewReader(os.Stdin)\n\ttext, _ := reader.ReadString('\\n')\n\tfmt.Println(\"IS start exec :: \", text)\n\tserver.executor.summary.startTime = time.Now().UnixNano()\n\tif text == \"start\\n\" {\n\t\tcmd := pb.ExecutionCommand{\n\t\t\tType: startExec,\n\t\t}\n\t\tfor clinetID := range server.clientStreams {\n\t\t\tserver.sendCommand(clinetID, &cmd)\n\t\t}\n\t}\n}", "func remoteStateNeedsInit(remoteState *remote.RemoteState, terragruntOptions *options.TerragruntOptions) (bool, error) {\n\n\t// We only configure remote state for the commands that use the tfstate files. We do not configure it for\n\t// commands such as \"get\" or \"version\".\n\tif remoteState != nil && util.ListContainsElement(TerraformCommandsThatUseState, util.FirstArg(terragruntOptions.TerraformCliArgs)) {\n\t\treturn remoteState.NeedsInit(terragruntOptions)\n\t}\n\treturn false, nil\n}", "func (c *ClientManager) WaitInstanceUntilReady(id int, until time.Time) error {\n\tfor {\n\t\tvirtualGuest, found, err := c.GetInstance(id, \"id, lastOperatingSystemReload[id,modifyDate], activeTransaction[id,transactionStatus.name], provisionDate, powerState.keyName\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !found {\n\t\t\treturn bosherr.WrapErrorf(err, \"SoftLayer virtual guest '%d' does not exist\", id)\n\t\t}\n\n\t\tlastReload := virtualGuest.LastOperatingSystemReload\n\t\tactiveTxn := virtualGuest.ActiveTransaction\n\t\tprovisionDate := virtualGuest.ProvisionDate\n\n\t\t// if lastReload != nil && lastReload.ModifyDate != nil {\n\t\t// \tfmt.Println(\"lastReload: \", (*lastReload.ModifyDate).Format(time.RFC3339))\n\t\t// }\n\t\t// if activeTxn != nil && activeTxn.TransactionStatus != nil && activeTxn.TransactionStatus.Name != nil {\n\t\t// \tfmt.Println(\"activeTxn: \", *activeTxn.TransactionStatus.Name)\n\t\t// }\n\t\t// if provisionDate != nil {\n\t\t// \tfmt.Println(\"provisionDate: \", (*provisionDate).Format(time.RFC3339))\n\t\t// }\n\n\t\treloading := activeTxn != nil && lastReload != nil && *activeTxn.Id == *lastReload.Id\n\t\tif provisionDate != nil && !reloading {\n\t\t\t// fmt.Println(\"power state:\", *virtualGuest.PowerState.KeyName)\n\t\t\tif *virtualGuest.PowerState.KeyName == \"RUNNING\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tnow := time.Now()\n\t\tif now.After(until) {\n\t\t\treturn bosherr.Errorf(\"Power on virtual guest with id %d Time Out!\", *virtualGuest.Id)\n\t\t}\n\n\t\tmin := math.Min(float64(10.0), float64(until.Sub(now)))\n\t\ttime.Sleep(time.Duration(min) * time.Second)\n\t}\n}", "func (tc *testContext) sshSetup() error {\n\tif err := tc.ensureTestRunnerSA(); err != nil {\n\t\treturn fmt.Errorf(\"error ensuring SA created: %w\", err)\n\t}\n\tif err := tc.ensureTestRunnerRole(); err != nil {\n\t\treturn fmt.Errorf(\"error ensuring Role created: %w\", err)\n\t}\n\tif err := tc.ensureTestRunnerRoleBinding(); err != nil {\n\t\treturn fmt.Errorf(\"error ensuring RoleBinding created: %w\", err)\n\t}\n\treturn nil\n}", "func Bootstrap(host, sshConfigPath, executable string, minionConfig *MinionConfig, masterCreds *Creds) (*Client, error) {\n\tvar gofigureClient *Client\n\n\tsshConfig, connectString, err := ssher.ClientConfig(host, sshConfigPath)\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\n\tsshConn, err := ssh.Dial(\"tcp\", connectString, sshConfig)\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\tdefer sshConn.Close()\n\n\t// TODO kill existing process?\n\n\tsftpClient, err := sftp.NewClient(sshConn)\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\tdefer sftpClient.Close()\n\n\terr = putfile(sftpClient, executable, path.Base(executable), 0700)\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\n\tfor _, filename := range []string{\n\t\tminionConfig.Creds.CAFile,\n\t\tminionConfig.Creds.CertFile,\n\t\tminionConfig.Creds.KeyFile,\n\t} {\n\t\terr = putfile(sftpClient, filename, path.Base(filename), 0600)\n\t\tif err != nil {\n\t\t\treturn gofigureClient, err\n\t\t}\n\t}\n\n\tsession, err := sshConn.NewSession()\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\tdefer session.Close()\n\n\terr = session.Start(fmt.Sprintf(\"./%s serve --bind %s --port %d --caFile %s --certFile %s --keyFile %s </dev/null &>/dev/null\",\n\t\tpath.Base(executable),\n\t\tminionConfig.Bind,\n\t\tminionConfig.Port,\n\t\tpath.Base(minionConfig.Creds.CAFile),\n\t\tpath.Base(minionConfig.Creds.CertFile),\n\t\tpath.Base(minionConfig.Creds.KeyFile),\n\t))\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\n\tsplitConnectString := strings.Split(connectString, \":\")\n\tgrpcConnectString := fmt.Sprintf(\"%s:%d\", splitConnectString[0], minionConfig.Port)\n\n\tconn, err := ConnectGRPC(grpcConnectString, masterCreds.CAFile, masterCreds.CertFile, masterCreds.KeyFile)\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\n\treturn &Client{GofigureClient: pb.NewGofigureClient(conn)}, nil\n}", "func WaitForASGInstancesAndNodesReady(ctx context.Context, f *framework.Framework, describeASGsInput *autoscaling.DescribeAutoScalingGroupsInput) error {\n\tvar asgInstanceIDs []*string\n\n\tBy(\"wait until ASG instances are ready\")\n\terr := f.Cloud.AutoScaling().WaitUntilAutoScalingGroupInService(aws.BackgroundContext(), describeASGsInput)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Get instance IDs\n\tasgInstances, err := f.Cloud.AutoScaling().DescribeInServiceAutoScalingGroupInstancesAsList(aws.BackgroundContext(), describeASGsInput)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tBy(\"wait nodes ready\")\n\tfor i, asgInstance := range asgInstances {\n\t\tlog.Debugf(\"Instance %d/%d (id: %s) is in service\", i+1, len(asgInstances), *(asgInstance.InstanceId))\n\t\tasgInstanceIDs = append(asgInstanceIDs, asgInstance.InstanceId)\n\t}\n\tdescribeInstancesInput := &ec2.DescribeInstancesInput{\n\t\tInstanceIds: asgInstanceIDs,\n\t}\n\tinstancesList, err := f.Cloud.EC2().DescribeInstancesAsList(aws.BackgroundContext(), describeInstancesInput)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tdefault:\n\t\t\t\tlog.Debug(aerr)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Debug(err)\n\t\t}\n\t\treturn err\n\t}\n\n\t// Wait until nodes exist and are ready\n\tfor i, instance := range instancesList {\n\t\tnodeName := instance.PrivateDnsName\n\t\tlog.Debugf(\"Wait until node %d/%d (%s) exists\", i+1, len(instancesList), *nodeName)\n\t\tnode := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: *nodeName}}\n\t\tnode, err = f.ResourceManager.WaitNodeExists(ctx, node)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Debugf(\"Wait until node %d/%d (%s) ready\", i+1, len(instancesList), *nodeName)\n\t\t_, err = f.ResourceManager.WaitNodeReady(ctx, node)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (t *Task) generateSSHKeys() error {\n\t// Check if already generated\n\tif t.SSHKeys != nil {\n\t\treturn nil\n\t}\n\t// Private Key generation\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 4096)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Validate Private Key\n\terr = privateKey.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt.SSHKeys = &sshKeys{\n\t\tPublicKey: &privateKey.PublicKey,\n\t\tPrivateKey: privateKey,\n\t}\n\treturn nil\n}", "func WaitReady(s *state.State) error {\n\tif !s.Cluster.MachineController.Deploy {\n\t\treturn nil\n\t}\n\n\ts.Logger.Infoln(\"Waiting for machine-controller to come up...\")\n\n\tif err := cleanupStaleResources(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForWebhook(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\tif err := waitForMachineController(s.Context, s.DynamicClient); err != nil {\n\t\treturn err\n\t}\n\n\treturn waitForCRDs(s)\n}", "func (c *Client) BootstrapRemote(repoName string) error {\n\tprintln(\"Setting up remote \\\"\" + c.Name + \"\\\" at \" + c.IP)\n\n\tprintln(\">> Step 1/4: Installing docker...\")\n\terr := c.installDocker(c.sshRunner)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintln(\"\\n>> Step 2/4: Building deploy key...\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tpub, err := c.keyGen(c.sshRunner)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// This step needs to run before any other commands that rely on\n\t// the daemon image, since the daemon is loaded here.\n\tprintln(\"\\n>> Step 3/4: Starting daemon...\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = c.DaemonUp(c.version, c.IP, c.Daemon.Port)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintln(\"\\n>> Step 4/4: Fetching daemon API token...\")\n\ttoken, err := c.getDaemonAPIToken(c.sshRunner, c.version)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Daemon.Token = token\n\n\tprintln(\"\\nInertia has been set up and daemon is running on remote!\")\n\tprintln(\"You may have to wait briefly for Inertia to set up some dependencies.\")\n\tfmt.Printf(\"Use 'inertia %s logs --stream' to check on the daemon's setup progress.\\n\\n\", c.Name)\n\n\tprintln(\"=============================\\n\")\n\n\t// Output deploy key to user.\n\tprintln(\">> GitHub Deploy Key (add to https://www.github.com/\" + repoName + \"/settings/keys/new): \")\n\tprintln(pub.String())\n\n\t// Output Webhook url to user.\n\tprintln(\">> GitHub WebHook URL (add to https://www.github.com/\" + repoName + \"/settings/hooks/new): \")\n\tprintln(\"WebHook Address: https://\" + c.IP + \":\" + c.Daemon.Port + \"/webhook\")\n\tprintln(\"WebHook Secret: \" + c.Daemon.WebHookSecret)\n\tprintln(`Note that you will have to disable SSH verification in your webhook\nsettings - Inertia uses self-signed certificates that GitHub won't\nbe able to verify.` + \"\\n\")\n\n\tprintln(`Inertia daemon successfully deployed! Add your webhook url and deploy\nkey to enable continuous deployment.`)\n\tfmt.Printf(\"Then run 'inertia %s up' to deploy your application.\\n\", c.Name)\n\n\treturn nil\n}", "func setupSpinmint(prNumber int, prRef string, repo *Repository, upgrade bool) (*ec2.Instance, error) {\n\tLogInfo(\"Setting up spinmint for PR: \" + strconv.Itoa(prNumber))\n\n\tsvc := ec2.New(session.New(), Config.GetAwsConfig())\n\n\tvar setupScript string\n\tif upgrade {\n\t\tsetupScript = repo.InstanceSetupUpgradeScript\n\t} else {\n\t\tsetupScript = repo.InstanceSetupScript\n\t}\n\n\tdata, err := ioutil.ReadFile(path.Join(\"config\", setupScript))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsdata := string(data)\n\tsdata = strings.Replace(sdata, \"BUILD_NUMBER\", strconv.Itoa(prNumber), -1)\n\tsdata = strings.Replace(sdata, \"BRANCH_NAME\", prRef, -1)\n\tbsdata := []byte(sdata)\n\tsdata = base64.StdEncoding.EncodeToString(bsdata)\n\n\tvar one int64 = 1\n\tparams := &ec2.RunInstancesInput{\n\t\tImageId: &Config.AWSImageId,\n\t\tMaxCount: &one,\n\t\tMinCount: &one,\n\t\tInstanceType: &Config.AWSInstanceType,\n\t\tUserData: &sdata,\n\t\tSecurityGroupIds: []*string{&Config.AWSSecurityGroup},\n\t}\n\n\tresp, err := svc.RunInstances(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Add tags to the created instance\n\ttime.Sleep(time.Second * 10)\n\t_, errtag := svc.CreateTags(&ec2.CreateTagsInput{\n\t\tResources: []*string{resp.Instances[0].InstanceId},\n\t\tTags: []*ec2.Tag{\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Name\"),\n\t\t\t\tValue: aws.String(\"Spinmint-\" + prRef),\n\t\t\t},\n\t\t\t{\n\t\t\t\tKey: aws.String(\"Created\"),\n\t\t\t\tValue: aws.String(time.Now().Format(\"2006-01-02/15:04:05\")),\n\t\t\t},\n\t\t},\n\t})\n\tif errtag != nil {\n\t\tLogError(\"Could not create tags for instance: \" + *resp.Instances[0].InstanceId + \" Error: \" + errtag.Error())\n\t}\n\n\treturn resp.Instances[0], nil\n}", "func main() {\n\tvar cfgFile string\n\tvar debugEnable bool\n\tvar displayVersion bool\n\tvar noColor bool\n\tvar pprofEnable bool\n\tvar shutdownAfter int\n\tvar sshPort int\n\n\tuserName := user.Name()\n\n\tflag.BoolVar(&debugEnable, \"debug\", false, \"Activate debug messages\")\n\tflag.BoolVar(&displayVersion, \"version\", false, \"Display version\")\n\tflag.BoolVar(&noColor, \"noColor\", false, \"Disable ANSII terminal colors\")\n\tflag.BoolVar(&pprofEnable, \"pprofEnable\", false, \"Enable pprof server\")\n\tflag.IntVar(&shutdownAfter, \"shutdownAfter\", 0, \"Automatically shutdown after so many seconds\")\n\tflag.IntVar(&sshPort, \"port\", 2222, \"SSH server port\")\n\tflag.StringVar(&cfgFile, \"cfg\", \"\", \"Config file path\")\n\n\tflag.Parse()\n\n\tconfig.Read(cfgFile, sshPort)\n\tcolor.Colored = !noColor\n\n\tif displayVersion {\n\t\tversion.PrintAndExit()\n\t}\n\n\tserverEnable := true\n\tsilentEnable := false\n\tnothingEnable := false\n\tlogger.Start(serverEnable, debugEnable, silentEnable, nothingEnable)\n\tdefer logger.Stop()\n\n\tif shutdownAfter > 0 {\n\t\tgo func() {\n\t\t\tdefer os.Exit(1)\n\n\t\t\tlogger.Info(\"Enabling auto shutdown timer\", shutdownAfter)\n\t\t\ttime.Sleep(time.Duration(shutdownAfter) * time.Second)\n\t\t\tlogger.Info(\"Auto shutdown timer reached, shutting down now\")\n\t\t}()\n\t}\n\n\tif pprofEnable || config.Common.PProfEnable {\n\t\tpprof.Start()\n\t}\n\n\tlogger.Info(\"Launching server\", version.String(), userName)\n\tsshServer := server.New()\n\tsshServer.Start()\n}", "func (i *instance) Go(ctx context.Context) {\n\tconst maxTries = 5\n\ttype stateT int\n\tconst (\n\t\t// Perform capacity check for EC2 spot.\n\t\tstateCapacity stateT = iota\n\t\t// Launch the instance via EC2.\n\t\tstateLaunch\n\t\t// Tag the instance\n\t\tstateTag\n\t\t// Wait for the instance to enter running state.\n\t\tstateWait\n\t\t// Describe the instance via EC2.\n\t\tstateDescribe\n\t\t// Wait for offers to appear--i.e., the Reflowlet is live.\n\t\tstateOffers\n\t\tstateDone\n\t)\n\tvar (\n\t\tstate stateT\n\t\tid string\n\t\tdns string\n\t\tn int\n\t\td = 5 * time.Second\n\t)\n\t// TODO(marius): propagate context to the underlying AWS calls\n\tfor state < stateDone && ctx.Err() == nil {\n\t\tswitch state {\n\t\tcase stateCapacity:\n\t\t\tif !i.Spot {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// 20 instances should be a good margin for spot.\n\t\t\tvar ok bool\n\t\t\tok, i.err = i.ec2HasCapacity(ctx, 20)\n\t\t\tif i.err == nil && !ok {\n\t\t\t\ti.err = errors.E(errors.Unavailable, errors.New(\"ec2 capacity is likely exhausted\"))\n\t\t\t}\n\t\tcase stateLaunch:\n\t\t\tid, i.err = i.launch(ctx)\n\t\t\tif i.err != nil {\n\t\t\t\ti.Log.Errorf(\"instance launch error: %v\", i.err)\n\t\t\t} else {\n\t\t\t\tspot := \"\"\n\t\t\t\tif i.Spot {\n\t\t\t\t\tspot = \"spot \"\n\t\t\t\t}\n\t\t\t\ti.Log.Printf(\"launched %sinstance %v: %s: %s %d %s\",\n\t\t\t\t\tspot,\n\t\t\t\t\tid, i.Config.Type,\n\t\t\t\t\tdata.Size(i.Config.Resources.Memory),\n\t\t\t\t\ti.Config.Resources.CPU,\n\t\t\t\t\tdata.Size(i.Config.Resources.Disk))\n\t\t\t}\n\n\t\tcase stateTag:\n\t\t\tinput := &ec2.CreateTagsInput{\n\t\t\t\tResources: []*string{aws.String(id)},\n\t\t\t\tTags: []*ec2.Tag{{Key: aws.String(\"Name\"), Value: aws.String(i.Tag)}},\n\t\t\t}\n\t\t\tfor k, v := range i.Labels {\n\t\t\t\tinput.Tags = append(input.Tags, &ec2.Tag{Key: aws.String(k), Value: aws.String(v)})\n\t\t\t}\n\t\t\t_, i.err = i.EC2.CreateTags(input)\n\t\tcase stateWait:\n\t\t\ti.err = i.EC2.WaitUntilInstanceRunning(&ec2.DescribeInstancesInput{\n\t\t\t\tInstanceIds: []*string{aws.String(id)},\n\t\t\t})\n\t\tcase stateDescribe:\n\t\t\tvar resp *ec2.DescribeInstancesOutput\n\t\t\tresp, i.err = i.EC2.DescribeInstances(&ec2.DescribeInstancesInput{\n\t\t\t\tInstanceIds: []*string{aws.String(id)},\n\t\t\t})\n\t\t\tif len(resp.Reservations) != 1 || len(resp.Reservations[0].Instances) != 1 {\n\t\t\t\ti.err = errors.Errorf(\"ec2.describeinstances %v: invalid output\", id)\n\t\t\t}\n\t\t\tif i.err == nil {\n\t\t\t\ti.ec2inst = resp.Reservations[0].Instances[0]\n\t\t\t\tif i.ec2inst.PublicDnsName == nil || *i.ec2inst.PublicDnsName == \"\" {\n\t\t\t\t\ti.err = errors.Errorf(\"ec2.describeinstances %v: no public DNS name\", id)\n\t\t\t\t} else {\n\t\t\t\t\tdns = *i.ec2inst.PublicDnsName\n\t\t\t\t}\n\t\t\t}\n\t\tcase stateOffers:\n\t\t\tvar pool pool.Pool\n\t\t\tpool, i.err = client.New(fmt.Sprintf(\"https://%s:9000/v1/\", dns), i.HTTPClient, nil /*log.New(os.Stderr, \"client: \", 0)*/)\n\t\t\tif i.err != nil {\n\t\t\t\ti.err = errors.E(errors.Fatal, i.err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tctx, cancel := context.WithTimeout(ctx, 10*time.Second)\n\t\t\t_, i.err = pool.Offers(ctx)\n\t\t\tif i.err != nil && strings.HasSuffix(i.err.Error(), \"connection refused\") {\n\t\t\t\ti.err = errors.E(errors.Temporary, i.err)\n\t\t\t}\n\t\t\tcancel()\n\t\tdefault:\n\t\t\tpanic(\"unknown state\")\n\t\t}\n\t\tif i.err == nil {\n\t\t\tn = 0\n\t\t\td = 5 * time.Second\n\t\t\tstate++\n\t\t\tcontinue\n\t\t}\n\t\tif n == maxTries {\n\t\t\tbreak\n\t\t}\n\t\tif awserr, ok := i.err.(awserr.Error); ok {\n\t\t\tswitch awserr.Code() {\n\t\t\t// According to EC2 API docs, these codes indicate\n\t\t\t// capacity issues.\n\t\t\t//\n\t\t\t// http://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html\n\t\t\t//\n\t\t\t// TODO(marius): add a separate package for interpreting AWS errors.\n\t\t\tcase \"InsufficientCapacity\", \"InsufficientInstanceCapacity\", \"InsufficientHostCapacity\", \"InsufficientReservedInstanceCapacity\", \"InstanceLimitExceeded\":\n\t\t\t\ti.err = errors.E(errors.Unavailable, awserr)\n\t\t\t}\n\t\t}\n\t\tswitch {\n\t\tcase i.err == nil:\n\t\tcase errors.Match(errors.Fatal, i.err):\n\t\t\treturn\n\t\tcase errors.Match(errors.Unavailable, i.err):\n\t\t\t// Return these immediately because our caller may be able to handle\n\t\t\t// them by selecting a different instance type.\n\t\t\treturn\n\t\tcase !errors.Recover(i.err).Timeout() && !errors.Recover(i.err).Temporary():\n\t\t\ti.Log.Errorf(\"instance error: %v\", i.err)\n\t\t}\n\t\ttime.Sleep(d)\n\t\tn++\n\t\td *= time.Duration(2)\n\t}\n\tif i.err != nil {\n\t\treturn\n\t}\n\ti.err = ctx.Err()\n}", "func (p *plugin) Provision(spec instance.Spec) (*instance.ID, error) {\n\n\tvar properties map[string]interface{}\n\n\tif spec.Properties != nil {\n\t\tif err := spec.Properties.Decode(&properties); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid instance properties: %s\", err)\n\t\t}\n\t}\n\n\tnewVM, err := parseParameters(properties, p)\n\tif err != nil {\n\t\tlog.Error(\"Problems Whilst Parsting\", \"err\", err)\n\t\treturn nil, err\n\t}\n\n\terr = setInternalStructures(p.vC, p.vCenterInternals)\n\tif err != nil {\n\t\tlog.Error(\"Problem whilst setting Internal Config\", \"err\", err)\n\t\treturn nil, err\n\t}\n\n\tif *p.vC.networkName != \"\" {\n\t\tfindNetwork(p.vC, p.vCenterInternals)\n\t}\n\n\t// Use the VMware plugin data in order to provision a new VM server\n\tvmName := instance.ID(fmt.Sprintf(newVM.vmPrefix+\"-%d\", rand.Int63()))\n\tif spec.Tags != nil {\n\t\tlog.Info(\"Provisioning\", \"vm\", string(vmName), \"group\", spec.Tags[group.GroupTag])\n\t} else {\n\t\tlog.Info(\"Provisioning\", \"vm\", string(vmName))\n\t}\n\n\t// Spawn a goroutine to provision in the background\n\tgo func() {\n\t\tnewVM.vmName = string(vmName)\n\t\tvar newInstanceError error\n\t\tif newVM.vmTemplate != \"\" {\n\t\t\tlog.Info(\"Cloning new instance\", \"template\", newVM.vmTemplate)\n\t\t\tnewInstanceError = cloneNewInstance(p, &newVM, spec)\n\t\t} else {\n\t\t\tnewInstanceError = createNewVMInstance(p, &newVM, spec)\n\t\t}\n\t\tif newInstanceError != nil {\n\t\t\tlog.Warn(\"Error creating\", \"vm\", newVM.vmName)\n\t\t\tlog.Error(\"vCenter problem\", \"err\", newInstanceError)\n\t\t}\n\t}()\n\n\tvar newInstance provisioningFSM\n\tnewInstance.instanceName = string(vmName)\n\tnewInstance.timer = time.Now().Add(time.Minute * 10) // Ten Minute timeout\n\n\t// duplicate the tags for the instance\n\tnewInstance.tags = make(map[string]string)\n\tfor k, v := range spec.Tags {\n\t\tnewInstance.tags[k] = v\n\t}\n\tnewInstance.tags[\"infrakit.state\"] = \"Provisioning\"\n\tp.fsm = append(p.fsm, newInstance)\n\n\tlog.Debug(\"FSM\", \"Count\", len(p.fsm))\n\n\treturn &vmName, nil\n}", "func waitUntilServerAvailable(ctx context.Context, c driver.Client) bool {\n\tinstanceUp := make(chan bool)\n\tgo func() {\n\t\tfor {\n\t\t\tverCtx, cancel := context.WithTimeout(ctx, time.Second*5)\n\t\t\tif _, err := c.Version(verCtx); err == nil {\n\t\t\t\tcancel()\n\t\t\t\tinstanceUp <- true\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tcancel()\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t}\n\t\t}\n\t}()\n\tselect {\n\tcase up := <-instanceUp:\n\t\treturn up\n\tcase <-ctx.Done():\n\t\treturn false\n\t}\n}", "func create_virtual_machine(){\n parameters := make([]string, 0)\n parameters = append(parameters, \"apply\")\n parameters = append(parameters, \"--auto-approve\")\n\n execute_command(\"terraform\", parameters)\n}", "func ProvisionWorker(pool *spotcluster.Pool,\n\tinstance *spotcluster.Instance) (*spotcluster.Instance, error) {\n\tif pool == nil {\n\t\treturn nil, errors.New(\"got nil pool object\")\n\t}\n\n\tif instance == nil {\n\t\treturn nil, errors.New(\"got nil instance object\")\n\t}\n\n\tc, err := remotedial.NewSSHClient(provider.DoRootUser, instance.Spec.RemoteAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer c.Close()\n\n\t// Provision worker node\n\terr = func() error {\n\t\tsession, err := c.NewSession()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer session.Close()\n\n\t\tsession.Run(\"curl -sfL \" + k3sInstallLink + \" | K3S_URL=\" +\n\t\t\tpool.Spec.MasterURL + \" K3S_TOKEN=\" + pool.Spec.NodeToken + \" sh -\")\n\t\treturn nil\n\t}()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Read node password\n\treturn func() (*spotcluster.Instance, error) {\n\t\tsession, err := c.NewSession()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdefer session.Close()\n\t\tvar stdout bytes.Buffer\n\t\tvar stderr bytes.Buffer\n\t\tsession.Stdout = &stdout\n\t\tsession.Stderr = &stderr\n\t\tsession.Run(nodePasswordCommand)\n\t\tinstance.Spec.NodePassword = strings.TrimSpace(stdout.String())\n\t\treturn instance, nil\n\t}()\n}", "func (m *Machine) IsBootstrappedWithSSH() bool {\n\tif !m.IsReady() || m.sshKeys == nil {\n\t\treturn false\n\t}\n\n\texecutor := m.getCommandExecutor(m.Address(), m.sshKeys)\n\n\toutput, err := executor.ExecuteCommand(\"cat /run/cluster-api/bootstrap-success.complete\")\n\tif err != nil || output != \"success\" {\n\t\treturn false\n\t}\n\treturn true\n}", "func ready(s *sdk.SDK) {\n\terr := s.Ready()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not send ready message\")\n\t}\n}", "func newSSH(ip net.IPAddr, port uint16, user string, pass string, key string) *inet.SSH {\n\tvar remoteConn = new(inet.SSH)\n\tremoteConn.Make(ip.String(), strconv.FormatUint(uint64(port), 10), user, pass, key)\n\tglog.Info(\"receiver host: \" + ip.String())\n\treturn remoteConn\n}", "func doSetup(port int, clusterConfig *kiln.ClusterConfig) (*server.Server, string, error) {\n\timageCreator, err := kiln.NewImageCreatorFromEnv()\n\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tbaseHost := fmt.Sprintf(\"http://localhost:%d\", port)\n\n\ttestServer := server.NewServer(imageCreator, clusterConfig)\n\n\t//start server in the background\n\tgo func() {\n\t\t//start the server and produce it to the start channel\n\t\ttestServer.Start(port, 10*time.Second)\n\t}()\n\n\t//wait for it to start\n\n\thostBase := fmt.Sprintf(\"%s/organizations\", baseHost)\n\n\tstarted := false\n\n\t//wait for host to start for 10 seconds\n\tfor i := 0; i < 20; i++ {\n\n\t\thost := fmt.Sprintf(\"localhost:%d\", port)\n\n\t\tconn, err := net.Dial(\"tcp\", host)\n\n\t\t//done waiting, continue\n\t\tif err == nil {\n\t\t\tconn.Close()\n\t\t\tstarted = true\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(500 * time.Millisecond)\n\t}\n\n\tif !started {\n\t\treturn nil, \"\", errors.New(\"Server did not start\")\n\t}\n\n\treturn testServer, hostBase, nil\n}", "func (csrv *CreateServerInput) CreateServer(con aws.EstablishConnectionInput) ([]ServerResponse, error) {\n\n\t//get the relative sessions before proceeding further\n\tec2, sesserr := con.EstablishConnection()\n\tif sesserr != nil {\n\t\treturn nil, sesserr\n\t}\n\n\t// I will make a decision which security group to pick\n\tsubInput := GetNetworksInput{SubnetIds: []string{csrv.SubnetId}}\n\tsubResult, suberr := subInput.FindSubnet(con)\n\tif suberr != nil {\n\t\treturn nil, suberr\n\t}\n\n\tif subResult != true {\n\t\treturn nil, fmt.Errorf(\"Could not find the entered SUBNET, please enter valid/existing SUBNET id\")\n\t}\n\n\tinst := new(aws.CreateServerInput)\n\n\tswitch csrv.SecGroupId {\n\tcase \"\":\n\t\tvpcRes, vpcerr := subInput.GetVpcFromSubnet(con)\n\t\tif vpcerr != nil {\n\t\t\treturn nil, vpcerr\n\t\t}\n\n\t\tsecInput := NetworkComponentInput{VpcIds: []string{vpcRes.VpcId}}\n\t\tsecRes, secerr := secInput.GetSecFromVpc(con)\n\t\tif secerr != nil {\n\t\t\treturn nil, nil\n\t\t}\n\t\tinst.SecurityGroups = secRes.SecGroupIds\n\n\tdefault:\n\t\tinst.SecurityGroups = []string{csrv.SecGroupId}\n\t}\n\n\t// I will be the spoc for the instance creation with the userdata passed to me\n\tswitch csrv.UserData {\n\tcase \"\":\n\t\tinst.UserData = b64.StdEncoding.EncodeToString([]byte(\"echo 'nothing'\"))\n\tdefault:\n\t\tinst.UserData = b64.StdEncoding.EncodeToString([]byte(csrv.UserData))\n\t}\n\n\tswitch csrv.MinCount {\n\tcase 0:\n\t\tinst.MinCount = 1\n\tdefault:\n\t\tinst.MinCount = csrv.MinCount\n\t}\n\n\tswitch csrv.MaxCount {\n\tcase 0:\n\t\tinst.MaxCount = 1\n\tdefault:\n\t\tinst.MaxCount = csrv.MaxCount\n\t}\n\n\tinst.ImageId = csrv.ImageId\n\tinst.InstanceType = csrv.InstanceType\n\tinst.KeyName = csrv.KeyName\n\tinst.AssignPubIp = csrv.AssignPubIp\n\tinst.SubnetId = csrv.SubnetId\n\t// support for custom ebs mapping will be rolled out soon\n\tserverCreateResult, err := ec2.CreateInstance(inst)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstanceIds := make([]string, 0)\n\tfor _, instance := range serverCreateResult.Instances {\n\t\tinstanceIds = append(instanceIds, *instance.InstanceId)\n\t}\n\n\t// I will make program wait until instance become running\n\twaitErr := ec2.WaitTillInstanceAvailable(\n\t\t&aws.DescribeComputeInput{\n\t\t\tInstanceIds: instanceIds,\n\t\t},\n\t)\n\tif waitErr != nil {\n\t\treturn nil, waitErr\n\t}\n\n\t// creating tags for the server\n\tfor i, instance := range instanceIds {\n\t\ttags := new(Tag)\n\t\ttags.Resource = instance\n\t\ttags.Name = \"Name\"\n\t\ttags.Value = csrv.InstanceName + \"-\" + strconv.Itoa(i)\n\t\t_, tagErr := tags.CreateTags(con)\n\t\tif tagErr != nil {\n\t\t\treturn nil, tagErr\n\t\t}\n\t}\n\n\t//fetching the details of server\n\tresult, serverr := ec2.DescribeInstance(\n\t\t&aws.DescribeComputeInput{\n\t\t\tInstanceIds: instanceIds,\n\t\t},\n\t)\n\tif serverr != nil {\n\t\treturn nil, serverr\n\t}\n\n\ttype serverResponse struct {\n\t\tname string\n\t\tinstanceId string\n\t\tipaddress string\n\t\tprivatedns string\n\t\tpublicIp string\n\t\tcreatedon string\n\t}\n\n\tresponse := make([]serverResponse, 0)\n\tcreateServerResponse := make([]ServerResponse, 0)\n\n\tif csrv.GetRaw == true {\n\t\tcreateServerResponse = append(createServerResponse, ServerResponse{CreateInstRaw: result, Cloud: \"Amazon\"})\n\t\treturn createServerResponse, nil\n\t}\n\n\t// fetching the instance details which is created in previous process\n\tfor _, reservation := range result.Reservations {\n\t\tfor _, instance := range reservation.Instances {\n\t\t\tif csrv.AssignPubIp == true {\n\t\t\t\tresponse = append(response, serverResponse{name: *instance.Tags[0].Value, instanceId: *instance.InstanceId, ipaddress: *instance.PrivateIpAddress, privatedns: *instance.PrivateDnsName, publicIp: *instance.PublicIpAddress, createdon: (*instance.LaunchTime).String()})\n\t\t\t} else {\n\t\t\t\tresponse = append(response, serverResponse{name: *instance.Tags[0].Value, instanceId: *instance.InstanceId, ipaddress: *instance.PrivateIpAddress, privatedns: *instance.PrivateDnsName, createdon: (*instance.LaunchTime).String()})\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, server := range response {\n\t\tcreateServerResponse = append(createServerResponse, ServerResponse{InstanceName: server.name, InstanceId: server.instanceId, SubnetId: csrv.SubnetId, PrivateIpAddress: server.ipaddress, PublicIpAddress: server.publicIp, PrivateDnsName: server.privatedns, CreatedOn: server.createdon, Cloud: \"Amazon\"})\n\t}\n\n\treturn createServerResponse, nil\n}", "func (d *Driver) Create() error {\n\tb2dutils := mcnutils.NewB2dUtils(d.StorePath)\n\tif err := b2dutils.CopyIsoToMachineDir(d.Boot2DockerURL, d.MachineName); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Generating SSH Keypair...\")\n\tif err := ssh.GenerateSSHKey(d.GetSSHKeyPath()); err != nil {\n\t\treturn err\n\t}\n\n\t// Create context\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tc, err := d.vsphereLogin(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Logout(ctx)\n\n\t// Create a new finder\n\tf := find.NewFinder(c.Client, true)\n\n\tdc, err := f.DatacenterOrDefault(ctx, d.Datacenter)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.SetDatacenter(dc)\n\n\tdss, err := f.DatastoreOrDefault(ctx, d.Datastore)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnetworks := make(map[string]object.NetworkReference)\n\tfor _, netName := range d.Networks {\n\t\tnet, err := f.NetworkOrDefault(ctx, netName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnetworks[netName] = net\n\t}\n\n\tvar hs *object.HostSystem\n\tif d.HostSystem != \"\" {\n\t\tvar err error\n\t\ths, err = f.HostSystemOrDefault(ctx, d.HostSystem)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar rp *object.ResourcePool\n\tif d.Pool != \"\" {\n\t\t// Find specified Resource Pool\n\t\trp, err = f.ResourcePool(ctx, d.Pool)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if d.HostSystem != \"\" {\n\t\t// Pick default Resource Pool for Host System\n\t\trp, err = hs.ResourcePool(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t// Pick the default Resource Pool for the Datacenter.\n\t\trp, err = f.DefaultResourcePool(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tspec := types.VirtualMachineConfigSpec{\n\t\tName: d.MachineName,\n\t\tGuestId: \"otherLinux64Guest\",\n\t\tFiles: &types.VirtualMachineFileInfo{VmPathName: fmt.Sprintf(\"[%s]\", dss.Name())},\n\t\tNumCPUs: int32(d.CPU),\n\t\tMemoryMB: int64(d.Memory),\n\t}\n\n\tscsi, err := object.SCSIControllerTypes().CreateSCSIController(\"pvscsi\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspec.DeviceChange = append(spec.DeviceChange, &types.VirtualDeviceConfigSpec{\n\t\tOperation: types.VirtualDeviceConfigSpecOperationAdd,\n\t\tDevice: scsi,\n\t})\n\n\tlog.Infof(\"Creating VM...\")\n\tfolders, err := dc.Folders(ctx)\n\ttask, err := folders.VmFolder.CreateVM(ctx, spec, rp, hs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinfo, err := task.WaitForResult(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Uploading Boot2docker ISO ...\")\n\tdsurl, err := dss.URL(ctx, dc, fmt.Sprintf(\"%s/%s\", d.MachineName, isoFilename))\n\tif err != nil {\n\t\treturn err\n\t}\n\tp := soap.DefaultUpload\n\tif err = c.Client.UploadFile(d.ISO, dsurl, &p); err != nil {\n\t\treturn err\n\t}\n\n\t// Retrieve the new VM\n\tvm := object.NewVirtualMachine(c.Client, info.Result.(types.ManagedObjectReference))\n\n\tdevices, err := vm.Device(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar add []types.BaseVirtualDevice\n\n\tcontroller, err := devices.FindDiskController(\"scsi\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdisk := devices.CreateDisk(controller, dss.Reference(),\n\t\tdss.Path(fmt.Sprintf(\"%s/%s.vmdk\", d.MachineName, d.MachineName)))\n\n\t// Convert MB to KB\n\tdisk.CapacityInKB = int64(d.DiskSize) * 1024\n\n\tadd = append(add, disk)\n\tide, err := devices.FindIDEController(\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcdrom, err := devices.CreateCdrom(ide)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tadd = append(add, devices.InsertIso(cdrom, dss.Path(fmt.Sprintf(\"%s/%s\", d.MachineName, isoFilename))))\n\n\tfor _, netName := range d.Networks {\n\t\tbacking, err := networks[netName].EthernetCardBackingInfo(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnetdev, err := object.EthernetCardTypes().CreateEthernetCard(\"vmxnet3\", backing)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Infof(\"adding network: %s\", netName)\n\t\tadd = append(add, netdev)\n\t}\n\n\tlog.Infof(\"Reconfiguring VM\")\n\tif vm.AddDevice(ctx, add...); err != nil {\n\t\treturn err\n\t}\n\n\t// Adding some guestinfo data\n\tvar opts []types.BaseOptionValue\n\tfor _, param := range d.CfgParams {\n\t\tv := strings.SplitN(param, \"=\", 2)\n\t\tkey := v[0]\n\t\tvalue := \"\"\n\t\tif len(v) > 1 {\n\t\t\tvalue = v[1]\n\t\t}\n\t\tfmt.Printf(\"Setting %s to %s\\n\", key, value)\n\t\topts = append(opts, &types.OptionValue{\n\t\t\tKey: key,\n\t\t\tValue: value,\n\t\t})\n\t}\n\tif d.CloudInit != \"\" {\n\t\tif _, err := url.ParseRequestURI(d.CloudInit); err == nil {\n\t\t\tlog.Infof(\"setting guestinfo.cloud-init.data.url to %s\\n\", d.CloudInit)\n\t\t\topts = append(opts, &types.OptionValue{\n\t\t\t\tKey: \"guestinfo.cloud-init.config.url\",\n\t\t\t\tValue: d.CloudInit,\n\t\t\t})\n\t\t} else {\n\t\t\tif _, err := os.Stat(d.CloudInit); err == nil {\n\t\t\t\tif value, err := ioutil.ReadFile(d.CloudInit); err == nil {\n\t\t\t\t\tlog.Infof(\"setting guestinfo.cloud-init.data to encoded content of %s\\n\", d.CloudInit)\n\t\t\t\t\tencoded := base64.StdEncoding.EncodeToString(value)\n\t\t\t\t\topts = append(opts, &types.OptionValue{\n\t\t\t\t\t\tKey: \"guestinfo.cloud-init.config.data\",\n\t\t\t\t\t\tValue: encoded,\n\t\t\t\t\t})\n\t\t\t\t\topts = append(opts, &types.OptionValue{\n\t\t\t\t\t\tKey: \"guestinfo.cloud-init.data.encoding\",\n\t\t\t\t\t\tValue: \"base64\",\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttask, err = vm.Reconfigure(ctx, types.VirtualMachineConfigSpec{\n\t\tExtraConfig: opts,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\ttask.Wait(ctx)\n\n\tif err := d.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Provisioning certs and ssh keys...\")\n\t// Generate a tar keys bundle\n\tif err := d.generateKeyBundle(); err != nil {\n\t\treturn err\n\t}\n\n\topman := guest.NewOperationsManager(c.Client, vm.Reference())\n\n\tfileman, err := opman.FileManager(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrc := d.ResolveStorePath(\"userdata.tar\")\n\ts, err := os.Stat(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tauth := AuthFlag{}\n\tflag := FileAttrFlag{}\n\tauth.auth.Username = B2DUser\n\tauth.auth.Password = B2DPass\n\tflag.SetPerms(0, 0, 660)\n\turl, err := fileman.InitiateFileTransferToGuest(ctx, auth.Auth(), \"/home/docker/userdata.tar\", flag.Attr(), s.Size(), true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu, err := c.Client.ParseURL(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = c.Client.UploadFile(src, u, nil); err != nil {\n\t\treturn err\n\t}\n\n\tprocman, err := opman.ProcessManager(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// first, untar - only boot2docker has /var/lib/boot2docker\n\t// TODO: don't hard-code to docker & staff - they are also just b2d\n\tvar env []string\n\tguestspec := types.GuestProgramSpec{\n\t\tProgramPath: \"/usr/bin/sudo\",\n\t\tArguments: \"/usr/bin/sudo /bin/sh -c \\\"tar xvf /home/docker/userdata.tar -C /home/docker > /var/log/userdata.log 2>&1 && chown -R docker:staff /home/docker\\\"\",\n\t\tWorkingDirectory: \"\",\n\t\tEnvVariables: env,\n\t}\n\n\t_, err = procman.StartProgram(ctx, auth.Auth(), &guestspec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// now move to /var/lib/boot2docker if its there\n\tguestspec = types.GuestProgramSpec{\n\t\tProgramPath: \"/usr/bin/sudo\",\n\t\tArguments: \"/bin/mv /home/docker/userdata.tar /var/lib/boot2docker/userdata.tar\",\n\t\tWorkingDirectory: \"\",\n\t\tEnvVariables: env,\n\t}\n\n\t_, err = procman.StartProgram(ctx, auth.Auth(), &guestspec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (repo *LocalRepository) Setup(instance *Instance) error {\n\terr := repo.EnsureDirectoriesExist(instance)\n\tif err != nil {\n\t\trepo.Logger.Error(\"ensure-dirs-exist\", err, lager.Data{\n\t\t\t\"instance_id\": instance.ID,\n\t\t})\n\t\treturn err\n\t}\n\n\terr = repo.Lock(instance)\n\tif err != nil {\n\t\trepo.Logger.Error(\"lock-shared-instance\", err, lager.Data{\n\t\t\t\"instance_id\": instance.ID,\n\t\t})\n\t\treturn err\n\t}\n\n\terr = repo.WriteConfigFile(instance)\n\tif err != nil {\n\t\trepo.Logger.Error(\"write-config-file\", err, lager.Data{\n\t\t\t\"instance_id\": instance.ID,\n\t\t})\n\t\treturn err\n\t}\n\n\trepo.Logger.Info(\"provision-instance\", lager.Data{\n\t\t\"instance_id\": instance.ID,\n\t\t\"plan\": \"shared-vm\",\n\t\t\"message\": \"Successfully provisioned Redis instance\",\n\t})\n\n\treturn nil\n}", "func WaitForInstance(commandID, instanceID *string, wg *sync.WaitGroup) {\n\n\tdefer wg.Done()\n\tvar err error\n\n\terr = ssmSvc.WaitUntilCommandExecuted(&ssm.GetCommandInvocationInput{\n\t\tCommandId: commandID,\n\t\tInstanceId: instanceID,\n\t})\n\n\tif err != nil {\n\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase request.WaiterResourceNotReadyErrorCode:\n\t\t\t\texitCode = 1\n\t\t\tdefault:\n\t\t\t\tfmt.Printf(\"ERROR waiting for instance %s to execute: %s\\n\", *instanceID, err)\n\t\t\t}\n\t\t}\n\t}\n\n}", "func AWSInstall() {\n\t// check if ansible is installed\n\tcommon.DependencyCheck(\"ansible\")\n\tSetClusterName()\n\t// Copy the configuraton files as indicated in the kubespray docs\n\tif _, err := os.Stat(\"./inventory/\" + common.Name + \"/installer\"); err == nil {\n\t\tfmt.Println(\"Configuration folder already exists\")\n\t} else {\n\t\tos.MkdirAll(\"./inventory/\"+common.Name+\"/installer\", 0755)\n\t\tmvHost := exec.Command(\"mv\", \"./inventory/hosts\", \"./inventory/\"+common.Name+\"/hosts\")\n\t\tmvHost.Run()\n\t\tmvHost.Wait()\n\t\tmvShhBastion := exec.Command(\"cp\", \"./kubespray/ssh-bastion.conf\", \"./inventory/\"+common.Name+\"/ssh-bastion.conf\")\n\t\tmvShhBastion.Run()\n\t\tmvShhBastion.Wait()\n\t\t//os.MkdirAll(\"./inventory/\"+common.Name+\"/installer/group_vars\", 0755)\n\t\tcpSample := exec.Command(\"cp\", \"-rfp\", \"./kubespray/inventory/sample/.\", \"./inventory/\"+common.Name+\"/installer/\")\n\t\tcpSample.Run()\n\t\tcpSample.Wait()\n\n\t\tcpKube := exec.Command(\"cp\", \"-rfp\", \"./kubespray/.\", \"./inventory/\"+common.Name+\"/installer/\")\n\t\tcpKube.Run()\n\t\tcpKube.Wait()\n\n\t\tmvInstallerHosts := exec.Command(\"cp\", \"./inventory/\"+common.Name+\"/hosts\", \"./inventory/\"+common.Name+\"/installer/hosts\")\n\t\tmvInstallerHosts.Run()\n\t\tmvInstallerHosts.Wait()\n\t\tmvProvisionerHosts := exec.Command(\"cp\", \"./inventory/\"+common.Name+\"/hosts\", \"./inventory/\"+common.Name+\"/installer/hosts\")\n\t\tmvProvisionerHosts.Run()\n\t\tmvProvisionerHosts.Wait()\n\n\t\t//Start Kubernetes Installation\n\t\t//Enable load balancer api access and copy the kubeconfig file locally\n\t\tloadBalancerName, err := exec.Command(\"sh\", \"-c\", \"grep apiserver_loadbalancer_domain_name= ./inventory/\"+common.Name+\"/installer/hosts | cut -d'=' -f2\").CombinedOutput()\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Problem getting the load balancer domain name\", err)\n\t\t} else {\n\t\t\tvar groupVars *os.File\n\t\t\t//Make a copy of kubeconfig on Ansible host\n\t\t\tif kubesprayVersion == \"develop\" || kubesprayVersion == \"version-0-7\" {\n\t\t\t\t// Set Kube Network Proxy\n\t\t\t\tSetNetworkPlugin(\"./inventory/\" + common.Name + \"/installer/group_vars/k8s-cluster\")\n\t\t\t\tprepareInventoryClusterFile(\"./inventory/\" + common.Name + \"/installer/group_vars/k8s-cluster/k8s-cluster.yml\")\n\t\t\t\tgroupVars = prepareInventoryGroupAllFile(\"./inventory/\" + common.Name + \"/installer/group_vars/all/all.yml\")\n\t\t\t} else {\n\t\t\t\t// Set Kube Network Proxy\n\t\t\t\tSetNetworkPlugin(\"./inventory/\" + common.Name + \"/installer/group_vars\")\n\t\t\t\tprepareInventoryClusterFile(\"./inventory/\" + common.Name + \"/installer/group_vars/k8s-cluster.yml\")\n\t\t\t\tgroupVars = prepareInventoryGroupAllFile(\"./inventory/\" + common.Name + \"/installer/group_vars/all.yml\")\n\t\t\t}\n\t\t\tdefer groupVars.Close()\n\t\t\t// Resolve Load Balancer Domain Name and pick the first IP\n\n\t\t\telbNameRaw, _ := exec.Command(\"sh\", \"-c\", \"grep apiserver_loadbalancer_domain_name= ./inventory/\"+common.Name+\"/installer/hosts | cut -d'=' -f2 | sed 's/\\\"//g'\").CombinedOutput()\n\n\t\t\t// Convert the Domain name to string, strip all spaces so that Lookup does not return errors\n\t\t\telbName := strings.TrimSpace(string(elbNameRaw))\n\t\t\tfmt.Println(elbName)\n\t\t\tnode, err := net.LookupHost(elbName)\n\t\t\tcommon.ErrorCheck(\"Error resolving ELB name: %v\", err)\n\t\t\telbIP := node[0]\n\t\t\tfmt.Println(node)\n\n\t\t\tDomainName := strings.TrimSpace(string(loadBalancerName))\n\t\t\tloadBalancerDomainName := \"apiserver_loadbalancer_domain_name: \" + DomainName\n\n\t\t\tfmt.Fprintf(groupVars, \"#Set cloud provider to AWS\\n\")\n\t\t\tfmt.Fprintf(groupVars, \"cloud_provider: 'aws'\\n\")\n\t\t\tfmt.Fprintf(groupVars, \"#Load Balancer Configuration\\n\")\n\t\t\tfmt.Fprintf(groupVars, \"loadbalancer_apiserver_localhost: false\\n\")\n\t\t\tfmt.Fprintf(groupVars, \"%s\\n\", loadBalancerDomainName)\n\t\t\tfmt.Fprintf(groupVars, \"loadbalancer_apiserver:\\n\")\n\t\t\tfmt.Fprintf(groupVars, \" address: %s\\n\", elbIP)\n\t\t\tfmt.Fprintf(groupVars, \" port: 6443\\n\")\n\t\t}\n\t}\n\n\tsshUser, osLabel := distSelect()\n\tinstaller.RunPlaybook(\"./inventory/\"+common.Name+\"/installer/\", \"cluster.yml\", sshUser, osLabel)\n\n\treturn\n}", "func createEC2InstanceMonitoredResource(awsIdentityDoc *awsIdentityDocument) *EC2Instance {\n\tawsInstance := EC2Instance{\n\t\tAWSAccount: awsIdentityDoc.accountID,\n\t\tInstanceID: awsIdentityDoc.instanceID,\n\t\tRegion: fmt.Sprintf(\"aws:%s\", awsIdentityDoc.region),\n\t}\n\treturn &awsInstance\n}", "func (machine *Machine) Create(e *expect.GExpect, root *Root, server *Server) error {\n\ttasks := []*Task{\n\t\t{\n\t\t\tInputs: []string{\n\t\t\t\t`cd('/')`,\n\t\t\t\t`pwd()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\t`edit:/`,\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`\nif '%s' == 'UnixMachine':\n\tcmo.createUnixMachine('%s')\n\tprint 'XxXsuccessXxX'\nelif '%[1]s' == 'Machine':\n\tcmo.createUnixMachine('%[2]s')\n\tprint 'XxXsuccessXxX'\nelse:\n\tprint 'XxXfailedXxX'\n`, machine.Type, machine.Name),\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\t`XxXsuccessXxX`,\n\t\t\t\t`weblogic.descriptor.BeanAlreadyExistsException: Bean already exists`,\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cd('/Machines/%s/NodeManager/%[1]s')`, machine.Name),\n\t\t\t\t`pwd()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`'edit:/Machines/%s/NodeManager/%[1]s'`, machine.Name),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cmo.setListenAddress('%s')`, machine.Host),\n\t\t\t\t`cmo.getListenAddress()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`'%s'`, machine.Host),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cmo.setListenPort(%s)`, machine.Port),\n\t\t\t\t`cmo.getListenPort()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`%s`, machine.Port),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cmo.setNMType('%s')`, machine.Protocol),\n\t\t\t\t`cmo.getNMType()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(\"'%s'\", machine.Protocol),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cd('/Servers/%s')`, server.Name),\n\t\t\t\t`pwd()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`'edit:/Servers/%s'`, server.Name),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t\t{\n\t\t\tRequireds: []string{``},\n\t\t\tInputs: []string{\n\t\t\t\tfmt.Sprintf(`cmo.setMachine(getMBean('/Machines/%s'))`, machine.Name),\n\t\t\t\t`cmo.getMachine()`,\n\t\t\t},\n\t\t\tExpecteds: []string{\n\t\t\t\tfmt.Sprintf(`\\[MBeanServerInvocationHandler\\]com.bea:Name=%s,Type=%s`, machine.Name, machine.Type),\n\t\t\t},\n\t\t\tTimeout: root.Internal.Timeout,\n\t\t},\n\t}\n\tfor _, task := range tasks {\n\t\tif err := RunTask(task, \"Machine-Create\", e); err != nil {\n\t\t\tserver.ReturnStatus = ret.Failed\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (c *HAProxyController) setToReady() {\n\tlogger.Panic(c.clientAPIClosure(func() error {\n\t\treturn c.Client.FrontendBindEdit(\"healthz\",\n\t\t\tmodels.Bind{\n\t\t\t\tName: \"v4\",\n\t\t\t\tAddress: \"0.0.0.0:1042\",\n\t\t\t})\n\t}))\n\tif !c.osArgs.DisableIPV6 {\n\t\tlogger.Panic(c.clientAPIClosure(func() error {\n\t\t\treturn c.Client.FrontendBindCreate(\"healthz\",\n\t\t\t\tmodels.Bind{\n\t\t\t\t\tName: \"v6\",\n\t\t\t\t\tAddress: \":::1042\",\n\t\t\t\t\tV4v6: true,\n\t\t\t\t})\n\t\t}))\n\t}\n\tlogger.Debugf(\"healthz frontend exposed for readiness probe\")\n\tcm := c.Store.ConfigMaps.Main\n\tif cm.Name != \"\" && !cm.Loaded {\n\t\tlogger.Warningf(\"Main configmap '%s/%s' not found\", cm.Namespace, cm.Name)\n\t}\n\tc.ready = true\n}", "func (c *SFTPServer) Run() error {\n\tif _, err := os.Stat(c.PrivateKeyPath()); os.IsNotExist(err) {\n\t\tif err := c.generateED25519PrivateKey(); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if err != nil {\n\t\treturn errors.Wrap(err, \"sftp: could not stat private key file\")\n\t}\n\tpb, err := os.ReadFile(c.PrivateKeyPath())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"sftp: could not read private key file\")\n\t}\n\tprivate, err := ssh.ParsePrivateKey(pb)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconf := &ssh.ServerConfig{\n\t\tConfig: ssh.Config{\n\t\t\tKeyExchanges: []string{\n\t\t\t\t\"curve25519-sha256\", \"curve25519-sha256@libssh.org\",\n\t\t\t\t\"ecdh-sha2-nistp256\", \"ecdh-sha2-nistp384\", \"ecdh-sha2-nistp521\",\n\t\t\t\t\"diffie-hellman-group14-sha256\",\n\t\t\t},\n\t\t\tCiphers: []string{\n\t\t\t\t\"aes128-gcm@openssh.com\",\n\t\t\t\t\"chacha20-poly1305@openssh.com\",\n\t\t\t\t\"aes128-ctr\", \"aes192-ctr\", \"aes256-ctr\",\n\t\t\t},\n\t\t\tMACs: []string{\n\t\t\t\t\"hmac-sha2-256-etm@openssh.com\", \"hmac-sha2-256\",\n\t\t\t},\n\t\t},\n\t\tNoClientAuth: false,\n\t\tMaxAuthTries: 6,\n\t\tPasswordCallback: func(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {\n\t\t\treturn c.makeCredentialsRequest(conn, remote.SftpAuthPassword, string(password))\n\t\t},\n\t\tPublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {\n\t\t\treturn c.makeCredentialsRequest(conn, remote.SftpAuthPublicKey, string(ssh.MarshalAuthorizedKey(key)))\n\t\t},\n\t}\n\tconf.AddHostKey(private)\n\n\tlistener, err := net.Listen(\"tcp\", c.Listen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpublic := string(ssh.MarshalAuthorizedKey(private.PublicKey()))\n\tlog.WithField(\"listen\", c.Listen).WithField(\"public_key\", strings.Trim(public, \"\\n\")).Info(\"sftp server listening for connections\")\n\n\tfor {\n\t\tif conn, _ := listener.Accept(); conn != nil {\n\t\t\tgo func(conn net.Conn) {\n\t\t\t\tdefer conn.Close()\n\t\t\t\tif err := c.AcceptInbound(conn, conf); err != nil {\n\t\t\t\t\tlog.WithField(\"error\", err).Error(\"sftp: failed to accept inbound connection\")\n\t\t\t\t}\n\t\t\t}(conn)\n\t\t}\n\t}\n}", "func (s *inMemSpannerServer) ready() {\n\ts.mu.Lock()\n\tfreezed := s.freezed\n\ts.mu.Unlock()\n\t// check if server should be freezed\n\t<-freezed\n}", "func DoServer(\n\tversion string,\n\tkeyFile string,\n\taddr string,\n\ttimeout time.Duration,\n\ttaskingDir string,\n\toutputDir string,\n) {\n\t/* Get the server hostkey */\n\tkey, err := getHostKey(keyFile)\n\tif nil != err {\n\t\tlog.Fatalf(\"Error reading key from %s: %v\", keyFile, err)\n\t}\n\n\t/* Make the server config */\n\tconf := &ssh.ServerConfig{\n\t\tKeyboardInteractiveCallback: func(\n\t\t\tconn ssh.ConnMetadata,\n\t\t\tclient ssh.KeyboardInteractiveChallenge,\n\t\t) (*ssh.Permissions, error) {\n\t\t\treturn handleClientAuth(\n\t\t\t\tconn,\n\t\t\t\tclient,\n\t\t\t\ttaskingDir,\n\t\t\t\toutputDir,\n\t\t\t)\n\t\t},\n\t\tServerVersion: version,\n\t}\n\tconf.AddHostKey(key)\n\n\t/* Listen for clients */\n\tl, err := net.Listen(\"tcp\", addr)\n\tif nil != err {\n\t\tlog.Fatalf(\"Unable to listen for clients on %v: %v\", addr, err)\n\t}\n\tlog.Printf(\n\t\t\"Listening for SSH clients on %v with fingerprint %v\",\n\t\tl.Addr(),\n\t\tssh.FingerprintSHA256(key.PublicKey()),\n\t)\n\n\t/* Handle clients */\n\tfor {\n\t\t/* Get a client */\n\t\tc, err := l.Accept()\n\t\tif nil != err {\n\t\t\tlog.Fatalf(\"Error accepting new clients: %v\", err)\n\t\t\t/* TODO: Check for too many clients */\n\t\t}\n\t\t/* Upgrade to SSH and wait for tasking to finish */\n\t\tgo handleClientConn(c, conf, timeout)\n\t}\n}", "func scpAction(c *cli.Context) {\n\texec := PrepareExecutor(c)\n\tsrc := c.String(\"src\")\n\tuseScp := func() {\n\t\texec.SetTransfer(src, c.String(\"dst\"))\n\t\texec.SetTransferHook(c.String(\"before\"), c.String(\"after\"))\n\t}\n\tuseP2P := func() {\n\t\tp2pMgr := p2p.GetMgr()\n\t\tp2pMgr.SetTransfer(src, c.String(\"dst\"))\n\t\terr := p2pMgr.Mkseed()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(2)\n\t\t}\n\t\tif p2pMgr.NeedTransferFile() {\n\t\t\tremoteTmp := config.GetString(\"remote.tmpdir\")\n\t\t\texec.SetTransfer(p2pMgr.TransferFilePath(), remoteTmp)\n\t\t}\n\t\tcmd := util.WrapCmd(p2pMgr.ClientCmd(), c.String(\"before\"), c.String(\"after\"))\n\t\texec.Parameter.Cmd = cmd\n\t\texec.Parameter.Concurrency = -1\n\t}\n\tif !p2p.Available() {\n\t\tuseScp()\n\t} else if util.IsDir(src) {\n\t\tuseP2P()\n\t} else {\n\t\tstat, err := os.Lstat(src)\n\t\tif nil != err {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(2)\n\t\t}\n\t\tsize := stat.Size()\n\t\tsizeInMB := size / 1024 / 1024\n\t\ttransferTotal := sizeInMB * int64(exec.HostCount())\n\t\t// If transferTotal is less than 1 MB * 10 machine, use scp.\n\t\tif 10 > transferTotal {\n\t\t\tuseScp()\n\t\t} else {\n\t\t\tuseP2P()\n\t\t}\n\t}\n\tfailed, err := exec.Run()\n\tif nil != err {\n\t\tfmt.Println(err)\n\t\tos.Exit(2)\n\t}\n\tos.Exit(failed)\n}", "func SetupSSHKey(source ConcourseSource) error {\n\thomeDir := os.Getenv(\"HOME\")\n\n\terr := ioutil.WriteFile(\"/tmp/git-private-key\", []byte(source.PrivateKey), os.FileMode(0600))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsshAgent, _ := exec.Command(\"ssh-agent\").Output()\n\n\tfor key, value := range retrieveEnvVarsFromAgent(string(sshAgent)) {\n\t\tos.Setenv(key, value)\n\t}\n\n\terr = exec.Command(\"ssh-add\", \"/tmp/git-private-key\").Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.MkdirAll(homeDir+\"/.ssh\", os.FileMode(0600))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(homeDir+\"/.ssh/config\", []byte(\"StrictHostKeyChecking no\"), os.FileMode(0600))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func newSshNativeTask(host string, cmd string, opt Options) func() (interface{}, error) {\n\tstate := &sshNativeTask{\n\t\tHost: host,\n\t\tCmd: cmd,\n\t\tOpts: opt,\n\t}\n\treturn state.run\n}", "func (s *server) Start() error {\n\t// Start C2 server\n\tdbType := \"E4C2_DB_TYPE=sqlite3\"\n\tdbName := fmt.Sprintf(\"E4C2_DB_FILE=%s\", s.dbPath)\n\tbroker := fmt.Sprintf(\"E4C2_MQTT_BROKER=tcp://%s\", s.mqttEndpoint)\n\tesEnable := \"E4C2_ES_ENABLE=false\"\n\tpassphrase := \"E4C2_DB_ENCRYPTION_PASSPHRASE=very_secure_testpass\"\n\tcryptoMode := \"E4C2_CRYPTO_MODE=symkey\"\n\n\tfmt.Fprintf(os.Stderr, \"Database set to %s\\n\", dbName)\n\tfmt.Fprintf(os.Stderr, \"Broker set to %s\\n\", broker)\n\n\tenv := []string{\n\t\tdbType,\n\t\tdbName,\n\t\tbroker,\n\t\tesEnable,\n\t\tpassphrase,\n\t\tcryptoMode,\n\t}\n\n\ts.cmd = exec.Command(\"bin/c2\")\n\ts.cmd.Env = append(os.Environ(), env...)\n\n\ts.cmd.Stdout = os.Stderr\n\ts.cmd.Stderr = os.Stderr\n\n\tif err := s.cmd.Start(); err != nil {\n\t\treturn fmt.Errorf(\"failed to start server: %v\", err)\n\t}\n\n\t// Wait for server to be ready\n\tretryTimeout := 100 * time.Millisecond\n\tmaxRetryCount := 100\n\tretryCount := 0\n\n\tticker := time.NewTicker(retryTimeout)\n\tdefer ticker.Stop()\n\n\tfor range ticker.C {\n\t\tif CheckC2Online(\"127.0.0.1\", 5555, 8888) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif retryCount > maxRetryCount {\n\t\t\ts.Stop()\n\t\t\treturn errors.New(\"timeout while waiting for server to start\")\n\t\t}\n\n\t\tretryCount++\n\t}\n\n\treturn nil\n}", "func AWSScale() {\n\tSetClusterName()\n\t// Scale the AWS infrastructure\n\tfmt.Printf(\"\\t\\t===============Starting AWS Scaling====================\\n\\n\")\n\tsshUser, osLabel := distSelect()\n\tprepareConfigFiles(osLabel)\n\tprovisioner.ExecuteTerraform(\"apply\", \"./inventory/\"+common.Name+\"/provisioner/\")\n\tmvHost := exec.Command(\"mv\", \"./inventory/hosts\", \"./inventory/\"+common.Name+\"/provisioner/hosts\")\n\tmvHost.Run()\n\tmvHost.Wait()\n\t// waiting for Infrastructure\n\ttime.Sleep(30)\n\t// Scale the Kubernetes cluster\n\tfmt.Printf(\"\\n\\n\\t\\t===============Starting Kubernetes Scaling====================\\n\\n\")\n\t_, err := os.Stat(\"./inventory/\" + common.Name + \"/provisioner/hosts\")\n\tcommon.ErrorCheck(\"No host file found.\", err)\n\tcpHost := exec.Command(\"cp\", \"./inventory/\"+common.Name+\"/provisioner/hosts\", \"./inventory/\"+common.Name+\"/installer/hosts\")\n\tcpHost.Run()\n\tcpHost.Wait()\n\tinstaller.RunPlaybook(\"./inventory/\"+common.Name+\"/installer/\", \"scale.yml\", sshUser, osLabel)\n\n\treturn\n}", "func (c *EC2) createAWSEC2Instance(input *RunInstancesInput) (r aws.Referencer, attr aws.Attrabuter, err error) {\n\n\truninstancesrequest := input\n\treservation, err := RunInstances(runinstancesrequest)\n\tif err == nil {\n\t\tdescribeinstancesrequest := &DescribeInstancesInput{}\n\t\tif err := awsutil.CopyValue(describeinstancesrequest, \"InstanceIds\", reservation, \"Instances[].InstanceId\"); err != nil {\n\t\t\treturn reservation, reservation, err\n\t\t}\n\t\tif err := WaitUntilInstanceRunning(describeinstancesrequest); err != nil {\n\t\t\treturn reservation, reservation, err\n\t\t}\n\n\t} else {\n\t\treturn nil, nil, err\n\t}\n\tstartinstancesrequest := &StartInstancesInput{}\n\tif err := awsutil.CopyValue(startinstancesrequest, \"InstanceIds\", reservation, \"Instances[].InstanceId\"); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tstartinstancesresult, err := StartInstances(startinstancesrequest)\n\tif err == nil {\n\t\tdescribeinstancesrequest := &DescribeInstancesInput{}\n\t\tif err := awsutil.CopyValue(describeinstancesrequest, \"InstanceIds\", reservation, \"Instances[].InstanceId\"); err != nil {\n\t\t\treturn reservation, reservation, err\n\t\t}\n\t\tif err := WaitUntilInstanceRunning(describeinstancesrequest); err != nil {\n\t\t\treturn reservation, reservation, err\n\t\t}\n\n\t} else {\n\t\treturn nil, nil, err\n\t}\n\treturn reservation, reservation, nil\n}", "func configSSH(l *logrus.Logger, ssh *sshd.SSHServer, c *config.C) (func(), error) {\n\t//TODO conntrack list\n\t//TODO print firewall rules or hash?\n\n\tlisten := c.GetString(\"sshd.listen\", \"\")\n\tif listen == \"\" {\n\t\treturn nil, fmt.Errorf(\"sshd.listen must be provided\")\n\t}\n\n\t_, port, err := net.SplitHostPort(listen)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid sshd.listen address: %s\", err)\n\t}\n\tif port == \"22\" {\n\t\treturn nil, fmt.Errorf(\"sshd.listen can not use port 22\")\n\t}\n\n\t//TODO: no good way to reload this right now\n\thostKeyFile := c.GetString(\"sshd.host_key\", \"\")\n\tif hostKeyFile == \"\" {\n\t\treturn nil, fmt.Errorf(\"sshd.host_key must be provided\")\n\t}\n\n\thostKeyBytes, err := ioutil.ReadFile(hostKeyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while loading sshd.host_key file: %s\", err)\n\t}\n\n\terr = ssh.SetHostKey(hostKeyBytes)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while adding sshd.host_key: %s\", err)\n\t}\n\n\trawKeys := c.Get(\"sshd.authorized_users\")\n\tkeys, ok := rawKeys.([]interface{})\n\tif ok {\n\t\tfor _, rk := range keys {\n\t\t\tkDef, ok := rk.(map[interface{}]interface{})\n\t\t\tif !ok {\n\t\t\t\tl.WithField(\"sshKeyConfig\", rk).Warn(\"Authorized user had an error, ignoring\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tuser, ok := kDef[\"user\"].(string)\n\t\t\tif !ok {\n\t\t\t\tl.WithField(\"sshKeyConfig\", rk).Warn(\"Authorized user is missing the user field\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tk := kDef[\"keys\"]\n\t\t\tswitch v := k.(type) {\n\t\t\tcase string:\n\t\t\t\terr := ssh.AddAuthorizedKey(user, v)\n\t\t\t\tif err != nil {\n\t\t\t\t\tl.WithError(err).WithField(\"sshKeyConfig\", rk).WithField(\"sshKey\", v).Warn(\"Failed to authorize key\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\tcase []interface{}:\n\t\t\t\tfor _, subK := range v {\n\t\t\t\t\tsk, ok := subK.(string)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tl.WithField(\"sshKeyConfig\", rk).WithField(\"sshKey\", subK).Warn(\"Did not understand ssh key\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\terr := ssh.AddAuthorizedKey(user, sk)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tl.WithError(err).WithField(\"sshKeyConfig\", sk).Warn(\"Failed to authorize key\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tl.WithField(\"sshKeyConfig\", rk).Warn(\"Authorized user is missing the keys field or was not understood\")\n\t\t\t}\n\t\t}\n\t} else {\n\t\tl.Info(\"no ssh users to authorize\")\n\t}\n\n\tvar runner func()\n\tif c.GetBool(\"sshd.enabled\", false) {\n\t\tssh.Stop()\n\t\trunner = func() {\n\t\t\tif err := ssh.Run(listen); err != nil {\n\t\t\t\tl.WithField(\"err\", err).Warn(\"Failed to run the SSH server\")\n\t\t\t}\n\t\t}\n\t} else {\n\t\tssh.Stop()\n\t}\n\n\treturn runner, nil\n}", "func main() {\n\t// parse arguments\n\tvmConfigPathPtr := flag.String(\"v\", \"None\", \"required: path to vm config json file\")\n\tdbConfigPathPtr := flag.String(\"d\", \"None\", \"optional: path to db config file\")\n\tflag.Parse()\n\n\t// download json data\n\tbody, err := ioutil.ReadFile(*vmConfigPathPtr)\n\tec2utils.HandleError(err)\n\n\t// parse the json into structs\n\tvar config ec2utils.CreateVMInput\n\tjson.Unmarshal([]byte(body), &config)\n\n\t// region will be user's own aws config default region\n\tsess, err := session.NewSession()\n\tec2utils.HandleError(err)\n\n\tec2utils.CreateEC2Instance(sess, config, *dbConfigPathPtr)\n}", "func writeEnv(out io.Writer) error {\n\tmetaSvc := ec2metadata.New(session.New(), &aws.Config{\n\t\tRegion: aws.String(\"us-east-1\"),\n\t})\n\tif !metaSvc.Available() {\n\t\treturn errors.New(\"not running on an ec2 instance\")\n\t}\n\n\tidentity, err := metaSvc.GetInstanceIdentityDocument()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to retrieve instance identity\")\n\t}\n\n\tec2Svc := ec2.New(session.New(), &aws.Config{\n\t\tRegion: aws.String(identity.Region),\n\t})\n\tres, err := ec2Svc.DescribeInstances(&ec2.DescribeInstancesInput{\n\t\tInstanceIds: aws.StringSlice([]string{identity.InstanceID}),\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to describe instance \")\n\t}\n\tif len(res.Reservations) == 0 {\n\t\treturn errors.Errorf(\"reservations for instance %s not found\", identity.InstanceID)\n\t}\n\tif len(res.Reservations[0].Instances) == 0 {\n\t\treturn errors.Errorf(\"instance %s not found\", identity.InstanceID)\n\t}\n\tinstance := res.Reservations[0].Instances[0]\n\n\twr := func(name string, value interface{}) {\n\t\tfmt.Fprintf(out, \"%s=%s\\n\", name, value)\n\t}\n\n\twr(\"EC2_AVAILABILITY_ZONE\", identity.AvailabilityZone)\n\twr(\"EC2_AVAILABILITY_ZONE_LETTER\", zoneLetter(identity.AvailabilityZone))\n\twr(\"EC2_REGION\", identity.Region)\n\twr(\"EC2_REGION_SHORT\", shortRegion(identity.Region))\n\twr(\"EC2_INSTANCE_ID\", identity.InstanceID)\n\twr(\"EC2_INSTANCE_TYPE\", identity.InstanceType)\n\twr(\"EC2_ACCOUNT_ID\", identity.AccountID)\n\twr(\"EC2_IMAGE_ID\", identity.ImageID)\n\n\twr(\"EC2_PRIVATE_DNS\", aws.StringValue(instance.PrivateDnsName))\n\twr(\"EC2_PRIVATE_IP\", aws.StringValue(instance.PrivateIpAddress))\n\twr(\"EC2_PUBLIC_DNS\", aws.StringValue(instance.PublicDnsName))\n\twr(\"EC2_PUBLIC_IP\", aws.StringValue(instance.PublicIpAddress))\n\twr(\"EC2_SUBNET_ID\", aws.StringValue(instance.SubnetId))\n\twr(\"EC2_VPC_ID\", aws.StringValue(instance.VpcId))\n\twr(\"EC2_KEYNAME\", aws.StringValue(instance.KeyName))\n\twr(\"EC2_NAMESERVER\", getNameserver(metaSvc))\n\n\tfor _, tag := range instance.Tags {\n\t\tname := fmt.Sprintf(\"EC2_TAG_%s\", tagEnvName(aws.StringValue(tag.Key)))\n\t\twr(name, aws.StringValue(tag.Value))\n\t}\n\treturn nil\n}", "func ListEC2(environment, profile string, cfg *config.Config) ([]EC2Result, error) {\n\tif r, ok := resultCache[environment]; ok {\n\t\treturn r, nil\n\t}\n\tresultCache[environment] = make([]EC2Result, 0)\n\n\tec2Svc := getEC2Service(environment, profile)\n\n\tvar result *ec2.DescribeInstancesOutput\n\tvar err error\n\texpectEnvTag := environment\n\tif cfg.IsCI(environment) {\n\t\texpectEnvTag = \"ci\"\n\t}\n\trequest := &ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: aws.String(\"tag:Environment\"),\n\t\t\t\tValues: []*string{aws.String(expectEnvTag)},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: aws.String(\"instance-state-name\"),\n\t\t\t\tValues: []*string{aws.String(ec2.InstanceStateNameRunning)},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor {\n\t\tif result != nil {\n\t\t\tif result.NextToken == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\trequest.SetNextToken(*result.NextToken)\n\t\t}\n\n\t\tif result, err = ec2Svc.DescribeInstances(request); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, r := range result.Reservations {\n\t\t\tfor _, i := range r.Instances {\n\t\t\t\tvar name, ansibleGroup string\n\t\t\t\tfor _, tag := range i.Tags {\n\t\t\t\t\tif tag.Key != nil && *tag.Key == \"Name\" && tag.Value != nil {\n\t\t\t\t\t\tname = *tag.Value\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if tag.Key != nil && *tag.Key == \"AnsibleGroup\" && tag.Value != nil {\n\t\t\t\t\t\tansibleGroup = *tag.Value\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar ipAddr string\n\t\t\t\tif cfg.IsCI(environment) && cfg.IsAWSA(environment) {\n\t\t\t\t\tif len(i.NetworkInterfaces) > 0 &&\n\t\t\t\t\t\ti.NetworkInterfaces[0].Association != nil &&\n\t\t\t\t\t\tlen(*i.NetworkInterfaces[0].Association.PublicIp) > 0 &&\n\t\t\t\t\t\ti.NetworkInterfaces[0].Association.PublicIp != nil {\n\t\t\t\t\t\tipAddr = *i.NetworkInterfaces[0].Association.PublicIp\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif len(i.NetworkInterfaces) > 0 &&\n\t\t\t\t\t\tlen(i.NetworkInterfaces[0].PrivateIpAddresses) > 0 &&\n\t\t\t\t\t\ti.NetworkInterfaces[0].PrivateIpAddresses[0].PrivateIpAddress != nil {\n\t\t\t\t\t\tipAddr = *i.NetworkInterfaces[0].PrivateIpAddresses[0].PrivateIpAddress\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresultCache[environment] = append(resultCache[environment], EC2Result{\n\t\t\t\t\tName: name,\n\t\t\t\t\tIPAddress: ipAddr,\n\t\t\t\t\tEnvironment: environment,\n\t\t\t\t\tAnsibleGroups: strings.Split(ansibleGroup, \",\"),\n\t\t\t\t\tGroupAKA: []string{},\n\t\t\t\t\tInstanceId: *i.InstanceId,\n\t\t\t\t\tLaunchTime: i.LaunchTime,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tsort.Slice(resultCache[environment], func(i, j int) bool {\n\t\tif resultCache[environment][i].Name == resultCache[environment][j].Name {\n\t\t\treturn resultCache[environment][i].LaunchTime.Before(*resultCache[environment][j].LaunchTime)\n\t\t}\n\t\treturn resultCache[environment][i].Name < resultCache[environment][j].Name\n\t})\n\n\t// add (e.g.) \"publishing 2\" to GroupAKA field, now that the list is sorted\n\tcountGroup := make(map[string]int)\n\tfor i := range resultCache[environment] {\n\t\tfor _, grp := range resultCache[environment][i].AnsibleGroups {\n\t\t\tcountGroup[grp]++\n\t\t\tresultCache[environment][i].GroupAKA = append(resultCache[environment][i].GroupAKA, fmt.Sprintf(\"%s %d\", grp, countGroup[grp]))\n\t\t}\n\t}\n\n\treturn resultCache[environment], nil\n}", "func createVsphereConfigSecret(namespace string, cfg e2eTestConfig, sshClientConfig *ssh.ClientConfig,\n\tallMasterIps []string) error {\n\n\tvar conf string\n\tvar controlIp string\n\n\tfor _, masterIp := range allMasterIps {\n\t\treadCsiYaml := \"ls -l vsphere-csi-driver.yaml\"\n\t\tframework.Logf(\"list csi driver yaml: %s \", readCsiYaml)\n\t\tgrepCsiNs, err := sshExec(sshClientConfig, masterIp, readCsiYaml)\n\t\tif err != nil && grepCsiNs.Code != 0 {\n\t\t\tif strings.Contains(err.Error(), \"No such file or directory\") {\n\t\t\t\tframework.Logf(\"Retry other master nodes\")\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred(), \"couldn't execute command on host: %v , error: %s\",\n\t\t\t\t\tmasterIp, err)\n\t\t\t}\n\t\t}\n\t\tif err == nil {\n\t\t\tcontrolIp = masterIp\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvCenterHostnames := strings.Split(cfg.Global.VCenterHostname, \",\")\n\tusers := strings.Split(cfg.Global.User, \",\")\n\tpasswords := strings.Split(cfg.Global.Password, \",\")\n\tdataCenters := strings.Split(cfg.Global.Datacenters, \",\")\n\tports := strings.Split(cfg.Global.VCenterPort, \",\")\n\n\tconf = fmt.Sprintf(\"tee csi-vsphere.conf >/dev/null <<EOF\\n[Global]\\ncluster-distribution = \\\"%s\\\"\\n\"+\n\t\t\"csi-fetch-preferred-datastores-intervalinmin = %d\\n\"+\n\t\t\"query-limit = %d\\nlist-volume-threshold = %d\\n\\n\",\n\t\tcfg.Global.ClusterDistribution, cfg.Global.CSIFetchPreferredDatastoresIntervalInMin, cfg.Global.QueryLimit,\n\t\tcfg.Global.ListVolumeThreshold)\n\tfor i := 0; i < len(vCenterHostnames); i++ {\n\t\tconf += fmt.Sprintf(\"[VirtualCenter \\\"%s\\\"]\\ninsecure-flag = \\\"%t\\\"\\nuser = \\\"%s\\\"\\npassword = \\\"%s\\\"\\n\"+\n\t\t\t\"port = \\\"%s\\\"\\ndatacenters = \\\"%s\\\"\\n\\n\",\n\t\t\tvCenterHostnames[i], cfg.Global.InsecureFlag, users[i], passwords[i], ports[i], dataCenters[i])\n\t}\n\n\tconf += fmt.Sprintf(\"[Snapshot]\\nglobal-max-snapshots-per-block-volume = %d\\n\\n\",\n\t\tcfg.Snapshot.GlobalMaxSnapshotsPerBlockVolume)\n\tconf += fmt.Sprintf(\"[Labels]\\ntopology-categories = \\\"%s\\\"\\n\", cfg.Labels.TopologyCategories)\n\tconf += \"\\nEOF\"\n\n\tframework.Logf(conf)\n\n\tresult, err := sshExec(sshClientConfig, controlIp, conf)\n\tif err != nil && result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\", conf, controlIp, err)\n\t}\n\tapplyConf := \"kubectl create secret generic vsphere-config-secret --from-file=csi-vsphere.conf \" +\n\t\t\"-n \" + namespace\n\tframework.Logf(applyConf)\n\tresult, err = sshExec(sshClientConfig, controlIp, applyConf)\n\tif err != nil && result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tapplyConf, controlIp, err)\n\t}\n\treturn nil\n}", "func MakeImage(svc ec2iface.EC2API, description, instanceID, name *string) (*ec2.CreateImageOutput, error) {\n // snippet-start:[ec2.go.create_image.call]\n opts := &ec2.CreateImageInput{\n Description: description,\n InstanceId: instanceID,\n Name: name,\n BlockDeviceMappings: []*ec2.BlockDeviceMapping{\n {\n DeviceName: aws.String(\"/dev/sda1\"),\n NoDevice: aws.String(\"\"),\n },\n {\n DeviceName: aws.String(\"/dev/sdb\"),\n NoDevice: aws.String(\"\"),\n },\n {\n DeviceName: aws.String(\"/dev/sdc\"),\n NoDevice: aws.String(\"\"),\n },\n },\n }\n resp, err := svc.CreateImage(opts)\n // snippet-end:[ec2.go.create_image.call]\n if err != nil {\n return nil, err\n }\n\n return resp, nil\n}", "func (sdk *SDK) createNode(req *CreateInstanceRequest) (*cloudsvr.CloudNode, error) {\n\tvar err error\n\n\t// create ecs firstly\n\tecsID, err := sdk.NewEcs(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs create failed: %v\", err)\n\t}\n\tlog.Printf(\"aliyun ecs %s created at %s\", ecsID, req.RegionID)\n\n\t// if create succeed, but other operations failed, clean up the newly created ecs instance to prevent garbage left\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"aliyun cloud node creation failed, clean up the newly created ecs instance %s. [%v]\", ecsID, err)\n\t\t\tsdk.RemoveNode(&cloudsvr.CloudNode{ID: ecsID, RegionOrZoneID: req.RegionID})\n\t\t}\n\t}()\n\n\t// now ecs is stopped, we assign an public ip to it\n\tip, err := sdk.AssignEcsPublicIP(ecsID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs %s assign public ip failed: %v\", ecsID, err)\n\t}\n\tlog.Printf(\"aliyun ecs %s assgined public ipaddress %s\", ecsID, ip)\n\n\t// start ecs\n\tif err = sdk.StartEcs(ecsID); err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs %s start failed: %v\", ecsID, err)\n\t}\n\tlog.Printf(\"aliyun ecs %s starting\", ecsID)\n\n\t// wait ecs to be running\n\tif err = sdk.WaitEcs(req.RegionID, ecsID, \"Running\", time.Second*300); err != nil {\n\t\treturn nil, fmt.Errorf(\"aliyun ecs %s waitting to be running failed: %v\", ecsID, err)\n\t}\n\tlog.Printf(\"aliyun ecs %s is Running now\", ecsID)\n\n\treturn &cloudsvr.CloudNode{\n\t\tID: ecsID,\n\t\tRegionOrZoneID: req.RegionID,\n\t\tInstanceType: req.InstanceType,\n\t\tCloudSvrType: sdk.Type(),\n\t\tIPAddr: ip,\n\t\tPort: \"22\",\n\t\tUser: \"root\",\n\t\tPassword: req.Password,\n\t}, nil\n}", "func InitSshNodes(nodes []*Node) error {\n\t// 1\n\tInitNodesBaseOnGlobal(nodes, MatchSshConfig)\n\t// 2\n\tif err := InitConfig(nodes); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Prepare() error {\n\n\t// log.Println(\"Preparing work...\")\n\n\t// commands := [][]string{\n\t// \t[]string{\"yum\", \"update\", \"-y\"},\n\t// \t[]string{\"yum\", \"install\", \"-y\", \"docker\"},\n\t// \t[]string{\"service\", \"docker\", \"start\"},\n\t// \t[]string{\"docker\", \"pull\", \"tnolet/scraper:0.1.0\"},\n\t// }\n\n\t// for _, command := range commands {\n\t// \tout, err := exec.Command(command).Output()\n\n\t// \tif err != nil {\n\t// \t\tlog.Printf(\"Prepare command unsuccessful: %v, %v\", err.Error(), out)\n\t// \t\treturn err\n\t// \t}\n\n\t// \tlog.Printf(\"Succesfully executed preparation: %v\", out)\n\t// }\n\treturn nil\n\n}", "func SpawnInstance(user *twitter.User, twitterClient *twitter.Client, appConfig *AppConfig, tweetRefID *int64) error {\n\tvar count int\n\tif err := CountActiveSession(&count); err != nil {\n\t\treturn err\n\t}\n\n\tif count > appConfig.Scw.Limit {\n\t\treturn errors.New(\"Server limit reached\")\n\t}\n\n\ts, _ := scw.NewScalewayAPI(appConfig.Scw.AccessKey, appConfig.Scw.SecretKey, \"SCW-Twt\", appConfig.Scw.Region)\n\tpassword := NewPassword(6)\n\tserver := scw.ScalewayServerDefinition{\n\t\tName: user.ScreenName,\n\t\tImage: &appConfig.Scw.Image,\n\t\tOrganization: appConfig.Scw.AccessKey,\n\t\tCommercialType: appConfig.Scw.InstanceType,\n\t\tTags: []string{password},\n\t}\n\n\tid, err := s.PostServer(server)\n\n\tsession := &Session{\n\t\tUserID: user.ID,\n\t\tScreenName: user.ScreenName,\n\t\tServerID: id,\n\t\tState: \"starting\",\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := CreateSession(session); err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"twitter ID\": user.ID,\n\t\t\"server ID\": id,\n\t}).Info(\"Server created\")\n\tTweet(\n\t\ttwitterClient,\n\t\tfmt.Sprintf(\"@%s %s\", user.ScreenName, appConfig.Messages.StartingInProgress),\n\t\ttweetRefID,\n\t)\n\n\tif err := scw.StartServer(s, id, true); err != nil {\n\t\treturn err\n\n\t}\n\tlog.WithFields(logrus.Fields{\n\t\t\"twitter ID\": user.ID,\n\t\t\"server ID\": id,\n\t}).Info(\"Server started\")\n\n\tserver_info, _ := s.GetServer(id)\n\n\tnow := time.Now()\n\tsession.SessionEndAt = now.Add(time.Duration(appConfig.Scw.SessionTime * 60000000000))\n\tsession.State = \"running\"\n\n\tif err := UpdateSession(session); err != nil {\n\t\treturn err\n\t}\n\n\tTweet(\n\t\ttwitterClient,\n\t\tfmt.Sprintf(\"@%s %s\", user.ScreenName, appConfig.Messages.ServerReady),\n\t\ttweetRefID,\n\t)\n\n\tDM(\n\t\ttwitterClient,\n\t\tuser.ID,\n\t\tuser.ScreenName,\n\t\tfmt.Sprintf(\"%s %s ubuntu@%s\", appConfig.Messages.DmServerReady, password, server_info.PublicAddress.IP),\n\t)\n\treturn nil\n}", "func (i EC2Instance) Teardown() error {\n\tlog.Printf(\"DEBUG:aws: Tearing down a compute instance\\n\")\n\t// must be able to deal with the exit status of script is 255 b/c of reboot command\n\tsetup := utils.Config(\"partitions\").Lookup(i.partition + \".teardown\").Self()\n\tif setup == \"\" {\n\t\tlog.Printf(\"DEBUG:aws: No teardown required\\n\")\n\t\treturn nil\n\t}\n\tdirSplit := strings.SplitAfter(setup, \"/\")\n\tdir := strings.Join(dirSplit[:len(dirSplit)-1], \"\")\n\terr := exec.Command(setup, i.Name(), dir).Run()\n\tif err != nil && !strings.Contains(err.Error(), \"255\") {\n\t\treturn fmt.Errorf(\"WARNING:aws: could not teardown instance %s due to %v\", i.Name(), err)\n\t}\n\treturn nil\n}", "func (a *ami) amiCreate(amiCreateChan chan *workResults) {\n\n\t// instChan is the input channel for the system\n\tinstChan := make(chan *ec2.CreateImageInput)\n\tresChan := make(chan *workResult) // results and output chan\n\tdoneChan := make(chan *workResults)\n\n\t// Create an EC2 service object\n\t// config values keys, sercet key & region read from environment\n\t//a.svc = ec2.New(a.sess, &aws.Config{MaxRetries: aws.Int(10)})\n\tvar wg sync.WaitGroup\n\n\t// create 3 workers that will create the AMI's\n\t// ami create takes a lot of work so don't overload the system and\n\t// hit the AWS rate limiters\n\tfor x := 0; x <= 3; x++ {\n\t\twg.Add(1)\n\t\tgo a.createandTagImage(instChan, resChan, &wg)\n\t}\n\n\t// create a channel to receive instances needing bkup\n\tfaInstChan := getBkupInstances(a.svc, a.tagname)\n\n\t// start the results goroutine running\n\tgo a.processResults(resChan, doneChan)\n\n\t// start pushing things into the system\n\tfor faBkupInst := range faInstChan {\n\t\tif faBkupInst.e != nil {\n\t\t\tfmt.Printf(\"error received getting bkup instance details: %v\\n\", faBkupInst.e)\n\t\t\tcontinue\n\t\t}\n\t\tinstChan <- faBkupInst.ii\n\t}\n\n\t// all instances to be backed up have been pushed to the workers so close their input channel\n\tclose(instChan)\n\n\t// wait for the goroutines to do their work and exit\n\twg.Wait()\n\n\t// Now we know the workers are gone and therefore no more work will be sent on the resChan\n\t// this will exit the results processor range over the resChan\n\tclose(resChan)\n\t// wait for the results goroutine to shutdown then return\n\twrs := <-doneChan\n\tclose(doneChan)\n\n\t// update complete time\n\twrs.endtime = time.Now().String()\n\t// send on the chan to indicate we are done\n\tamiCreateChan <- wrs\n\treturn\n}", "func (s *SlaveNode) doReadyState() string { // -> SUnbooted\n\ts.hasSuccessfullyBooted = true\n\n\t// If we have a queued restart, service that rather than booting\n\t// slaves or commands on potentially stale code.\n\tselect {\n\tcase <-s.needsRestart:\n\t\ts.doRestart()\n\t\treturn SUnbooted\n\tdefault:\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-s.needsRestart:\n\t\t\ts.doRestart()\n\t\t\treturn SUnbooted\n\t\tcase slave := <-s.slaveBootRequests:\n\t\t\ts.bootSlave(slave)\n\t\tcase request := <-s.commandBootRequests:\n\t\t\ts.bootCommand(request)\n\t\t}\n\t}\n}", "func init() {\n\tcmd := cli.Command{\n\t\tName: \"ssh\",\n\t\tUsage: \"create and manage ssh certificates\",\n\t\tUsageText: \"step ssh <subcommand> [arguments] [global-flags] [subcommand-flags]\",\n\t\tDescription: `**step ssh** command group provides facilities to sign SSH certificates.\n\n## EXAMPLES\n\nGenerate a new SSH key pair and user certificate:\n'''\n$ step ssh certificate joe@work id_ecdsa\n'''\n\nGenerate a new SSH key pair and host certificate:\n'''\n$ step ssh certificate --host internal.example.com ssh_host_ecdsa_key\n'''\n\nAdd a new user certificate to the agent:\n'''\n$ step ssh login joe@example.com\n'''\n\nRemove a certificate from the agent:\n'''\n$ step ssh logout joe@example.com\n'''\n\nList all keys in the agent:\n'''\n$ step ssh list\n'''\n\nConfigure a user environment with the SSH templates:\n'''\n$ step ssh config\n'''\n\nInspect an ssh certificate file:\n'''\n$ step ssh inspect id_ecdsa-cert.pub\n'''\n\nInspect an ssh certificate in the agent:\n'''\n$ step ssh list --raw joe@example.com | step ssh inspect\n'''\n\nList all the hosts you have access to:\n'''\n$ step ssh hosts\n'''\n\nLogin into one host:\n'''\n$ ssh internal.example.com\n'''`,\n\t\tSubcommands: cli.Commands{\n\t\t\tcertificateCommand(),\n\t\t\tcheckHostCommand(),\n\t\t\tconfigCommand(),\n\t\t\tfingerPrintCommand(),\n\t\t\thostsCommand(),\n\t\t\tinspectCommand(),\n\t\t\tlistCommand(),\n\t\t\tloginCommand(),\n\t\t\tlogoutCommand(),\n\t\t\tneedsRenewalCommand(),\n\t\t\t// proxyCommand(),\n\t\t\tproxycommandCommand(),\n\t\t\trekeyCommand(),\n\t\t\trenewCommand(),\n\t\t\trevokeCommand(),\n\t\t},\n\t}\n\n\tcommand.Register(cmd)\n}", "func CheckSshConnectionE(t testing.TestingT, host Host) error {\n\t_, err := CheckSshCommandE(t, host, \"'exit'\")\n\treturn err\n}", "func NewSSHServer(logger log.Logger) (d clientserverpair.Dialer, pubKey ssh2.PublicKey, stop func()) {\n\tssh.Handle(func(s ssh.Session) {\n\t\tif len(s.Command()) == 0 {\n\t\t\tpanic(\"unimplemented\")\n\t\t} else {\n\t\t\t// Exec a command.\n\t\t\tcmd := shellquote.Join(s.Command()...)\n\t\t\tout := commandMap[cmd]\n\t\t\ts.Write([]byte(out.Output))\n\t\t\ts.Exit(out.Code)\n\t\t}\n\t})\n\n\td, l := clientserverpair.New(&clientserverpair.PipeCSPairConfig{\n\t\tLogger: logger,\n\n\t\tClientReadDebug: nil,\n\t\tClientWriteDebug: nil,\n\t\tServerReadDebug: nil,\n\t\tServerWriteDebug: nil,\n\t})\n\tli := recursivelistener.New(l)\n\tlogger.Debug(\"created dialer/listener pair\")\n\terrC := make(chan error)\n\tcancelC := make(chan struct{})\n\n\tkey, err := rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsigner, err := ssh2.NewSignerFromKey(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tgo func() {\n\t\tlogger.Debug(\"About serve SSH\")\n\t\tsrv := &ssh.Server{\n\t\t\tPasswordHandler: func(user, password string) bool {\n\t\t\t\tif user == \"test\" && password == \"Password123\" {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t},\n\t\t\tHostSigners: []ssh.Signer{signer.(ssh.Signer)},\n\t\t}\n\t\terr = srv.Serve(li)\n\t\tselect {\n\t\tcase errC <- err:\n\t\tcase <-cancelC:\n\t\t}\n\t}()\n\n\t// Wait for a few milliseconds to ensure the server started without errors.\n\tselect {\n\tcase <-time.After(50 * time.Millisecond):\n\tcase err := <-errC:\n\t\tpanic(err)\n\t}\n\tlogger.Debug(\"No error attempting to start SSH server\")\n\n\treturn d, signer.PublicKey(), func() { close(cancelC); l.Close() }\n}", "func InitAWS(awsRegion, awsAccessKey, awsSecretKey string) {\n\n\tAWSSession = session.New()\n\n\t// Region\n\tif awsRegion != \"\" {\n\t\t// CLI trumps\n\t\tAWSSession.Config.Region = aws.String(awsRegion)\n\t} else if os.Getenv(\"AWS_DEFAULT_REGION\") != \"\" {\n\t\t// Env is good, too\n\t\tAWSSession.Config.Region = aws.String(os.Getenv(\"AWS_DEFAULT_REGION\"))\n\t} else {\n\t\t// Grab it from this EC2 instance, maybe\n\t\tregion, err := getAwsRegionE()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Cannot set AWS region: '%v'\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tAWSSession.Config.Region = aws.String(region)\n\t}\n\n\t// Creds\n\tif awsAccessKey != \"\" && awsSecretKey != \"\" {\n\t\t// CLI trumps\n\t\tcreds := credentials.NewStaticCredentials(\n\t\t\tawsAccessKey,\n\t\t\tawsSecretKey,\n\t\t\t\"\")\n\t\tAWSSession.Config.Credentials = creds\n\t} else if os.Getenv(\"AWS_ACCESS_KEY_ID\") != \"\" {\n\t\t// Env is good, too\n\t\tcreds := credentials.NewStaticCredentials(\n\t\t\tos.Getenv(\"AWS_ACCESS_KEY_ID\"),\n\t\t\tos.Getenv(\"AWS_SECRET_ACCESS_KEY\"),\n\t\t\t\"\")\n\t\tAWSSession.Config.Credentials = creds\n\t}\n\n}", "func phase1Setup(ctx context.Context, server, spawnClientserver, clientserver bool, dspath string, home, serverhash string, port int) (*core.IpfsNode, string, int, string, bool) {\n\n\tvar n *core.IpfsNode\n\tvar err error\n\n\t// grab or update configs\n\tfilepath := fmt.Sprintf(\"%s%s.ipbohrc\", home, string(os.PathSeparator))\n\tserverhash, port = getUpdateConfig(filepath, serverhash, port)\n\tcsBaseUrl := fmt.Sprintf(\"http://localhost:%d\", port)\n\n\tif server {\n\t\tn, err = startupIPFS(dspath, &ctx)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfor _, addr := range n.PeerHost.Addrs() {\n\t\t\tfmt.Printf(\"Swarm listening on %s\\n\", addr.String())\n\t\t}\n\t} else if clientserver {\n\t\tn, err = startupIPFS(dspath, &ctx)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tresp, err := http.Get(fmt.Sprintf(\"%s/areuthere\", csBaseUrl))\n\t\tif err != nil {\n\t\t\tspawnClientserver = true\n\t\t} else if resp.StatusCode == 200 {\n\t\t\tspawnClientserver = false\n\t\t} else {\n\t\t\tspawnClientserver = true\n\t\t}\n\n\t}\n\n\t// spawn a separate process to launch client server if it is not already running\n\tif spawnClientserver {\n\t\tvar exePath string\n\t\texePath, err := godaemon.GetExecutablePath()\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"failed to get pid: %v\", err)\n\t\t}\n\n\t\tfiles := make([]*os.File, 3, 3)\n\t\tfiles[0], files[1], files[2] = os.Stdin, os.Stdout, os.Stderr\n\t\tattrs := os.ProcAttr{Dir: \".\", Env: os.Environ(), Files: files}\n\t\t_, err = os.StartProcess(exePath, []string{exePath, \"-c\", \"-p\", fmt.Sprintf(\"%d\", port)}, &attrs)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\treturn n, serverhash, port, csBaseUrl, spawnClientserver\n}", "func getEC2Hosts(aws awsECSClient, state *ecsState) error {\n\t// Now extract all ec2 instance IDs\n\tec2IDs := []string{}\n\tfor cid, ci := range state.live.containerInstances {\n\t\tid := ptr.StringValue(ci.Ec2InstanceId)\n\t\tif id == \"\" {\n\t\t\tconsole.Error().Printf(\"Container %s did not contain a EC2 Instance ID\", cid)\n\t\t\tcontinue\n\t\t}\n\t\tec2IDs = append(ec2IDs, id)\n\t}\n\n\tsort.Strings(ec2IDs)\n\tec2IDs = dedupe.Strings(ec2IDs)\n\thosts, err := aws.GetEC2Instances(ec2IDs...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstate.live.ec2Hosts = hosts\n\n\treturn nil\n}", "func NewEc2Instance(ctx sdutils.AppContext, dd *awsDeploymentDescription) (*Ec2Instance, error) {\n\tvar err error\n\tcustomData := \"\"\n\tif dd.customPropFile != \"\" {\n\t\tdata, err := ioutil.ReadFile(dd.customPropFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid custom properties file: %s\", err)\n\t\t}\n\t\tcustomData = string(data)\n\t}\n\n\tcustomLog4J := \"\"\n\tif dd.customLog4J != \"\" {\n\t\tlog4JData, err := ioutil.ReadFile(dd.customLog4J)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid custom properties file: %s\", err)\n\t\t}\n\t\tcustomLog4J = base64.StdEncoding.EncodeToString(log4JData)\n\t}\n\n\tvar envBuffer bytes.Buffer\n\tfor _, env := range dd.environment {\n\t\tenvBuffer.WriteString(fmt.Sprintf(\"export %s\\n\", env))\n\t}\n\t// The custom script cannot be null in terraform so make a temp one\n\tscriptData := []byte(\"#!/bin/bash\\nexit 0\\n\")\n\tif dd.CustomScript != \"\" {\n\t\tscriptData, err = ioutil.ReadFile(dd.CustomScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to read the script %s: %s\", dd.CustomScript, err.Error())\n\t\t}\n\t}\n\tbase64CustomScriptData := base64.StdEncoding.EncodeToString(scriptData)\n\tbase64CustomScriptPath := path.Join(dd.deployDir, \"custom-stardogscript.base64\")\n\terr = ioutil.WriteFile(base64CustomScriptPath, []byte(base64CustomScriptData), 0644)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to create the base 64 encoded custom script\")\n\t}\n\n\tscriptZkData := []byte(\"#!/bin/bash\\nexit 0\\n\")\n\tif dd.CustomZkScript != \"\" {\n\t\tscriptZkData, err = ioutil.ReadFile(dd.CustomZkScript)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to read the script %s: %s\", dd.CustomZkScript, err.Error())\n\t\t}\n\t}\n\tbase64CustomZkScriptData := base64.StdEncoding.EncodeToString(scriptZkData)\n\tbase64CustomZkScriptPath := path.Join(dd.deployDir, \"custom-zk-stardogscript.base64\")\n\terr = ioutil.WriteFile(base64CustomZkScriptPath, []byte(base64CustomZkScriptData), 0644)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to create the base 64 encoded custom zk script\")\n\t}\n\n\tinstance := Ec2Instance{\n\t\tDeploymentName: dd.Name,\n\t\tRegion: dd.Region,\n\t\tKeyName: dd.AwsKeyName,\n\t\tVersion: dd.Version,\n\t\tZkInstanceType: dd.ZkInstanceType,\n\t\tSdInstanceType: dd.SdInstanceType,\n\t\tAmiID: dd.AmiID,\n\t\tPrivateKey: dd.PrivateKeyPath,\n\t\tDeployDir: dd.deployDir,\n\t\tCustomScript: base64CustomScriptPath,\n\t\tCustomZkScript: base64CustomZkScriptPath,\n\t\tCtx: ctx,\n\t\tCustomPropsData: customData,\n\t\tCustomLog4JData: customLog4J,\n\t\tEnvironment: envBuffer.String(),\n\t}\n\tif dd.disableSecurity {\n\t\tinstance.StartOpts = \"--disable-security\"\n\t}\n\treturn &instance, nil\n}", "func (p *CognitoIdpPlugin) prepare() error {\n\tsess, err := session.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig := aws.NewConfig()\n\tif p.AccessKeyID != \"\" && p.SecretAccessKey != \"\" {\n\t\tconfig = config.WithCredentials(credentials.NewStaticCredentials(p.AccessKeyID, p.SecretAccessKey, \"\"))\n\t}\n\tif p.Region != \"\" {\n\t\tconfig = config.WithRegion(p.Region)\n\t}\n\n\tp.CloudWatch = cloudwatch.New(sess, config)\n\n\treturn nil\n}" ]
[ "0.61722517", "0.6099489", "0.5970563", "0.5950927", "0.5914715", "0.58060163", "0.57204074", "0.56962776", "0.5693759", "0.5692265", "0.5665352", "0.5654342", "0.5614", "0.5586875", "0.55865085", "0.5542265", "0.5467121", "0.5443552", "0.53783226", "0.5374821", "0.53677905", "0.536054", "0.53338134", "0.5292312", "0.52617043", "0.5248376", "0.52446264", "0.52213216", "0.5219429", "0.5208006", "0.5197317", "0.5177655", "0.5143326", "0.5129565", "0.5125357", "0.5097255", "0.5095964", "0.5093421", "0.50881124", "0.50779617", "0.5057374", "0.50562084", "0.504885", "0.50301015", "0.50284165", "0.5021052", "0.50181645", "0.49931905", "0.49908474", "0.4990474", "0.49737293", "0.49718595", "0.49546844", "0.49155593", "0.49109465", "0.49019608", "0.48953888", "0.4884509", "0.4876748", "0.48640215", "0.48607808", "0.48599446", "0.48496136", "0.48441514", "0.4833558", "0.48302913", "0.48280847", "0.48240477", "0.48121375", "0.4810506", "0.4807408", "0.48003644", "0.4798364", "0.47937846", "0.47689247", "0.47664276", "0.47663", "0.47614437", "0.47296804", "0.47242978", "0.4715787", "0.47118765", "0.47110492", "0.47092065", "0.470351", "0.4684853", "0.46845815", "0.46812055", "0.46766365", "0.46683186", "0.4663557", "0.46592453", "0.46499053", "0.46476495", "0.46466932", "0.4635798", "0.46334258", "0.4627257", "0.46257025", "0.46213847" ]
0.824867
0
RunCommand is a wrapper around the SSH client to run a command abstracts the SSH connection details from the EC2 client interface RunCommandWithOutput discards the stdout and stderr from the command
func (ins *EC2RemoteClient) RunCommand(cmd string) (exitStatus int, err error) { exitStatus, err = ins.cmdClient.RunCommand(cmd) return exitStatus, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ins *EC2RemoteClient) RunCommandWithOutput(cmd string) (exitStatus int, stdoutBuf bytes.Buffer, stderrBuf bytes.Buffer, err error) {\n\texitStatus, stdoutBuf, stderrBuf, err = ins.cmdClient.RunCommandWithOutput(cmd)\n\treturn exitStatus, stdoutBuf, stderrBuf, err\n}", "func (client *Client) Run(command string, silent bool) (output string, err error) {\n\tkeys := ssh.Auth{\n\t\tKeys: []string{client.PrivateKeyFile},\n\t}\n\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \"SSH-2.0-MyCustomClient-1.0\", client.Port, &keys, nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\tif !silent {\n\t\tlog.Printf(\"Running: ssh -i \\\"%s\\\" %s@%s %s\", client.PrivateKeyFile, client.User, client.Host, command)\n\t}\n\tr, _, err := sshterm.Start(command)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to start command - %s\", err)\n\t}\n\tsshterm.Wait()\n\tresponse, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to read response - %s\", err)\n\t}\n\treturn string(response), nil\n}", "func (client *SSHClient) Run(command string, stdout io.Writer, stderr io.Writer) error {\n\tsession, err := client.cryptoClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer session.Close()\n\n\tsession.Stdout = stdout\n\tsession.Stderr = stderr\n\n\treturn session.Run(command)\n}", "func (self *Client) RunCommand(cmd *Command) (string, []error) {\n var (\n output string\n errs []error\n )\n\n //- Compile our \"Valid\" and \"Error\" REGEX patterns, if not done already.\n // This will allow us to reuse it with compiling it every time.\n cmd.CompileCmdRegex()\n\n\tcmd.LogCommandConfig() //- DEBUG\n\n //- \"Write\" the command to the remote SSH session.\n self.StdinPipe.Write([]byte(cmd.Exec))\n\n //- Loop until we've gotten all output from the remote SSH Session.\n done := false\n lastError := \"\"\n for done != true {\n b, _ := self.StdoutPipe.ReadByte()\n output = output + string(b)\n\n //- Check for errors, if we have any ErrorPatterns to test.\n if len(cmd.ErrorPatterns) > 0 {\n if matchedError, errDesc := testRegex(output, cmd.ErrorRegex); matchedError == true {\n if lastError != errDesc {\n errs = append(errs, fmt.Errorf(\"Matched error pattern: %s\", errDesc))\n lastError = errDesc\n }\n }\n }\n\n //- Check for Valid output. Continue retrieving bytes until we see a\n // \"valid\" pattern.\n if done, _ = testRegex(output, cmd.ValidRegex); done == true {\n //- Make sure there isn't any more left to read.\n//\t\t\ttime.Sleep(time.Second)\n if buff := self.StdoutPipe.Buffered(); buff != 0 {\n done = false\n }\n }\n }\n\n return output, errs\n}", "func (s *SSHClient) Run(command string) (string, error) {\n\tif err := s.createClient(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn s.run(command)\n}", "func (s *SSHer) Run(cmd string) (output []byte, err error) {\n\tvar session *ssh.Session\n\tif session, err = s.client.NewSession(); err != nil {\n\t\treturn\n\t}\n\tdefer session.Close()\n\n\tif output, err = session.CombinedOutput(cmd); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func RunSSHCommand(SSHHandle *ssh.Client, cmd string, sudo bool, bg bool, logger *log.Logger) (retCode int, stdout, stderr []string) {\n\tlogger.Println(\"Running cmd \" + cmd)\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\tsshSession, err := SSHHandle.NewSession()\n\tif err != nil {\n\t\tlogger.Printf(\"SSH session creation failed! %s\", err)\n\t\treturn -1, nil, nil\n\t}\n\tdefer sshSession.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err = sshSession.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\tlogger.Println(\"SSH session Pty creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tsshOut, err := sshSession.StdoutPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StdoutPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\tsshErr, err := sshSession.StderrPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StderrPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tshout := io.MultiWriter(&stdoutBuf, (*LogWriter)(logger))\n\tssherr := io.MultiWriter(&stderrBuf, (*LogWriter)(logger))\n\n\tgo func() {\n\t\tio.Copy(shout, sshOut)\n\t}()\n\tgo func() {\n\n\t\tio.Copy(ssherr, sshErr)\n\t}()\n\n\tif bg {\n\t\tcmd = \"nohup sh -c \\\"\" + cmd + \" 2>&1 >/dev/null </dev/null & \\\"\"\n\t} else {\n\t\tcmd = \"sh -c \\\"\" + cmd + \"\\\"\"\n\t}\n\n\tif sudo {\n\t\tcmd = SudoCmd(cmd)\n\t}\n\n\tlogger.Println(\"Running command : \" + cmd)\n\tif err = sshSession.Run(cmd); err != nil {\n\t\tlogger.Println(\"failed command : \" + cmd)\n\t\tswitch v := err.(type) {\n\t\tcase *ssh.ExitError:\n\t\t\tretCode = v.Waitmsg.ExitStatus()\n\t\tdefault:\n\t\t\tretCode = -1\n\t\t}\n\t} else {\n\t\tlogger.Println(\"sucess command : \" + cmd)\n\t\tretCode = 0\n\t}\n\n\tstdout = strings.Split(stdoutBuf.String(), \"\\n\")\n\tstderr = strings.Split(stderrBuf.String(), \"\\n\")\n\tlogger.Println(stdout)\n\tlogger.Println(stderr)\n\tlogger.Println(\"Return code : \" + strconv.Itoa(retCode))\n\n\treturn retCode, stdout, stderr\n\n}", "func SSHRunCommand(client *ssh.Client, cmd string) (string, error) {\n\tsession, err := client.NewSession()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer session.Close()\n\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tsession.Stdout = &stdout\n\tsession.Stderr = &stderr\n\n\terr = session.Run(cmd)\n\n\toutput := stdout.String() + stderr.String()\n\n\tif err != nil {\n\t\treturn output, fmt.Errorf(\"failed to execute command \\\"%s\\\" via SSH client: %s\", cmd, err)\n\t}\n\n\treturn output, nil\n}", "func (c *SSHConnection) RunCommand(cmd string) ([]byte, error) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.lastUsed = time.Now()\n\n\tif c.client == nil {\n\t\treturn nil, errors.New(\"not connected\")\n\t}\n\n\tsession, err := c.client.NewSession()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not open session\")\n\t}\n\tdefer session.Close()\n\n\tvar b = &bytes.Buffer{}\n\tsession.Stdout = b\n\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not run command\")\n\t}\n\n\treturn b.Bytes(), nil\n}", "func (runner *SSHRunner) Run(command string) (string, error) {\n\treturn runner.runSSHCommandFromDriver(command, false)\n}", "func (sc *sshclient) RunWithResults(address string, command string) (string, error) {\n\tclient, err := ssh.Dial(\"tcp\", address, sc.config)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not connect to address %s:%v \", address, err)\n\t}\n\n\t// Each ClientConn can support multiple interactive sessions,\n\t// represented by a Session.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not create session at address %s:%v \", address, err)\n\t}\n\tdefer session.Close()\n\n\tresultdata, err := session.Output(command)\n\tif err != nil {\n\t\treturn string(resultdata), fmt.Errorf(\"Command '%s' at address %s produced an error:%v \", command, address, err)\n\t}\n\n\treturn string(resultdata), nil\n}", "func RunCommand(host string, command string, reader io.Reader, stdOut io.Writer, stdErr io.Writer) error {\n\tsession, err := SSHSession(host)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err := session.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\tsession.Close()\n\t\treturn fmt.Errorf(\"request for pseudo terminal failed: %s\", err)\n\t}\n\n\tsession.Stdout = stdOut\n\tsession.Stdin = reader\n\tsession.Stderr = stdErr\n\terr = session.Run(command)\n\n\treturn nil\n}", "func (c *Command) RunCommand(instanceIDs []*string) (err error) {\n\tinput := ssm.SendCommandInput{\n\t\tTimeoutSeconds: aws.Int64(30),\n\t\tInstanceIds: instanceIDs,\n\t\tMaxConcurrency: &c.MaxConcurrency,\n\t\tMaxErrors: &c.MaxErrors,\n\t\tDocumentName: aws.String(\"AWS-RunShellScript\"),\n\t\tComment: &c.Comment,\n\t\tCloudWatchOutputConfig: &ssm.CloudWatchOutputConfig{\n\t\t\tCloudWatchLogGroupName: &c.LogGroup,\n\t\t\tCloudWatchOutputEnabled: aws.Bool(true),\n\t\t},\n\t}\n\n\tinput.Parameters = map[string][]*string{\n\t\t\"commands\": aws.StringSlice([]string{strings.Join(c.Command, \" \")}),\n\t\t\"executionTimeout\": aws.StringSlice([]string{fmt.Sprintf(\"%d\", c.ExecutionTimeout)}),\n\t}\n\n\toutput, err := ssmSvc.SendCommand(&input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error invoking SendCommand: %s\", err)\n\t}\n\n\tc.SSMCommand = output.Command\n\n\t// Wait for each instance to finish\n\tvar wg sync.WaitGroup\n\n\tfor _, instanceID := range instanceIDs {\n\t\twg.Add(1)\n\t\tgo Stream(&c.LogGroup, output.Command.CommandId, instanceID)\n\t\tgo WaitForInstance(output.Command.CommandId, instanceID, &wg)\n\t}\n\n\twg.Wait()\n\n\ttime.Sleep(10 * time.Second)\n\treturn nil\n}", "func (client *SSHClient) RunCommand(cmd *SSHCommand) error {\n\tvar (\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\tif session, err = client.newSession(); err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\tif err = client.prepareCommand(session, cmd); err != nil {\n\t\treturn err\n\t}\n\t// Must sleep here.\n\ttime.Sleep(5)\n\terr = session.Run(cmd.Path)\n\treturn err\n}", "func (s *SSHRunner) RunCmd(cmd *exec.Cmd) (*RunResult, error) {\n\tif cmd.Stdin != nil {\n\t\treturn nil, fmt.Errorf(\"SSHRunner does not support stdin - you could be the first to add it\")\n\t}\n\n\trr := &RunResult{Args: cmd.Args}\n\tklog.Infof(\"Run: %v\", rr.Command())\n\n\tvar outb, errb io.Writer\n\tstart := time.Now()\n\n\tif cmd.Stdout == nil {\n\t\tvar so bytes.Buffer\n\t\toutb = io.MultiWriter(&so, &rr.Stdout)\n\t} else {\n\t\toutb = io.MultiWriter(cmd.Stdout, &rr.Stdout)\n\t}\n\n\tif cmd.Stderr == nil {\n\t\tvar se bytes.Buffer\n\t\terrb = io.MultiWriter(&se, &rr.Stderr)\n\t} else {\n\t\terrb = io.MultiWriter(cmd.Stderr, &rr.Stderr)\n\t}\n\n\tsess, err := s.session()\n\tif err != nil {\n\t\treturn rr, errors.Wrap(err, \"NewSession\")\n\t}\n\n\tdefer func() {\n\t\tif err := sess.Close(); err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tklog.Errorf(\"session close: %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = teeSSH(sess, shellquote.Join(cmd.Args...), outb, errb)\n\telapsed := time.Since(start)\n\n\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\trr.ExitCode = exitError.ExitCode()\n\t}\n\t// Decrease log spam\n\tif elapsed > (1 * time.Second) {\n\t\tklog.Infof(\"Completed: %s: (%s)\", rr.Command(), elapsed)\n\t}\n\tif err == nil {\n\t\treturn rr, nil\n\t}\n\n\treturn rr, fmt.Errorf(\"%s: %v\\nstdout:\\n%s\\nstderr:\\n%s\", rr.Command(), err, rr.Stdout.String(), rr.Stderr.String())\n}", "func (e *SSHExecutor) Execute(cmd string, sudo bool, timeout ...time.Duration) ([]byte, []byte, error) {\n\t// try to acquire root permission\n\tif e.Sudo || sudo {\n\t\tcmd = fmt.Sprintf(\"sudo -H -u root bash -c \\\"%s\\\"\", cmd)\n\t}\n\n\t// set a basic PATH in case it's empty on login\n\tcmd = fmt.Sprintf(\"PATH=$PATH:/usr/bin:/usr/sbin %s\", cmd)\n\n\tif e.Locale != \"\" {\n\t\tcmd = fmt.Sprintf(\"export LANG=%s; %s\", e.Locale, cmd)\n\t}\n\n\t// run command on remote host\n\t// default timeout is 60s in easyssh-proxy\n\tif len(timeout) == 0 {\n\t\ttimeout = append(timeout, executeDefaultTimeout)\n\t}\n\n\tstdout, stderr, done, err := e.Config.Run(cmd, timeout...)\n\n\tzap.L().Info(\"SSHCommand\",\n\t\tzap.String(\"host\", e.Config.Server),\n\t\tzap.String(\"port\", e.Config.Port),\n\t\tzap.String(\"cmd\", cmd),\n\t\tzap.Error(err),\n\t\tzap.String(\"stdout\", stdout),\n\t\tzap.String(\"stderr\", stderr))\n\n\tif err != nil {\n\t\tbaseErr := ErrSSHExecuteFailed.\n\t\t\tWrap(err, \"Failed to execute command over SSH for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t\tif len(stdout) > 0 || len(stderr) > 0 {\n\t\t\toutput := strings.TrimSpace(strings.Join([]string{stdout, stderr}, \"\\n\"))\n\t\t\tbaseErr = baseErr.\n\t\t\t\tWithProperty(cliutil.SuggestionFromFormat(\"Command output on remote host %s:\\n%s\\n\",\n\t\t\t\t\te.Config.Server,\n\t\t\t\t\tcolor.YellowString(output)))\n\t\t}\n\t\treturn []byte(stdout), []byte(stderr), baseErr\n\t}\n\n\tif !done { // timeout case,\n\t\treturn []byte(stdout), []byte(stderr), ErrSSHExecuteTimedout.\n\t\t\tWrap(err, \"Execute command over SSH timedout for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t}\n\n\treturn []byte(stdout), []byte(stderr), nil\n}", "func RunCommandAndStoreOutput(vmi *v1.VirtualMachineInstance, command string, timeout time.Duration) (string, error) {\n\tvirtClient := kubevirt.Client()\n\n\topts := &kubecli.SerialConsoleOptions{ConnectionTimeout: timeout}\n\tstream, err := virtClient.VirtualMachineInstance(vmi.Namespace).SerialConsole(vmi.Name, opts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tconn := stream.AsConn()\n\tdefer conn.Close()\n\n\t_, err = fmt.Fprintf(conn, \"%s\\n\", command)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tscanner := bufio.NewScanner(conn)\n\tif !skipInput(scanner) {\n\t\treturn \"\", fmt.Errorf(\"failed to run [%s] at VMI %s (skip input)\", command, vmi.Name)\n\t}\n\tif !scanner.Scan() {\n\t\treturn \"\", fmt.Errorf(\"failed to run [%s] at VMI %s\", command, vmi.Name)\n\t}\n\treturn scanner.Text(), nil\n}", "func (c *Client) Run(ctx context.Context, cmds []*Command) error {\n\turl := c.Host + \":\" + c.Port\n\tclient, err := ssh.Dial(\"tcp\", url, c.Sshconfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in ssh.Dial to %v %w\", url, err)\n\t}\n\n\tdefer client.Close()\n\tsession, err := client.NewSession()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in client.NewSession to %v %w\", url, err)\n\t}\n\tdefer session.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err := session.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\treturn fmt.Errorf(\"error in session.RequestPty to %v %w\", url, err)\n\t}\n\n\tw, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in session.StdinPipe to %v %w\", url, err)\n\t}\n\tr, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in session.StdoutPipe to %v %w\", url, err)\n\t}\n\tin, out := listener(w, r, c.Prompt)\n\tif err := session.Start(\"/bin/sh\"); err != nil {\n\t\treturn fmt.Errorf(\"error in session.Start to %v %w\", url, err)\n\t}\n\n\t<-out // ignore login output\n\tfor _, cmd := range cmds {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.New(\"canceled by context\")\n\n\t\tdefault:\n\t\t\tlogf(cmd.OutputLevel, \"[%v]: cmd [%v] starting...\", c.Host, cmd.Input)\n\n\t\t\tin <- cmd\n\t\t\terr := cmd.wait(ctx, out)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[%v]: Error in cmd [%v] at waiting %w\", c.Host, cmd.Input, err)\n\t\t\t}\n\n\t\t\tif outputs, ok := cmd.output(); ok {\n\t\t\t\tfor _, output := range outputs {\n\t\t\t\t\tfmt.Println(output)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdoNext, err := cmd.Callback(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[%v]: Error in cmd [%v] Callback %w\", c.Host, cmd.Input, err)\n\t\t\t}\n\n\t\t\tif doNext && cmd.NextCommand != nil {\n\t\t\t\tnextCmd := cmd.NextCommand(cmd)\n\n\t\t\t\tlogf(nextCmd.OutputLevel, \"[%v]: next cmd [%v] starting...\", c.Host, nextCmd.Input)\n\n\t\t\t\tin <- nextCmd\n\t\t\t\terr = nextCmd.wait(ctx, out)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"[%v]: Error in next cmd [%v] at waiting %w\", c.Host, cmd.Input, err)\n\t\t\t\t}\n\n\t\t\t\tif outputs, ok := nextCmd.output(); ok {\n\t\t\t\t\tfor _, output := range outputs {\n\t\t\t\t\t\tfmt.Println(output)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t_, err := nextCmd.Callback(nextCmd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"[%v]: Error in next cmd [%v] Callback %w\", c.Host, nextCmd.Input, err)\n\t\t\t\t}\n\n\t\t\t\tlogf(nextCmd.OutputLevel, \"[%v]: next cmd [%v] done\", c.Host, nextCmd.Input)\n\n\t\t\t}\n\n\t\t\tlogf(cmd.OutputLevel, \"[%v]: cmd [%v] done\", c.Host, cmd.Input)\n\t\t}\n\t}\n\tsession.Close()\n\n\treturn nil\n}", "func runCommand(command string, commandPath string) (stdOut string, stdErr string, exitCode int, err error) {\n\treturn runCommandWithTimeout(command, commandPath, \"1h\")\n}", "func (s *SSH) Run(command string) (outStr string, err error) {\n\toutChan, doneChan, err := s.stream(command)\n\tif err != nil {\n\t\treturn outStr, err\n\t}\n\n\tdone := false\n\tfor !done {\n\t\tselect {\n\t\tcase <-doneChan:\n\t\t\tdone = true\n\t\tcase line := <-outChan:\n\t\t\t// TODO ew.. this is nasty\n\t\t\toutStr += line + \"\\n\"\n\n\t\t}\n\t}\n\n\treturn outStr, err\n}", "func Run(c *cli.Context) {\n\tport, err := osExpandAndVerifyGlobal(c, \"port\")\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tcommand, err := osExpandAndVerify(c, \"command\")\n\tif err != nil {\n\t\tfail(err)\n\t}\n\thost, err := osExpandAndVerify(c, \"host\")\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tuser, err := osExpandAndVerify(c, \"user\")\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tconnection := c.String(\"connection\")\n\tif connection == ansible.ConnectionWinRM {\n\t\tpassword, err := osExpandAndVerify(c, \"password\")\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t}\n\t\terr = winrm.RemoteWinRmCommand(user, password, host, port, command, nil, nil, \"\")\n\t} else {\n\t\tprivatekey, err := osExpandAndVerify(c, \"privatekey\")\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t}\n\t\tenvVars := make(map[string]string)\n\t\terr = ssh.RemoteSSHCommand(user, privatekey, host, port, command, envVars)\n\t}\n\tif err != nil {\n\t\tlog.Err(\"Failed: %v\", err)\n\t}\n}", "func (client *Client) Run() {\n\tret, val, msg := client.executeCommand()\n\tlog.Printf(\"Execute command result: %v\", ret)\n\tlog.Printf(\"Execute command value: %v\", val)\n\tlog.Printf(\"Execute command message: %v\", msg)\n}", "func runCommandWithOutput(execCmd *exec.Cmd) (string, int, error) {\n\tresult := icmd.RunCmd(transformCmd(execCmd))\n\treturn result.Combined(), result.ExitCode, result.Error\n}", "func (this Scanner) executeCommand(cmd string, session *ssh.Session) (string, error) {\n\t//Runs CombinedOutput, which takes cmd and returns stderr and stdout of the command\n\tout, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Convert our output to a string\n\ttmpOut := string(out)\n\ttmpOut = strings.Replace(tmpOut, \"\\n\", \"<br>\", -1)\n\n\t// Return a string version of our result\n\treturn tmpOut, nil\n}", "func (e *remoteExecutor) Execute(command []string, in io.Reader, out, errOut io.Writer) error {\n\tklog.V(3).Infof(\"Remote executor running command: %s\", strings.Join(command, \" \"))\n\texecOptions := &kexec.ExecOptions{\n\t\tStreamOptions: kexec.StreamOptions{\n\t\t\tNamespace: e.Namespace,\n\t\t\tPodName: e.PodName,\n\t\t\tContainerName: e.ContainerName,\n\t\t\tIOStreams: genericclioptions.IOStreams{\n\t\t\t\tIn: in,\n\t\t\t\tOut: out,\n\t\t\t\tErrOut: errOut,\n\t\t\t},\n\t\t\tStdin: in != nil,\n\t\t},\n\t\tExecutor: &kexec.DefaultRemoteExecutor{},\n\t\tPodClient: e.Client.CoreV1(),\n\t\tConfig: e.Config,\n\t\tCommand: command,\n\t}\n\terr := execOptions.Validate()\n\tif err != nil {\n\t\tklog.V(4).Infof(\"Error from remote command validation: %v\", err)\n\t\treturn err\n\t}\n\terr = execOptions.Run()\n\tif err != nil {\n\t\tklog.V(4).Infof(\"Error from remote execution: %v\", err)\n\t}\n\treturn err\n}", "func (k *OcRunner) RunCommand(command string) (stdOut string, stdErr string, exitCode int, err error) {\n\tstdOut, stdErr, exitCode, err = runCommand(command, k.CommandPath)\n\treturn\n}", "func (svc *SSHService) Run(hostName, cmd string) (int, string, string, error) {\n\tvar stdOut, stdErr string\n\tvar retCode int\n\tvar err error\n\n\thostSvc := NewHostService(svc.provider)\n\thost, err := hostSvc.Get(hostName)\n\tif err != nil {\n\t\treturn 0, \"\", \"\", logicErrf(err, \"no host found with name or id '%s'\", hostName)\n\t}\n\n\t// retrieve ssh config to perform some commands\n\tssh, err := svc.GetConfig(host)\n\n\tif err != nil {\n\t\treturn 0, \"\", \"\", infraErr(err)\n\t}\n\n\terr = retry.WhileUnsuccessfulDelay1SecondWithNotify(\n\t\tfunc() error {\n\t\t\tretCode, stdOut, stdErr, err = svc.run(ssh, cmd)\n\t\t\treturn err\n\t\t},\n\t\t2*time.Minute,\n\t\tfunc(t retry.Try, v Verdict.Enum) {\n\t\t\tif v == Verdict.Retry {\n\t\t\t\tlog.Printf(\"Remote SSH service on host '%s' isn't ready, retrying...\\n\", hostName)\n\t\t\t}\n\t\t},\n\t)\n\tif err != nil {\n\t\terr = infraErr(err)\n\t}\n\n\treturn retCode, stdOut, stdErr, err\n}", "func (h *Host) ExecWithOutput(cmd string) (string, error) {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer session.Close()\n\n\toutput, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\treturn strings.TrimSpace(string(output)), nil\n}", "func (s WebSSHBenchmark) runCommand(ctx context.Context, tc *client.TeleportClient, webSess *webSession, host, command string) error {\n\tstream, err := connectToHost(ctx, tc, webSess, host)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tdefer stream.Close()\n\n\tif _, err := io.WriteString(stream, command); err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tif _, err := io.Copy(tc.Stdout, stream); err != nil && !errors.Is(err, io.EOF) {\n\t\treturn trace.Wrap(err)\n\t}\n\n\treturn nil\n}", "func rcRunCommand(ctx context.Context, in Params) (out Params, err error) {\n\tcommand, err := in.GetString(\"command\")\n\tif err != nil {\n\t\tcommand = \"\"\n\t}\n\n\tvar opt = map[string]string{}\n\terr = in.GetStructMissingOK(\"opt\", &opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar arg = []string{}\n\terr = in.GetStructMissingOK(\"arg\", &arg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturnType, err := in.GetString(\"returnType\")\n\tif err != nil {\n\t\treturnType = \"COMBINED_OUTPUT\"\n\t}\n\n\tvar httpResponse http.ResponseWriter\n\thttpResponse, err = in.GetHTTPResponseWriter()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"response object is required\\n\" + err.Error())\n\t}\n\n\tvar allArgs = []string{}\n\tif command != \"\" {\n\t\t// Add the command e.g.: ls to the args\n\t\tallArgs = append(allArgs, command)\n\t}\n\t// Add all from arg\n\tallArgs = append(allArgs, arg...)\n\n\t// Add flags to args for e.g. --max-depth 1 comes in as { max-depth 1 }.\n\t// Convert it to [ max-depth, 1 ] and append to args list\n\tfor key, value := range opt {\n\t\tif len(key) == 1 {\n\t\t\tallArgs = append(allArgs, \"-\"+key)\n\t\t} else {\n\t\t\tallArgs = append(allArgs, \"--\"+key)\n\t\t}\n\t\tallArgs = append(allArgs, value)\n\t}\n\n\t// Get the path for the current executable which was used to run rclone.\n\tex, err := os.Executable()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcmd := exec.CommandContext(ctx, ex, allArgs...)\n\n\tif returnType == \"COMBINED_OUTPUT\" {\n\t\t// Run the command and get the output for error and stdout combined.\n\n\t\tout, err := cmd.CombinedOutput()\n\n\t\tif err != nil {\n\t\t\treturn Params{\n\t\t\t\t\"result\": string(out),\n\t\t\t\t\"error\": true,\n\t\t\t}, nil\n\t\t}\n\t\treturn Params{\n\t\t\t\"result\": string(out),\n\t\t\t\"error\": false,\n\t\t}, nil\n\t} else if returnType == \"STREAM_ONLY_STDOUT\" {\n\t\tcmd.Stdout = httpResponse\n\t} else if returnType == \"STREAM_ONLY_STDERR\" {\n\t\tcmd.Stderr = httpResponse\n\t} else if returnType == \"STREAM\" {\n\t\tcmd.Stdout = httpResponse\n\t\tcmd.Stderr = httpResponse\n\t} else {\n\t\treturn nil, fmt.Errorf(\"unknown returnType %q\", returnType)\n\t}\n\n\terr = cmd.Run()\n\treturn nil, err\n}", "func RunCommand(vmi *v1.VirtualMachineInstance, command string, timeout time.Duration) error {\n\terr := ExpectBatch(vmi, []expect.Batcher{\n\t\t&expect.BSnd{S: \"\\n\"},\n\t\t&expect.BExp{R: PromptExpression},\n\t\t&expect.BSnd{S: command + \"\\n\"},\n\t\t&expect.BExp{R: PromptExpression},\n\t\t&expect.BSnd{S: \"echo $?\\n\"},\n\t\t&expect.BCas{C: []expect.Caser{\n\t\t\t&expect.Case{\n\t\t\t\tR: ShellSuccessRegexp,\n\t\t\t\tT: expect.OK(),\n\t\t\t},\n\t\t\t&expect.Case{\n\t\t\t\tR: ShellFailRegexp,\n\t\t\t\tT: expect.Fail(expect.NewStatus(codes.Unavailable, command+\" failed\")),\n\t\t\t},\n\t\t}},\n\t}, timeout)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to run [%s] at VMI %s, error: %v\", command, vmi.Name, err)\n\t}\n\treturn nil\n}", "func (cmd *EnvironmentCommand) executeCommand(client *ssh.Client, cmdLine string) error {\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tcmd.currentSession = session\n\tsession.Stdin = os.Stdin\n\tif cmd.SuppressOutput {\n\t\tsession.Stdout = &cmd.OutputBuffer\n\t\tsession.Stderr = &cmd.ErrorBuffer\n\t} else {\n\t\tsession.Stdout = io.MultiWriter(os.Stdout, &cmd.OutputBuffer)\n\t\tsession.Stderr = io.MultiWriter(os.Stderr, &cmd.ErrorBuffer)\n\t}\n\treturn session.Run(cmdLine)\n}", "func (client *SSHClient) run(command string, resultdir string, sink *bufio.ReadWriter) error {\n\ts := &ssh.Session{}\n\terr := errors.New(\"\")\n\n\tif s, err = client.create(); err != nil {\n\t\treturn err\n\t}\n\tdefer s.Close()\n\n\tso, _ := s.StdoutPipe()\n\tif resultdir != \"\" {\n\t\tresultfile := strings.Replace(command, \" \", \"_\", -1)\n\t\tresultfile = strings.Replace(resultfile, \"/\", \"-\", -1)\n\t\tresultfile = strings.Replace(resultfile, \".\", \"\", -1)\n\t\trfname := filepath.Join(resultdir, resultfile)\n\t\trf := &os.File{}\n\t\tif rf, err = os.Create(rfname); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer rf.Close()\n\t\tgo io.Copy(rf, so)\n\t\terr = s.Run(command)\n\t\treturn err\n\t} else {\n\t\tgo io.Copy(sink, so)\n\t}\n\treturn nil\n}", "func (k *SshCMD)RemoteRun(user string, addr string, cmd string) (string, error) {\n\t// privateKey could be read from a file, or retrieved from another storage\n\t// source, such as the Secret Service / GNOME Keyring\n\t// Authentication\n\tconfig := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(k.rsa),\n\t\t\t//ssh.Password(\"jack2017\"),\n\t\t},\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t\t//alternatively, you could use a password\n\t\t/*\n\t\t\tAuth: []ssh.AuthMethod{\n\t\t\t\tssh.Password(\"PASSWORD\"),\n\t\t\t},\n\t\t*/\n\t}\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", addr+\":22222\", config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer session.Close()\n\tvar b bytes.Buffer // import \"bytes\"\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\tsession.Stderr = os.Stderr\n\t// Finally, run the command\n\terr = session.Run(cmd)\n\treturn b.String(), err\n}", "func (sshConfig *SSHConfig) Run(cmd string) (string, error) {\n\tb, err1 := sshConfig.rawRun(cmd)\n\treturn string(b), err1\n}", "func (sc *SSHClient) Command(cmd string) (io.Reader, error) {\n\tfmt.Println(cmd)\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := &bytes.Buffer{}\n\twriter := io.MultiWriter(os.Stdout, buf)\n\tgo io.Copy(writer, out)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo io.Copy(os.Stderr, outerr)\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}", "func (c *Communicator) run(cmd *exec.Cmd, remote *packer.RemoteCmd, stdin_w io.WriteCloser, outputFile *os.File, exitCodePath string) {\n\t// For Docker, remote communication must be serialized since it\n\t// only supports single execution.\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\t// Clean up after ourselves by removing our temporary files\n\tdefer os.Remove(outputFile.Name())\n\tdefer os.Remove(exitCodePath)\n\n\t// Tail the output file and send the data to the stdout listener\n\ttail, err := tail.TailFile(outputFile.Name(), tail.Config{\n\t\tPoll: true,\n\t\tReOpen: true,\n\t\tFollow: true,\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"Error tailing output file: %s\", err)\n\t\tremote.SetExited(254)\n\t\treturn\n\t}\n\tdefer tail.Stop()\n\n\t// Modify the remote command so that all the output of the commands\n\t// go to a single file and so that the exit code is redirected to\n\t// a single file. This lets us determine both when the command\n\t// is truly complete (because the file will have data), what the\n\t// exit status is (because Docker loses it because of the pty, not\n\t// Docker's fault), and get the output (Docker bug).\n\tremoteCmd := fmt.Sprintf(\"(%s) >%s 2>&1; echo $? >%s\",\n\t\tremote.Command,\n\t\tfilepath.Join(c.ContainerDir, filepath.Base(outputFile.Name())),\n\t\tfilepath.Join(c.ContainerDir, filepath.Base(exitCodePath)))\n\n\t// Start the command\n\tlog.Printf(\"Executing in container %s: %#v\", c.ContainerId, remoteCmd)\n\tif err := cmd.Start(); err != nil {\n\t\tlog.Printf(\"Error executing: %s\", err)\n\t\tremote.SetExited(254)\n\t\treturn\n\t}\n\n\tgo func() {\n\t\tdefer stdin_w.Close()\n\n\t\t// This sleep needs to be here because of the issue linked to below.\n\t\t// Basically, without it, Docker will hang on reading stdin forever,\n\t\t// and won't see what we write, for some reason.\n\t\t//\n\t\t// https://github.com/dotcloud/docker/issues/2628\n\t\ttime.Sleep(2 * time.Second)\n\n\t\tstdin_w.Write([]byte(remoteCmd + \"\\n\"))\n\t}()\n\n\t// Start a goroutine to read all the lines out of the logs. These channels\n\t// allow us to stop the go-routine and wait for it to be stopped.\n\tstopTailCh := make(chan struct{})\n\tdoneCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(doneCh)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-tail.Dead():\n\t\t\t\treturn\n\t\t\tcase line := <-tail.Lines:\n\t\t\t\tif remote.Stdout != nil {\n\t\t\t\t\tremote.Stdout.Write([]byte(line.Text + \"\\n\"))\n\t\t\t\t} else {\n\t\t\t\t\tlog.Printf(\"Command stdout: %#v\", line.Text)\n\t\t\t\t}\n\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\t// If we're done, then return. Otherwise, keep grabbing\n\t\t\t\t// data. This gives us a chance to flush all the lines\n\t\t\t\t// out of the tailed file.\n\t\t\t\tselect {\n\t\t\t\tcase <-stopTailCh:\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar exitRaw []byte\n\tvar exitStatus int\n\tvar exitStatusRaw int64\n\terr = cmd.Wait()\n\tif exitErr, ok := err.(*exec.ExitError); ok {\n\t\texitStatus = 1\n\n\t\t// There is no process-independent way to get the REAL\n\t\t// exit status so we just try to go deeper.\n\t\tif status, ok := exitErr.Sys().(syscall.WaitStatus); ok {\n\t\t\texitStatus = status.ExitStatus()\n\t\t}\n\n\t\t// Say that we ended, since if Docker itself failed, then\n\t\t// the command must've not run, or so we assume\n\t\tgoto REMOTE_EXIT\n\t}\n\n\t// Wait for the exit code to appear in our file...\n\tlog.Println(\"Waiting for exit code to appear for remote command...\")\n\tfor {\n\t\tfi, err := os.Stat(exitCodePath)\n\t\tif err == nil && fi.Size() > 0 {\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\t// Read the exit code\n\texitRaw, err = ioutil.ReadFile(exitCodePath)\n\tif err != nil {\n\t\tlog.Printf(\"Error executing: %s\", err)\n\t\texitStatus = 254\n\t\tgoto REMOTE_EXIT\n\t}\n\n\texitStatusRaw, err = strconv.ParseInt(string(bytes.TrimSpace(exitRaw)), 10, 0)\n\tif err != nil {\n\t\tlog.Printf(\"Error executing: %s\", err)\n\t\texitStatus = 254\n\t\tgoto REMOTE_EXIT\n\t}\n\texitStatus = int(exitStatusRaw)\n\tlog.Printf(\"Executed command exit status: %d\", exitStatus)\n\nREMOTE_EXIT:\n\t// Wait for the tail to finish\n\tclose(stopTailCh)\n\t<-doneCh\n\n\t// Set the exit status which triggers waiters\n\tremote.SetExited(exitStatus)\n}", "func testCommand(t *testing.T, client ssh.Client, command string) error {\n\t// To avoid mixing the output streams of multiple commands running in\n\t// parallel tests, we combine stdout and stderr on the remote host, and\n\t// capture stdout and write it to the test log here.\n\tstdout := new(bytes.Buffer)\n\tif err := client.Run(command+\" 2>&1\", stdout, os.Stderr); err != nil {\n\t\tt.Logf(\"`%s` failed with %v:\\n%s\", command, err, stdout.String())\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *MinikubeRunner) RunCommand(cmdStr string, failError bool, waitForRun ...bool) (string, string, error) {\n\tprofileArg := fmt.Sprintf(\"-p=%s \", m.Profile)\n\tcmdStr = profileArg + cmdStr\n\tcmdArgs := strings.Split(cmdStr, \" \")\n\tpath, _ := filepath.Abs(m.BinaryPath)\n\n\tcmd := exec.Command(path, cmdArgs...)\n\tLogf(\"Run: %s\", cmd.Args)\n\tstdout, stderr, err := m.teeRun(cmd, waitForRun...)\n\tif err != nil {\n\t\texitCode := \"\"\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\texitCode = string(exitError.Stderr)\n\t\t}\n\t\terrMsg := fmt.Sprintf(\"Error RunCommand : %s \\n\\t Begin RunCommand log block ---> \\n\\t With Profile: %s \\n\\t With ExitCode: %q \\n\\t With STDOUT %s \\n\\t With STDERR %s \\n\\t <--- End of RunCommand log block\", cmdStr, m.Profile, exitCode, stdout, stderr)\n\t\tif failError {\n\t\t\tm.T.Fatalf(errMsg)\n\t\t} else {\n\t\t\tm.T.Logf(errMsg)\n\t\t}\n\t}\n\treturn stdout, stderr, err\n}", "func (s *SSHClient) Execute(host, cmd string) (string, error) {\n\thostname := fmt.Sprintf(\"%s.%s.%s:%d\", host, s.projectID, DropletDomain, defaultSSHPort)\n\n\tpemBytes, err := s.repo.GetKey(s.projectID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(pemBytes)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"parse key failed: %v\", err)\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: \"workshop\",\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"dialing\")\n\tconn, err := ssh.Dial(\"tcp\", hostname, config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"creating session\")\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer session.Close()\n\n\tvar buf bytes.Buffer\n\tsession.Stdout = &buf\n\n\ts.log.WithFields(logrus.Fields{\n\t\t\"hostname\": hostname,\n\t\t\"cmd\": cmd}).\n\t\tInfo(\"running command\")\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\ts.log.WithField(\"output\", buf.String()).WithError(err).Error(\"ssh client run returned non zero result\")\n\t\treturn \"\", fmt.Errorf(\"%s\\n%s\", err, buf.String())\n\t}\n\n\treturn buf.String(), nil\n}", "func (scp *SCP) Run(_ string) (*entities.CommandResult, derrors.Error) {\n\n\tconn, err := connection.NewSSHConnection(\n\t\tscp.TargetHost, scp.getTargetPort(),\n\t\tscp.Credentials.Username, scp.Credentials.Password, \"\", scp.Credentials.PrivateKey)\n\tif err != nil {\n\t\treturn nil, derrors.NewInternalError(errors.SSHConnectionError, err).WithParams(scp.TargetHost)\n\t}\n\tstart := time.Now()\n\terr = conn.Copy(scp.Source, scp.Destination, false)\n\tif err != nil {\n\t\treturn nil, derrors.NewInternalError(errors.SSHConnectionError, err).WithParams(scp.TargetHost)\n\t}\n\n\treturn entities.NewSuccessCommand([]byte(scp.String() + \": OK \" + time.Since(start).String())), nil\n}", "func (eCmd *Exec) Run() int {\n\tif eCmd.allocatePTY && !isTerminal() {\n\t\tlog.Error(\"Cannot allocate pseudo-terminal without a terminal\")\n\t\treturn 1\n\t}\n\n\tlocalClient, err := eCmd.clientGetter.Client(eCmd.common.host)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn 1\n\t}\n\tdefer localClient.Close()\n\n\tcontainerClient, err := eCmd.clientGetter.ContainerClient(\n\t\tlocalClient, eCmd.targetContainer)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error getting container client\")\n\t\treturn 1\n\t}\n\n\tcontainer, err := util.GetContainer(containerClient, eCmd.targetContainer)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error getting container information\")\n\t\treturn 1\n\t}\n\n\terr = eCmd.SSHClient.Connect(containerClient.Host(), eCmd.privateKey)\n\tif err != nil {\n\t\tlog.WithError(err).Info(\"Error opening SSH connection\")\n\t\treturn 1\n\t}\n\tdefer eCmd.SSHClient.Disconnect()\n\n\tif eCmd.allocatePTY {\n\t\tif err = eCmd.SSHClient.RequestPTY(); err != nil {\n\t\t\tlog.WithError(err).Info(\"Error requesting pseudo-terminal\")\n\t\t\treturn 1\n\t\t}\n\t}\n\n\tvar flags string\n\tif eCmd.allocatePTY {\n\t\tflags = \"-it\"\n\t}\n\tcommand := strings.Join(\n\t\t[]string{\"docker exec\", flags, container.DockerID, eCmd.command}, \" \")\n\tif err = eCmd.SSHClient.Run(command); err != nil {\n\t\tlog.WithError(err).Info(\"Error running command over SSH\")\n\t\treturn 1\n\t}\n\n\treturn 0\n}", "func (svc *SSHService) run(ssh *system.SSHConfig, cmd string) (int, string, string, error) {\n\t// Create the command\n\tsshCmd, err := ssh.Command(cmd)\n\tif err != nil {\n\t\treturn 0, \"\", \"\", err\n\t}\n\treturn sshCmd.Run()\n}", "func runCommand(command string) error {\n\tcmd := exec.Command(\"sh\", \"-c\", command)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}", "func (r *Remoter) Run(waitCtx context.Context, cmds []string, stdout io.Writer, stderr io.Writer) error {\n\n\tclt := r.clt\n\tssn, err := clt.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer ssn.Close()\n\n\t// not know why use this\n\t// keep it for someday I know this\n\t//modes := ssh.TerminalModes{\n\t// ssh.ECHO: 0, // disable echoing\n\t// ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t// ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t//}\n\t//_ = modes\n\t//if err := ssn.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t// return nil\n\t//}\n\n\tshellInput, err := ssn.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tssn.Stdout = stdout\n\tssn.Stderr = stderr\n\terr = ssn.Shell()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, cmd := range cmds {\n\t\t_, err = fmt.Fprintf(shellInput, \"%s\\n\", cmd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// we must have exit to return `Wait()`\n\t_, err = fmt.Fprintf(shellInput, \"exit\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t// all command after exit will not run\n\tnoNeedWait, waitGrp := r.wait(waitCtx)\n\terr = ssn.Wait()\n\tclose(noNeedWait)\n\twaitGrp.Wait()\n\treturn err\n}", "func Run(cmd *exec.Cmd) (string, error) {\n\tklog.V(4).Infof(\"Executing: %s\", cmd)\n\n\tr, w := io.Pipe()\n\tcmd.Stdout = w\n\tcmd.Stderr = w\n\tbuffer := new(bytes.Buffer)\n\tr2 := io.TeeReader(r, buffer)\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tscanner := bufio.NewScanner(r2)\n\t\tfor scanner.Scan() {\n\t\t\tklog.V(5).Infof(\"%s: %s\", cmd.Path, scanner.Text())\n\t\t}\n\t}()\n\terr := cmd.Run()\n\tw.Close()\n\twg.Wait()\n\tklog.V(4).Infof(\"%s terminated, with %d bytes of output and error %v\", cmd.Path, buffer.Len(), err)\n\n\toutput := string(buffer.Bytes())\n\tif err != nil {\n\t\terr = fmt.Errorf(\"command %q failed: %v\\nOutput: %s\", cmd, err, output)\n\t}\n\treturn output, err\n}", "func RemoteRun(user string, addr string, port int, sshKey []byte, cmd string) (string, string, error) {\n\t// Create the Signer for this private key.\n\tsigner, err := ssh.ParsePrivateKey(sshKey)\n\tif err != nil {\n\t\treturn \"\", \"error in ssh.ParsePrivateKey()\", err\n\t}\n\n\t// Authentication\n\tconfig := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: func(string, net.Addr, ssh.PublicKey) error { return nil },\n\t}\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", addr, port), config)\n\tif err != nil {\n\t\treturn \"\", \"error in ssh.Dial()\", err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn \"\", \"error in NewSession()\", err\n\t}\n\tdefer session.Close()\n\tvar bOut, bErr bytes.Buffer\n\tsession.Stdout = &bOut // get output\n\tsession.Stderr = &bErr // get error\n\n\terr = session.Run(cmd)\n\treturn bOut.String(), bErr.String(), err\n}", "func ExecuteWithOutput(cmd *exec.Cmd) (outStr string, err error) {\n\t// connect to stdout and stderr for filtering purposes\n\terrPipe, err := cmd.StderrPipe()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"cmd\": cmd.Args,\n\t\t}).Fatal(\"Couldn't connect to command's stderr\")\n\t}\n\toutPipe, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"cmd\": cmd.Args,\n\t\t}).Fatal(\"Couldn't connect to command's stdout\")\n\t}\n\t_ = bufio.NewReader(errPipe)\n\toutReader := bufio.NewReader(outPipe)\n\n\t// start the command and filter the output\n\tif err = cmd.Start(); err != nil {\n\t\treturn \"\", err\n\t}\n\toutScanner := bufio.NewScanner(outReader)\n\tfor outScanner.Scan() {\n\t\toutStr += outScanner.Text() + \"\\n\"\n\t\tif log.GetLevel() == log.DebugLevel {\n\t\t\tfmt.Println(outScanner.Text())\n\t\t}\n\t}\n\terr = cmd.Wait()\n\treturn outStr, err\n}", "func runCommand() {\n\tvar commandOutput bytes.Buffer\n\tvar c *exec.Cmd\n\tif len(commandArgs) > 1 {\n\t\tc = exec.Command(commandArgs[0], commandArgs[1:]...)\n\t} else {\n\t\tc = exec.Command(commandArgs[0])\n\t}\n\tc.Stdout = &commandOutput\n\tc.Stderr = &commandOutput\n\n\terr := c.Run()\n\tif err != nil {\n\t\toutput.PrintError(commandOutput, err)\n\t} else if commandOutput.String() != \"\" {\n\t\toutput.PrintSuccess(commandOutput)\n\t} else {\n\t\toutput.NoError()\n\t}\n}", "func executeCommand(t *testing.T, cmd string, continueOnErr bool) string {\n\t// Fake the k8s api server\n\tapisvr := newAPIServer()\n\tdefer apisvr.Close()\n\n\t// Generate a test kubeconfig pointing at the server\n\tkubeconfig, err := writeTestKubeconfig(apisvr.URL)\n\tif err != nil {\n\t\tt.Fatalf(\"%+v\", err)\n\t}\n\tdefer os.Remove(kubeconfig)\n\n\t// Setup the svcat command\n\tsvcat, _, err := buildCommand(cmd, newContext(), kubeconfig)\n\tif err != nil {\n\t\tt.Fatalf(\"%+v\", err)\n\t}\n\n\t// Capture all output: stderr and stdout\n\toutput := &bytes.Buffer{}\n\tsvcat.SetOutput(output)\n\n\terr = svcat.Execute()\n\tif err != nil && !continueOnErr {\n\t\tt.Fatalf(\"%+v\", err)\n\t}\n\n\treturn output.String()\n}", "func Run(cl *cli.CliClient, args ...string) (string, string, error) {\n\toldArgs := os.Args\n\tos.Args = append([]string{\"scootcl\"}, args...)\n\tdefer func() {\n\t\tos.Args = oldArgs\n\t}()\n\n\toutput := captureOutput()\n\tdefer output.Reset()\n\n\terr := cl.Exec()\n\tstdout, stderr := output.WaitAndReset() // Reset early so we can use stdout/stderr and write to uncaptured stdout/stderr\n\treturn stdout, stderr, err\n}", "func (client *MockPodExecClient) RunPodExecCommand(ctx context.Context, streamOptions *remotecommand.StreamOptions, baseCmd []string) (string, string, error) {\n\n\tvar mockPodExecReturnContext *MockPodExecReturnContext = &MockPodExecReturnContext{}\n\tvar command string\n\t// This is to prevent the crash in the case where streamOptions.Stdin is anything other than *strings.Reader\n\t// In most of the cases the base command will be /bin/sh but if it is something else, it can be reading from\n\t// a io.Reader pipe. For e.g. tarring a file, writing to a write pipe and then untarring it on the pod by reading\n\t// from the reader pipe.\n\tif baseCmd[0] == \"/bin/sh\" {\n\t\tvar cmdStr string\n\t\tstreamOptionsCmd := streamOptions.Stdin.(*strings.Reader)\n\t\tfor i := 0; i < int(streamOptionsCmd.Size()); i++ {\n\t\t\tcmd, _, _ := streamOptionsCmd.ReadRune()\n\t\t\tcmdStr = cmdStr + string(cmd)\n\t\t}\n\n\t\tmockPodExecReturnContext, command = client.GetMockPodExecReturnContextAndKey(ctx, cmdStr)\n\t\tif mockPodExecReturnContext == nil {\n\t\t\terr := fmt.Errorf(\"mockPodExecReturnContext is nil\")\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t}\n\n\t// check if the command is already added or not in the list of GotCmdList\n\tvar found bool\n\tfor i := range client.GotCmdList {\n\t\tif command == client.GotCmdList[i] {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\tclient.GotCmdList = append(client.GotCmdList, command)\n\t}\n\n\treturn mockPodExecReturnContext.StdOut, mockPodExecReturnContext.StdErr, mockPodExecReturnContext.Err\n}", "func (sh *Shell) RunCommand(cmd string, args []string, timeout time.Duration) (result string, err error) {\n\n\t// default timeout\n\tif timeout == 0 {\n\t\ttimeout = sh.timeout\n\t}\n\n\t// Already called in LoadRemoteEnvironment, but just in case.\n\tif !sh.tokenSet {\n\t\terr = sh.setTokenIndex(sh.Log, timeout)\n\t\tif err != nil {\n\t\t\tsh.Log.Error(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tcmd = cmd + \" \" + strings.Join(args, \" \") // Concat command and args.\n\n\t// Get platform/OS for correct dispatch. Use associated host/DB, or anything.\n\t// Waiting, only Unix...\n\treturn sh.runCommandUnix(cmd, timeout)\n}", "func executeCmd(remote_host string) string {\n\treadConfig(\"config\")\n\t//\tconfig, err := sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t//\tif err != nil {\n\t//\t\tlog.Fatal(err)\n\t//\t}\n\tvar config *ssh.ClientConfig\n\n\tif Conf.Method == \"password\" {\n\t\tconfig = sshAuthPassword(Conf.SshUser, Conf.SshPassword)\n\t} else if Conf.Method == \"key\" {\n\t\tconfig = sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t\t//\t\tif err != nil {\n\t\t//\t\t\tlog.Fatal(err)\n\t\t//\t\t}\n\t} else {\n\t\tlog.Fatal(`Please set method \"password\" or \"key\" at configuration file`)\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", remote_host+\":\"+Conf.SshPort, config)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to dial: \", err)\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to create session: \", err)\n\t}\n\tdefer session.Close()\n\n\tvar b bytes.Buffer\n\tsession.Stdout = &b\n\tif err := session.Run(Conf.Command); err != nil {\n\t\tlog.Fatal(\"Failed to run: \" + err.Error())\n\t}\n\tfmt.Println(\"\\x1b[31;1m\" + remote_host + \"\\x1b[0m\")\n\treturn b.String()\n}", "func RunCommand(t *testing.T) *Command {\n\tt.Helper()\n\n\t// prefer MustRunCluster since it sets up for using etcd using\n\t// the GenDisCoConfig(size) option.\n\treturn MustRunUnsharedCluster(t, 1).GetNode(0)\n}", "func (factory *Factory) ExecuteCmd(\n\tnamespace string,\n\tname string,\n\tcontainer string,\n\tcommand string,\n\tprintOutput bool,\n) (string, string, error) {\n\tcmd := []string{\n\t\t\"/bin/bash\",\n\t\t\"-c\",\n\t\tcommand,\n\t}\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\terr := factory.ExecuteCommandRaw(namespace, name, container, cmd, nil, &stdout, &stderr, false)\n\tsout := stdout.String()\n\tserr := stderr.String()\n\t// TODO: Stream these to our own stdout as we run.\n\tif printOutput {\n\t\tif sout != \"\" && !strings.Contains(serr, \"constructing many client\") {\n\t\t\tlog.Println(sout)\n\t\t}\n\t\t// Callers of this used to skip printing serr if err was nil, but we never populate serr\n\t\t// if err is nil; always print for now.\n\t\tif serr != \"\" &&\n\t\t\t!strings.Contains(\n\t\t\t\tserr,\n\t\t\t\t\"constructing many client\",\n\t\t\t) { // ignoring constructing many client message\n\t\t\tlog.Println(serr)\n\t\t}\n\t}\n\treturn sout, serr, err\n}", "func RunCommand(name string, args ...string) (string, error) {\n\tvar out, berr bytes.Buffer\n\tcmd := exec.Command(name, args...)\n\tcmd.Stdout = &out\n\tcmd.Stderr = &berr\n\n\tif err := cmd.Run(); err != nil {\n\t\treturn out.String(), fmt.Errorf(\"err:%v berr:%v\", err, berr.String())\n\t}\n\n\treturn out.String() + berr.String(), nil\n\n}", "func (client *activeClient) runCommand(c *ishell.Context) {\n\tcommand := strings.Join(c.Args, \" \")\n\tvar r string\n\targs := shared.Cmd{\n\t\tCmd: command,\n\t\tPowershell: false,\n\t}\n\n\terr := client.RPC.Call(\"API.RunCmd\", args, &r)\n\tif err != nil {\n\t\tc.Println(yellow(\"[\"+client.Client.Name+\"] \") + red(\"[!] Bad or unkown command!\"))\n\t\tc.Println(yellow(\"[\"+client.Client.Name+\"] \") + red(\"[!] \", err))\n\t}\n\n\tc.Println(r)\n}", "func (r RealCommandRunner) Run(command string, args ...string) ([]byte, error) {\n\tout, err := exec.Command(command, args...).CombinedOutput()\n\treturn out, err\n}", "func (r *RemoteShell) Execute(ctx context.Context, cmd string) ([]byte, error) {\n\tsshCmd, err := r.conn.CommandContext(ctx, cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sshCmd.CombinedOutput()\n}", "func RunCommand(name string, args ...string) (stdout string, stderr string, exitCode int) {\n\tvar outbuf, errbuf bytes.Buffer\n\tcmd := exec.Command(name, args...)\n\tcmd.Stdout = &outbuf\n\tcmd.Stderr = &errbuf\n\n\terr := cmd.Run()\n\tstdout = outbuf.String()\n\tstderr = errbuf.String()\n\n\tif err != nil {\n\t\t// try to get the exit code\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\tws := exitError.Sys().(syscall.WaitStatus)\n\t\t\texitCode = ws.ExitStatus()\n\t\t} else {\n\t\t\t// This will happen (in OSX) if `name` is not available in $PATH,\n\t\t\t// in this situation, exit code could not be get, and stderr will be\n\t\t\t// empty string very likely, so we use the default fail code, and format err\n\t\t\t// to string and set to stderr\n\t\t\texitCode = defaultFailedCode\n\t\t\tif stderr == \"\" {\n\t\t\t\tstderr = err.Error()\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// success, exitCode should be 0 if go is ok\n\t\tws := cmd.ProcessState.Sys().(syscall.WaitStatus)\n\t\texitCode = ws.ExitStatus()\n\t}\n\treturn\n}", "func (c *Client) Exec(cmd string) ([]byte, error) {\n\tsession, err := c.SSHClient.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\n\treturn session.CombinedOutput(cmd)\n}", "func Run(connectAs string, connectTo string, key string) {\n\ttarget := connectAs + \"@\" + connectTo\n\tlog.Info(\"Connecting as \" + target)\n\n\texecutable := \"sshpass\"\n\tparams := []string{\n\t\t\"-p\", key, \"ssh\", \"-o\", \"StrictHostKeyChecking=no\", \"-t\", \"-t\", target,\n\t}\n\tlog.Infof(\"Launching: %s %s\", executable, strings.Join(params, \" \"))\n\n\tif log.GetLevel() == log.DebugLevel {\n\t\tfor i, param := range params {\n\t\t\tif param == \"ssh\" {\n\t\t\t\ti = i + 1\n\t\t\t\t// Yes: this is crazy, but this inserts an element into a slice\n\t\t\t\tparams = append(params[:i], append([]string{\"-v\"}, params[i:]...)...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tcmd := exec.Command(executable, params...)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\terr := cmd.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd.Wait()\n\tlog.Infof(\"Just ran subprocess %d, exiting\\n\", cmd.Process.Pid)\n}", "func (c *DockerContainer) RunCommand(opts RunCommandOptions) (err error) {\n\tcontainerConfig, hostConfig, err := c.getConfig(opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := c.DockerClient.ContainerCreate(\n\t\tc.Ctx,\n\t\t&containerConfig,\n\t\t&hostConfig,\n\t\tnil,\n\t\tnil,\n\t\t\"\",\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.ID = resp.ID\n\n\tif opts.Input != nil {\n\t\tconn, attachErr := c.DockerClient.ContainerAttach(c.Ctx, c.ID, types.ContainerAttachOptions{\n\t\t\tStream: true,\n\t\t\tStdin: true,\n\t\t})\n\n\t\tif attachErr != nil {\n\t\t\treturn attachErr\n\t\t}\n\n\t\tdefer conn.Close()\n\n\t\t// This code is simplified version of docker cli code\n\t\tcErr := make(chan error, 1)\n\n\t\t// Write to stdin asynchronously\n\t\tgo func() {\n\t\t\t_, copyErr := io.Copy(conn.Conn, opts.Input)\n\t\t\tcErr <- copyErr\n\t\t}()\n\n\t\tif err = c.DockerClient.ContainerStart(c.Ctx, c.ID, types.ContainerStartOptions{}); err != nil {\n\t\t\t<-cErr\n\t\t\treturn err\n\t\t}\n\t\t// lock until error is returned from the write channel\n\t\treturn <-cErr\n\t}\n\n\tif err = c.DockerClient.ContainerStart(c.Ctx, c.ID, types.ContainerStartOptions{}); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Debug(\"docker container is started\")\n\treturn nil\n}", "func runCommand(name string, args ...string) (*exec.Cmd, error) {\n\tcmd := exec.Command(name, args...)\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn cmd, err\n\t}\n\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn cmd, err\n\t}\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn cmd, err\n\t}\n\n\tgo io.Copy(os.Stdout, stdout)\n\tgo io.Copy(os.Stderr, stderr)\n\n\treturn cmd, nil\n}", "func (s *sshNativeTask) run() (interface{}, error) {\n\tclient, err := s.newClient()\n\t// create session\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\n\t// run cmd\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tsession.Stdout = &stdout\n\tsession.Stderr = &stderr\n\n\tctx := createContext(s.Host)\n\tif err := session.Run(s.Cmd); err != nil {\n\t\t// if of type ExitError, then its a remote issue, add to code\n\t\twaitmsg, ok := err.(*ssh.ExitError)\n\t\tif ok {\n\t\t\tctx.Response.Code = waitmsg.ExitStatus()\n\t\t} else {\n\t\t\t// else return err\n\t\t\treturn ctx, err\n\t\t}\n\t}\n\n\tctx.Response.Stdout = stdout.String()\n\tctx.Response.Stderr = stderr.String()\n\n\treturn ctx, nil\n}", "func (n *Node) ExecuteCommand(command string) (string, error) {\n\tsigner, err := ssh.ParsePrivateKey(n.SSHKey)\n\tvar output []byte\n\tvar output_string string\n\n\tif err != nil {\n\t\treturn output_string, err\n\t}\n\n\tauths := []ssh.AuthMethod{ssh.PublicKeys([]ssh.Signer{signer}...)}\n\n\tcfg := &ssh.ClientConfig{\n\t\tUser: n.SSHUser,\n\t\tAuth: auths,\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\tcfg.SetDefaults()\n\n\tclient, err := ssh.Dial(\"tcp\", n.PublicIPAddress+\":22\", cfg)\n\tif err != nil {\n\t\treturn output_string, err\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn output_string, err\n\t}\n\n\toutput, err = session.Output(command)\n\toutput_string = string(output)\n\treturn output_string, err\n}", "func (v *vcsCmd) runOutput(dir string, cmd string, keyval ...string) ([]byte, error) {\n\treturn v.run1(dir, cmd, keyval, true)\n}", "func RunCommand(command string, args ...string) ([]byte, error) {\n\tcmd := exec.Command(command, args...)\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn output, err\n\t}\n\treturn output, nil\n}", "func runCommandOutput(dir, command string, args ...string) ([]byte, error) {\n\tcmd := exec.Command(command, args...)\n\tcmd.Dir = dir\n\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"error running '%s':\\n%s\\n\", strings.Join(append([]string{command}, args...), \" \"), output))\n\t}\n\n\treturn output, nil\n}", "func (sh *Shell) runCommandUnix(cmd string, timeout time.Duration) (out string, err error) {\n\n\t// Forge token and command, and send to remote\n\ttoken := randStringBytesRmndr()\n\tforgedCmd := sh.forgeCommand(cmd, token)\n\n\tif err = sh.write(forgedCmd, timeout); err != nil {\n\t\tsh.Log.Error(err)\n\t\treturn\n\t}\n\tsh.Log.Debugf(tui.Green(\"command: \") + tui.Bold(cmd))\n\n\t// 2. Read connection.\n\tdone := make(chan struct{})\n\tprocessed := make(chan string, 1)\n\tgo func(chan struct{}, chan string) {\n\t\tdefer close(done)\n\t\tfor {\n\t\t\tselect {\n\t\t\tdefault:\n\t\t\t\t// Read all output until one/both tokens are found\n\t\t\t\toutput, err := sh.readCommandOuput(cmd, token, sh.tokenIndex)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn // We already logged the error\n\t\t\t\t}\n\n\t\t\t\t// Process output\n\t\t\t\tout, err = sh.processRawLine(output, cmd, token)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn // We already logged the error\n\t\t\t\t}\n\t\t\t\tprocessed <- out\n\t\t\t\treturn\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(done, processed)\n\n\t// We wait either for the response body, or a timeout.\n\tfor {\n\t\tselect {\n\t\tcase out = <-processed:\n\t\t\tsh.Log.Debugf(tui.Dim(\"result: \") + tui.Bold(cmd))\n\t\t\treturn out, nil\n\t\tcase <-time.After(timeout):\n\t\t\tclose(done)\n\t\t\t// We still give out, in case it has something in it still.\n\t\t\treturn out, fmt.Errorf(\"reading command result from conn stream timed out\")\n\t\t}\n\t}\n}", "func RunCommand(command string, args ...string) (string, error) {\n\tbytes, err := exec.Command(command, args...).CombinedOutput()\n\treturn string(bytes), err\n}", "func Run(cmd *exec.Cmd) (*RunResult, error) {\n\trr := &RunResult{Args: cmd.Args}\n\n\tvar outb, errb bytes.Buffer\n\tcmd.Stdout, rr.Stdout = &outb, &outb\n\tcmd.Stderr, rr.Stderr = &errb, &errb\n\n\tstart := time.Now()\n\tklog.V(1).Infof(\"Running: %s\", cmd)\n\terr := cmd.Run()\n\trr.Duration = time.Since(start)\n\n\tif err != nil {\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\trr.ExitCode = exitError.ExitCode()\n\t\t}\n\t}\n\n\tklog.V(1).Infof(\"Completed: %s (duration: %s, exit code: %d, err: %v)\", cmd, rr.Duration, rr.ExitCode, err)\n\tif len(rr.Stderr.Bytes()) > 0 {\n\t\tklog.V(1).Infof(\"stderr:\\n%s\\n\", rr.Stderr.String())\n\t}\n\n\treturn rr, err\n}", "func ExecCommand(ctx *Ctx, cmdAndArgs []string, env map[string]string) {\n\t// Execution time\n\tdtStart := time.Now()\n\n\t// STDOUT pipe size\n\tpipeSize := 0x100\n\n\t// Command & arguments\n\tcommand := cmdAndArgs[0]\n\targuments := cmdAndArgs[1:]\n\tif ctx.CmdDebug > 0 {\n\t\tPrintf(\"%s\\n\", strings.Join(cmdAndArgs, \" \"))\n\t}\n\tcmd := exec.Command(command, arguments...)\n\n\t// Environment setup (if any)\n\tif len(env) > 0 {\n\t\tnewEnv := os.Environ()\n\t\tfor key, value := range env {\n\t\t\tnewEnv = append(newEnv, key+\"=\"+value)\n\t\t}\n\t\tcmd.Env = newEnv\n\t\tif ctx.CmdDebug > 0 {\n\t\t\tPrintf(\"Environment Override: %+v\\n\", env)\n\t\t\tif ctx.CmdDebug > 2 {\n\t\t\t\tPrintf(\"Full Environment: %+v\\n\", newEnv)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Capture STDOUT (non buffered - all at once when command finishes), only used on error and when no buffered/piped version used\n\t// Which means it is used on error when CmdDebug <= 1\n\t// Capture STDERR (non buffered - all at once when command finishes)\n\tvar (\n\t\tstdOut bytes.Buffer\n\t\tstdErr bytes.Buffer\n\t)\n\tcmd.Stderr = &stdErr\n\tif ctx.CmdDebug <= 1 {\n\t\tcmd.Stdout = &stdOut\n\t}\n\n\t// Pipe command's STDOUT during execution (if CmdDebug > 1)\n\t// Or just starts command when no DTDOUT debug\n\tif ctx.CmdDebug > 1 {\n\t\tstdOutPipe, e := cmd.StdoutPipe()\n\t\tFatalOnError(e)\n\t\tFatalOnError(cmd.Start())\n\t\tbuffer := make([]byte, pipeSize, pipeSize)\n\t\tnBytes, e := stdOutPipe.Read(buffer)\n\t\tfor e == nil && nBytes > 0 {\n\t\t\tPrintf(\"%s\", buffer[:nBytes])\n\t\t\tnBytes, e = stdOutPipe.Read(buffer)\n\t\t}\n\t\tif e != io.EOF {\n\t\t\tFatalOnError(e)\n\t\t}\n\t} else {\n\t\tFatalOnError(cmd.Start())\n\t}\n\t// Wait for command to finish\n\terr := cmd.Wait()\n\n\t// If error - then output STDOUT, STDERR and error info\n\tif err != nil {\n\t\tif ctx.CmdDebug <= 1 {\n\t\t\toutStr := stdOut.String()\n\t\t\tif len(outStr) > 0 {\n\t\t\t\tPrintf(\"%v\\n\", outStr)\n\t\t\t}\n\t\t}\n\t\terrStr := stdErr.String()\n\t\tif len(errStr) > 0 {\n\t\t\tPrintf(\"STDERR:\\n%v\\n\", errStr)\n\t\t}\n\t\tFatalOnError(err)\n\t}\n\n\t// If CmdDebug > 1 display STDERR contents as well (if any)\n\tif ctx.CmdDebug > 1 {\n\t\terrStr := stdErr.String()\n\t\tif len(errStr) > 0 {\n\t\t\tPrintf(\"Errors:\\n%v\\n\", errStr)\n\t\t}\n\t}\n\tif ctx.CmdDebug > 0 {\n\t\tdtEnd := time.Now()\n\t\tPrintf(\"%s ... %+v\\n\", strings.Join(cmdAndArgs, \" \"), dtEnd.Sub(dtStart))\n\t}\n}", "func (v *vncCommand) Run() error {\n\tvmPodInfo, err := v.client.GetVMPodInfo(v.podName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't get VM pod info for %q: %v\", v.podName, err)\n\t}\n\n\tvar buffer bytes.Buffer\n\tvirshOutput := bufio.NewWriter(&buffer)\n\texitCode, err := v.client.ExecInContainer(\n\t\tvmPodInfo.VirtletPodName, \"libvirt\", \"kube-system\",\n\t\tnil, virshOutput, os.Stderr,\n\t\t[]string{\"virsh\", \"domdisplay\", vmPodInfo.LibvirtDomainName()},\n\t)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error executing virsh in Virtlet pod %q: %v\", vmPodInfo.VirtletPodName, err)\n\t}\n\tif exitCode != 0 {\n\t\treturn fmt.Errorf(\"virsh returned non-zero exit code %d\", exitCode)\n\t}\n\n\tvirshOutput.Flush()\n\tparts := strings.Split(strings.Trim(buffer.String(), \"\\n\"), \":\")\n\tswitch {\n\tcase len(parts) != 3:\n\t\treturn fmt.Errorf(\"virsh returned %q, while expected to return a value of a form %q\", buffer.String(), \"vnc://127.0.0.1:0\")\n\tcase parts[0] != vncProtocolName:\n\t\treturn fmt.Errorf(\"virsh returned %q as a display protocol instead of expected %q\", parts[0], vncProtocolName)\n\tcase parts[1][:2] != \"//\":\n\t\treturn fmt.Errorf(\"virsh returned %q after first ':' instead of expected %q\", parts[1][:2], \"//\")\n\tcase parts[1][2:] != expectedHost:\n\t\treturn fmt.Errorf(\"virsh returned %q as a display host instead of expected %q\", parts[1], expectedHost)\n\t}\n\n\tdisplayNumber, err := strconv.Atoi(parts[2])\n\tif err != nil || displayNumber < 0 || displayNumber > maxDisplayNumber {\n\t\treturn fmt.Errorf(\"virsh returned %q as a display number which is expected to be in range 0..%d\", parts[2], maxDisplayNumber)\n\t}\n\n\tpf := &ForwardedPort{\n\t\tRemotePort: 5900 + uint16(displayNumber),\n\t\tLocalPort: v.port,\n\t}\n\tstopCh, err := v.client.ForwardPorts(vmPodInfo.VirtletPodName, \"kube-system\", []*ForwardedPort{pf})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error forwarding the vnc port: %v\", err)\n\t}\n\tdefer close(stopCh)\n\n\tfmt.Fprintf(v.output, \"VNC console for pod %q is available on local port %d\\n\", v.podName, pf.LocalPort)\n\tfmt.Fprintf(v.output, \"Press ctrl-c or kill the process stop.\\n\")\n\n\t// if waitForInterrupt is set to false do not wait for interrupt (e.x. in tests).\n\tif v.waitForInterrupt {\n\t\tc := make(chan os.Signal, 2)\n\t\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM)\n\n\t\t<-c\n\t}\n\n\treturn nil\n}", "func InvokeCommand(ip, cmdStr string) (string, error) {\n\t// OpenSSH sessions terminate sporadically when a pty isn't allocated.\n\t// The -t flag doesn't work with OpenSSH on Windows, so we wrap the ssh call\n\t// within a bash session as a workaround, so that a pty is created.\n\tcmd := exec.Command(\"/bin/bash\")\n\tcmd.Stdin = strings.NewReader(fmt.Sprintf(sshTemplate, ip, cmdStr))\n\tout, err := cmd.CombinedOutput()\n\treturn strings.TrimSpace(string(out[:])), err\n}", "func (s *sshSessionExternal) Run(cmd string) error {\n\terr := s.Start(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.Wait()\n}", "func executeFakeCommand(t *testing.T, cmd string, fakeContext *command.Context, continueOnErr bool) string {\n\t// Setup the svcat command\n\tsvcat, _, err := buildCommand(cmd, fakeContext, \"\")\n\tif err != nil {\n\t\tt.Fatalf(\"%+v\", err)\n\t}\n\n\t// Capture all output: stderr and stdout\n\toutput := &bytes.Buffer{}\n\tsvcat.SetOutput(output)\n\n\terr = svcat.Execute()\n\tif err != nil && !continueOnErr {\n\t\tt.Fatalf(\"%+v\", err)\n\t}\n\n\treturn output.String()\n}", "func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\n\tvar b bytes.Buffer // import \"bytes\"\n\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", net.JoinHostPort(addr, \"22\"), config)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stderr = os.Stderr // get output\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\n\t// Finally, run the command\n\tfullCmd := \". ~/.nix-profile/etc/profile.d/nix.sh && cd \" + workDir + \" && nix-shell \" + nixConf + \" --command '\" + cmd + \"'\"\n\tfmt.Println(fullCmd)\n\terr = session.Run(fullCmd)\n\treturn b, err\n}", "func (m *MinikubeRunner) SSH(cmdStr string) (string, error) {\n\tprofileArg := fmt.Sprintf(\"-p=%s\", m.Profile)\n\tpath, _ := filepath.Abs(m.BinaryPath)\n\n\tcmd := exec.Command(path, profileArg, \"ssh\", cmdStr)\n\tLogf(\"SSH: %s\", cmdStr)\n\tstdout, err := cmd.CombinedOutput()\n\tLogf(\"Output: %s\", stdout)\n\tif err, ok := err.(*exec.ExitError); ok {\n\t\treturn string(stdout), err\n\t}\n\treturn string(stdout), nil\n}", "func NewSSHCommand(p *config.KfParams) *cobra.Command {\n\tvar (\n\t\tdisableTTY bool\n\t\tcommand []string\n\t\tcontainer string\n\t)\n\n\tcmd := &cobra.Command{\n\t\tUse: \"ssh APP_NAME\",\n\t\tShort: \"Open a shell on an App instance.\",\n\t\tExample: `\n\t\t# Open a shell to a specific App\n\t\tkf ssh myapp\n\n\t\t# Open a shell to a specific Pod\n\t\tkf ssh pod/myapp-revhex-podhex\n\n\t\t# Start a different command with args\n\t\tkf ssh myapp -c /my/command -c arg1 -c arg2\n\t\t`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tLong: `\n\t\tOpens a shell on an App instance using the Pod exec endpoint.\n\n\t\tThis command mimics CF's SSH command by opening a connection to the\n\t\tKubernetes control plane which spawns a process in a Pod.\n\n\t\tThe command connects to an arbitrary Pod that matches the App's runtime\n\t\tlabels. If you want a specific Pod, use the pod/<podname> notation.\n\n\t\tNOTE: Traffic is encrypted between the CLI and the control plane, and\n\t\tbetween the control plane and Pod. A malicious Kubernetes control plane\n\t\tcould observe the traffic.\n\t\t`,\n\t\tValidArgsFunction: completion.AppCompletionFn(p),\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx := cmd.Context()\n\t\t\tif err := p.ValidateSpaceTargeted(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstreamExec := execstreamer.Get(ctx)\n\n\t\t\tenableTTY := !disableTTY\n\t\t\tappName := args[0]\n\n\t\t\tpodSelector := metav1.ListOptions{}\n\t\t\tif strings.HasPrefix(appName, podPrefix) {\n\t\t\t\tpodName := strings.TrimPrefix(appName, podPrefix)\n\t\t\t\tpodSelector.FieldSelector = fields.OneTermEqualSelector(\"metadata.name\", podName).String()\n\t\t\t} else {\n\t\t\t\tappLabels := v1alpha1.AppComponentLabels(appName, \"app-server\")\n\t\t\t\tpodSelector.LabelSelector = labels.SelectorFromSet(appLabels).String()\n\t\t\t}\n\n\t\t\texecOpts := corev1.PodExecOptions{\n\t\t\t\tContainer: container,\n\t\t\t\tCommand: command,\n\t\t\t\tStdin: true,\n\t\t\t\tStdout: true,\n\t\t\t\tStderr: true,\n\t\t\t\tTTY: enableTTY,\n\t\t\t}\n\n\t\t\tt := term.TTY{\n\t\t\t\tOut: cmd.OutOrStdout(),\n\t\t\t\tIn: cmd.InOrStdin(),\n\t\t\t\tRaw: true,\n\t\t\t}\n\n\t\t\tsizeQueue := t.MonitorSize(t.GetSize())\n\n\t\t\tstreamOpts := remotecommand.StreamOptions{\n\t\t\t\tStdin: cmd.InOrStdin(),\n\t\t\t\tStdout: cmd.OutOrStdout(),\n\t\t\t\tStderr: cmd.ErrOrStderr(),\n\t\t\t\tTty: enableTTY,\n\t\t\t\tTerminalSizeQueue: sizeQueue,\n\t\t\t}\n\n\t\t\t// Set up a TTY locally if it's enabled.\n\t\t\tif fd, isTerm := dockerterm.GetFdInfo(streamOpts.Stdin); isTerm && enableTTY {\n\t\t\t\toriginalState, err := dockerterm.MakeRaw(fd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdefer dockerterm.RestoreTerminal(fd, originalState)\n\t\t\t}\n\n\t\t\treturn streamExec.Stream(ctx, podSelector, execOpts, streamOpts)\n\t\t},\n\t}\n\n\tcmd.Flags().StringArrayVarP(\n\t\t&command,\n\t\t\"command\",\n\t\t\"c\",\n\t\t[]string{\"/bin/bash\"},\n\t\t\"Command to run for the shell. Subsequent definitions will be used as args.\",\n\t)\n\n\tcmd.Flags().StringVar(\n\t\t&container,\n\t\t\"container\",\n\t\tv1alpha1.DefaultUserContainerName,\n\t\t\"Container to start the command in.\",\n\t)\n\n\tcmd.Flags().BoolVarP(\n\t\t&disableTTY,\n\t\t\"disable-pseudo-tty\",\n\t\t\"T\",\n\t\tfalse,\n\t\t\"Don't use a TTY when executing.\",\n\t)\n\n\treturn cmd\n}", "func (ex Exec) ExecuteCommand(command string, args []string) (outStr string, errStr string) {\n\n\tvar logger = log.WithFields(log.Fields{\n\t\t\"command\": command,\n\t\t\"args\": strings.Join(args, \",\"),\n\t})\n\n\tw := &logrusWriter{\n\t\tentry: logger,\n\t}\n\n\tcmd := exec.Command(command, args...)\n\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\tstdoutIn, _ := cmd.StdoutPipe()\n\tstderrIn, _ := cmd.StderrPipe()\n\n\tvar errStdout, errStderr error\n\tstdout := io.MultiWriter(os.Stdout, &stdoutBuf, w)\n\tstderr := io.MultiWriter(os.Stderr, &stderrBuf, w)\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t}).Errorf(\"unable to start the execute the command: %v\", strings.Join(args, \",\"))\n\t\terrStr = err.Error()\n\n\t} else {\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\n\t\tgo func() {\n\t\t\t_, errStdout = io.Copy(stdout, stdoutIn)\n\t\t\twg.Done()\n\t\t}()\n\n\t\t_, errStderr = io.Copy(stderr, stderrIn)\n\t\twg.Wait()\n\n\t\terr = cmd.Wait()\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"err\": err.Error(),\n\t\t\t}).Error(\"Problems waiting for command to complete\")\n\t\t\terrStr = err.Error()\n\t\t\treturn\n\t\t}\n\t\tif errStdout != nil || errStderr != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"err\": err.Error(),\n\t\t\t}).Error(\"failed to capture stdout or stderr\")\n\t\t\terrStr = err.Error()\n\t\t\treturn\n\t\t}\n\n\t\toutStr, errStr = string(stdoutBuf.Bytes()), string(stderrBuf.Bytes())\n\t}\n\treturn\n}", "func RunCommandAndReturn(host string, command string) (string, error) {\n\tvar output bytes.Buffer\n\tRunCommand(host, command, os.Stdin, &output, os.Stderr)\n\treturn output.String(), nil\n}", "func runRemoteCommandTest(t *testing.T, commandType string) {\n\ts, testServer := startTestServer(t)\n\tdefer testServer.Close()\n\n\tvar reqURL *url.URL\n\tstdin, stdout, stderr := true, true, true\n\tcontainerID := testContainerID\n\tswitch commandType {\n\tcase \"exec\":\n\t\tresp, err := s.GetExec(&runtimeapi.ExecRequest{\n\t\t\tContainerId: containerID,\n\t\t\tCmd: []string{\"echo\"},\n\t\t\tStdin: stdin,\n\t\t\tStdout: stdout,\n\t\t\tStderr: stderr,\n\t\t})\n\t\trequire.NoError(t, err)\n\t\treqURL, err = url.Parse(resp.Url)\n\t\trequire.NoError(t, err)\n\tcase \"attach\":\n\t\tresp, err := s.GetAttach(&runtimeapi.AttachRequest{\n\t\t\tContainerId: containerID,\n\t\t\tStdin: stdin,\n\t\t\tStdout: stdout,\n\t\t\tStderr: stderr,\n\t\t})\n\t\trequire.NoError(t, err)\n\t\treqURL, err = url.Parse(resp.Url)\n\t\trequire.NoError(t, err)\n\t}\n\n\twg := sync.WaitGroup{}\n\twg.Add(2)\n\n\tstdinR, stdinW := io.Pipe()\n\tstdoutR, stdoutW := io.Pipe()\n\tstderrR, stderrW := io.Pipe()\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\texec, err := remotecommand.NewSPDYExecutor(&restclient.Config{}, \"POST\", reqURL)\n\t\trequire.NoError(t, err)\n\n\t\topts := remotecommand.StreamOptions{\n\t\t\tStdin: stdinR,\n\t\t\tStdout: stdoutW,\n\t\t\tStderr: stderrW,\n\t\t\tTty: false,\n\t\t}\n\t\trequire.NoError(t, exec.StreamWithContext(context.Background(), opts))\n\t}()\n\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tdoClientStreams(t, commandType, stdinW, stdoutR, stderrR)\n\t}()\n\n\twg.Wait()\n\n\t// Repeat request with the same URL should be a 404.\n\tresp, err := http.Get(reqURL.String())\n\trequire.NoError(t, err)\n\tassert.Equal(t, http.StatusNotFound, resp.StatusCode)\n}", "func (k *OcRunner) RunCommandWithTimeout(command string, timeout string) (stdOut string, stdErr string, exitCode int, err error) {\n\tstdOut, stdErr, exitCode, err = runCommandWithTimeout(command, k.CommandPath, timeout)\n\treturn\n}", "func (i ClusterInstance) Exec(log *logging.Logger, command string) (string, error) {\n\tstdout, err := i.runRemoteCommand(log, command, \"\", false)\n\tif err != nil {\n\t\treturn stdout, maskAny(err)\n\t}\n\treturn stdout, nil\n}", "func (h *Host) Exec(cmd string) error {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tstdout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstderr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.Debugf(\"executing command: %s\", cmd)\n\tif err := session.Start(cmd); err != nil {\n\t\treturn err\n\t}\n\n\tmultiReader := io.MultiReader(stdout, stderr)\n\toutputScanner := bufio.NewScanner(multiReader)\n\n\tfor outputScanner.Scan() {\n\t\tlogrus.Debugf(\"%s: %s\", h.FullAddress(), outputScanner.Text())\n\t}\n\tif err := outputScanner.Err(); err != nil {\n\t\tlogrus.Errorf(\"%s: %s\", h.FullAddress(), err.Error())\n\t}\n\n\treturn nil\n}", "func (cmd *ReceiveCommand) Run() error {\n\tclient, err := cmd.WebsocketClientFactory.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\n\tif err := client.Receive(cmd.Timeout, func(message []byte) error {\n\t\t_, err := cmd.OutputWriter.Write(append(message, '\\n'))\n\t\treturn err\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (cc *Command) RunCommand(obj interface{}, args ...string) error {\n\targs = append(args, \"--conf\")\n\targs = append(args, cc.conf)\n\n\texit, stdout, stderr, err := exec.Run(defaultTimeout, cc.bin, args...)\n\tif err != nil || exit != 0 {\n\t\treturn fmt.Errorf(\"run command failed, err: %v, exit: %d, output: %s\", err, exit, stderr)\n\t}\n\n\tif obj != nil {\n\t\tif err := json.Unmarshal([]byte(stdout), obj); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (e *TranslateCommandExecutor) ExecuteCommandWithOutput(command string, arg ...string) (string, error) {\n\ttransCommand, transArgs := e.Translator(command, arg...)\n\treturn e.Executor.ExecuteCommandWithOutput(transCommand, transArgs...)\n}", "func ExecSSH(ctx context.Context, id Identity, cmd []string, opts plugin.ExecOptions) (plugin.ExecCommand, error) {\n\t// find port, username, etc from .ssh/config\n\tport, err := ssh_config.GetStrict(id.Host, \"Port\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := id.User\n\tif user == \"\" {\n\t\tif user, err = ssh_config.GetStrict(id.Host, \"User\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif user == \"\" {\n\t\tuser = \"root\"\n\t}\n\n\tstrictHostKeyChecking, err := ssh_config.GetStrict(id.Host, \"StrictHostKeyChecking\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconnection, err := sshConnect(id.Host, port, user, strictHostKeyChecking != \"no\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to connect: %s\", err)\n\t}\n\n\t// Run command via session\n\tsession, err := connection.NewSession()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create session: %s\", err)\n\t}\n\n\tif opts.Tty {\n\t\t// sshd only processes signal codes if a TTY has been allocated. So set one up when requested.\n\t\tmodes := ssh.TerminalModes{ssh.ECHO: 0, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400}\n\t\tif err := session.RequestPty(\"xterm\", 40, 80, modes); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to setup a TTY: %v\", err)\n\t\t}\n\t}\n\n\texecCmd := plugin.NewExecCommand(ctx)\n\tsession.Stdin, session.Stdout, session.Stderr = opts.Stdin, execCmd.Stdout(), execCmd.Stderr()\n\n\tif opts.Elevate {\n\t\tcmd = append([]string{\"sudo\"}, cmd...)\n\t}\n\n\tcmdStr := shellquote.Join(cmd...)\n\tif err := session.Start(cmdStr); err != nil {\n\t\treturn nil, err\n\t}\n\texecCmd.SetStopFunc(func() {\n\t\t// Close the session on context cancellation. Copying will block until there's more to read\n\t\t// from the exec output. For an action with no more output it may never return.\n\t\t// If a TTY is setup and the session is still open, send Ctrl-C over before closing it.\n\t\tif opts.Tty {\n\t\t\tactivity.Record(ctx, \"Sent SIGINT on context termination: %v\", session.Signal(ssh.SIGINT))\n\t\t}\n\t\tactivity.Record(ctx, \"Closing session on context termination for %v: %v\", id.Host, session.Close())\n\t})\n\n\t// Wait for session to complete and stash result.\n\tgo func() {\n\t\terr := session.Wait()\n\t\tactivity.Record(ctx, \"Closing session for %v: %v\", id.Host, session.Close())\n\t\texecCmd.CloseStreamsWithError(nil)\n\t\tif err == nil {\n\t\t\texecCmd.SetExitCode(0)\n\t\t} else if exitErr, ok := err.(*ssh.ExitError); ok {\n\t\t\texecCmd.SetExitCode(exitErr.ExitStatus())\n\t\t} else {\n\t\t\texecCmd.SetExitCodeErr(err)\n\t\t}\n\t}()\n\treturn execCmd, nil\n}", "func (m *MockClienter) RunCommand(command string, options go_ssh_client.CommandOptions) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"RunCommand\", command, options)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (ac *activeClient) runCommand(c *ishell.Context) {\n\tcommand := strings.Join(c.Args, \" \")\n\tvar r string\n\targs := shared.Cmd{\n\t\tCmd: command,\n\t\tPowershell: false,\n\t}\n\n\tif err := ac.RPC.Call(\"API.RunCmd\", args, &r); err != nil {\n\t\tc.Println(yellow(\"[\"+ac.Data().Name+\"] \") + red(\"[!] Bad or unkown command:\", err))\n\t}\n\n\tc.Println(r)\n}", "func RunCommand(command string, payloads []string, executor string, timeout int) ([]byte, string, string){\n\tcmd := string(util.Decode(command))\n\tvar status string\n\tvar result []byte\n\tvar pid string\n\tmissingPaths := util.CheckPayloadsAvailable(payloads)\n\tif len(missingPaths) == 0 {\n\t\tresult, status, pid = Executors[executor].Run(cmd, timeout)\n\t} else {\n\t\tresult = []byte(fmt.Sprintf(\"Payload(s) not available: %s\", strings.Join(missingPaths, \", \")))\n\t\tstatus = ERROR_STATUS\n\t\tpid = ERROR_STATUS\n\t}\n\treturn result, status, pid\n}", "func (r *RemoteExecutor) RunWithStdout(name string, args ...string) (string, error) {\n\tcmd := name\n\tfor _, arg := range args {\n\t\tcmd = fmt.Sprintf(\"%s \\\"%s\\\"\", cmd, arg)\n\t}\n\tstdout, stderr, err := r.Client.RunCommand(cmd)\n\t// To fetch the stderr after executing command.\n\tStdErrSudoPassword = string(stderr)\n\tzap.S().Debug(\"Running command \", cmd, \"stdout:\", string(stdout), \"stderr:\", string(stderr))\n\treturn string(stdout), err\n}", "func (cc *CopyCommand) RunCommand() error {\n\tcc.cpOption.recursive, _ = GetBool(OptionRecursion, cc.command.options)\n\tcc.cpOption.force, _ = GetBool(OptionForce, cc.command.options)\n\tcc.cpOption.update, _ = GetBool(OptionUpdate, cc.command.options)\n\tcc.cpOption.threshold, _ = GetInt(OptionBigFileThreshold, cc.command.options)\n\tcc.cpOption.cpDir, _ = GetString(OptionCheckpointDir, cc.command.options)\n\tcc.cpOption.routines, _ = GetInt(OptionRoutines, cc.command.options)\n\tcc.cpOption.ctnu = false\n\tif cc.cpOption.recursive {\n\t\tdisableIgnoreError, _ := GetBool(OptionDisableIgnoreError, cc.command.options)\n\t\tcc.cpOption.ctnu = !disableIgnoreError\n\t}\n\toutputDir, _ := GetString(OptionOutputDir, cc.command.options)\n\tcc.cpOption.snapshotPath, _ = GetString(OptionSnapshotPath, cc.command.options)\n\tcc.cpOption.vrange, _ = GetString(OptionRange, cc.command.options)\n\tcc.cpOption.encodingType, _ = GetString(OptionEncodingType, cc.command.options)\n\tcc.cpOption.meta, _ = GetString(OptionMeta, cc.command.options)\n\tcc.cpOption.tagging, _ = GetString(OptionTagging, cc.command.options)\n\tacl, _ := GetString(OptionACL, cc.command.options)\n\tpayer, _ := GetString(OptionRequestPayer, cc.command.options)\n\tcc.cpOption.partitionInfo, _ = GetString(OptionPartitionDownload, cc.command.options)\n\tcc.cpOption.versionId, _ = GetString(OptionVersionId, cc.command.options)\n\tcc.cpOption.enableSymlinkDir, _ = GetBool(OptionEnableSymlinkDir, cc.command.options)\n\tcc.cpOption.onlyCurrentDir, _ = GetBool(OptionOnlyCurrentDir, cc.command.options)\n\tcc.cpOption.disableDirObject, _ = GetBool(OptionDisableDirObject, cc.command.options)\n\tcc.cpOption.disableAllSymlink, _ = GetBool(OptionDisableAllSymlink, cc.command.options)\n\n\tif cc.cpOption.enableSymlinkDir && cc.cpOption.disableAllSymlink {\n\t\treturn fmt.Errorf(\"--enable-symlink-dir and --disable-all-symlink can't be both exist\")\n\t}\n\n\tvar res bool\n\tres, cc.cpOption.filters = getFilter(os.Args)\n\tif !res {\n\t\treturn fmt.Errorf(\"--include or --exclude does not support format containing dir info\")\n\t}\n\n\tif !cc.cpOption.recursive && len(cc.cpOption.filters) > 0 {\n\t\treturn fmt.Errorf(\"--include or --exclude only work with --recursive\")\n\t}\n\n\tfor k, v := range cc.cpOption.filters {\n\t\tLogInfo(\"filter %d,name:%s,pattern:%s\\n\", k, v.name, v.pattern)\n\t}\n\n\t//get file list\n\tsrcURLList, err := cc.getStorageURLs(cc.command.args[0 : len(cc.command.args)-1])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdestURL, err := StorageURLFromString(cc.command.args[len(cc.command.args)-1], cc.cpOption.encodingType)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\topType := cc.getCommandType(srcURLList, destURL)\n\tif err := cc.checkCopyArgs(srcURLList, destURL, opType); err != nil {\n\t\treturn err\n\t}\n\tif err := cc.checkCopyOptions(opType); err != nil {\n\t\treturn err\n\t}\n\n\tcc.cpOption.options = []oss.Option{}\n\tif cc.cpOption.meta != \"\" {\n\t\theaders, err := cc.command.parseHeaders(cc.cpOption.meta, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttopts, err := cc.command.getOSSOptions(headerOptionMap, headers)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcc.cpOption.options = append(cc.cpOption.options, topts...)\n\t}\n\n\tif cc.cpOption.tagging != \"\" {\n\t\tif opType == operationTypeGet {\n\t\t\treturn fmt.Errorf(\"No need to set tagging for download\")\n\t\t}\n\t\ttags, err := cc.command.getOSSTagging(cc.cpOption.tagging)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttagging := oss.Tagging{Tags: tags}\n\t\tcc.cpOption.options = append(cc.cpOption.options, oss.SetTagging(tagging))\n\t}\n\n\tif acl != \"\" {\n\t\tif opType == operationTypeGet {\n\t\t\treturn fmt.Errorf(\"No need to set ACL for download\")\n\t\t}\n\n\t\tvar opAcl oss.ACLType\n\t\tif opAcl, err = cc.command.checkACL(acl, objectACL); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcc.cpOption.options = append(cc.cpOption.options, oss.ObjectACL(opAcl))\n\t}\n\n\tif cc.cpOption.versionId != \"\" {\n\t\tcc.cpOption.options = append(cc.cpOption.options, oss.VersionId(cc.cpOption.versionId))\n\t}\n\n\tif payer != \"\" {\n\t\tif payer != strings.ToLower(string(oss.Requester)) {\n\t\t\treturn fmt.Errorf(\"invalid request payer: %s, please check\", payer)\n\t\t}\n\t\tcc.cpOption.options = append(cc.cpOption.options, oss.RequestPayer(oss.PayerType(payer)))\n\t\tcc.cpOption.payerOptions = append(cc.cpOption.payerOptions, oss.RequestPayer(oss.PayerType(payer)))\n\t}\n\n\t// init reporter\n\tif cc.cpOption.reporter, err = GetReporter(cc.cpOption.recursive, outputDir, commandLine); err != nil {\n\t\treturn err\n\t}\n\n\t// create checkpoint dir\n\tif err := os.MkdirAll(cc.cpOption.cpDir, 0755); err != nil {\n\n\t\t//\n\t\t//fmt.Printf(\"%s\", cc.cpOption.cpDir)\n\t\treturn err\n\t}\n\n\t// load snapshot\n\tif cc.cpOption.snapshotPath != \"\" {\n\t\tif cc.cpOption.snapshotldb, err = leveldb.OpenFile(cc.cpOption.snapshotPath, nil); err != nil {\n\t\t\treturn fmt.Errorf(\"load snapshot error, reason: %s\", err.Error())\n\t\t}\n\t\tdefer cc.cpOption.snapshotldb.Close()\n\t}\n\n\tif cc.cpOption.partitionInfo != \"\" {\n\t\tif opType == operationTypeGet {\n\t\t\tsliceInfo := strings.Split(cc.cpOption.partitionInfo, \":\")\n\t\t\tif len(sliceInfo) == 2 {\n\t\t\t\tpartitionIndex, err1 := strconv.Atoi(sliceInfo[0])\n\t\t\t\tpartitionCount, err2 := strconv.Atoi(sliceInfo[1])\n\t\t\t\tif err1 != nil || err2 != nil {\n\t\t\t\t\treturn fmt.Errorf(\"parsar OptionPartitionDownload error,value is:%s\", cc.cpOption.partitionInfo)\n\t\t\t\t}\n\t\t\t\tif partitionIndex < 1 || partitionCount < 1 || partitionIndex > partitionCount {\n\t\t\t\t\treturn fmt.Errorf(\"parsar OptionPartitionDownload error,value is:%s\", cc.cpOption.partitionInfo)\n\t\t\t\t}\n\t\t\t\tcc.cpOption.partitionIndex = partitionIndex\n\t\t\t\tcc.cpOption.partitionCount = partitionCount\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"parsar OptionPartitionDownload error,value is:%s\", cc.cpOption.partitionInfo)\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"PutObject or CopyObject doesn't support option OptionPartitionDownload\")\n\t\t}\n\t} else {\n\t\tcc.cpOption.partitionIndex = 0\n\t\tcc.cpOption.partitionCount = 0\n\t}\n\n\tcc.monitor.init(opType)\n\tcc.cpOption.opType = opType\n\n\tchProgressSignal = make(chan chProgressSignalType, 10)\n\tgo cc.progressBar()\n\n\tstartT := time.Now().UnixNano() / 1000 / 1000\n\tswitch opType {\n\tcase operationTypePut:\n\t\tLogInfo(\"begin uploadFiles\\n\")\n\t\terr = cc.uploadFiles(srcURLList, destURL.(CloudURL))\n\tcase operationTypeGet:\n\t\tLogInfo(\"begin downloadFiles\\n\")\n\t\terr = cc.downloadFiles(srcURLList[0].(CloudURL), destURL.(FileURL))\n\tdefault:\n\t\tLogInfo(\"begin copyFiles\\n\")\n\t\terr = cc.copyFiles(srcURLList[0].(CloudURL), destURL.(CloudURL))\n\t}\n\tendT := time.Now().UnixNano() / 1000 / 1000\n\tif endT-startT > 0 {\n\t\taverSpeed := (cc.monitor.transferSize / (endT - startT)) * 1000\n\t\tfmt.Printf(\"\\naverage speed %d(byte/s)\\n\", averSpeed)\n\t\tLogInfo(\"average speed %d(byte/s)\\n\", averSpeed)\n\t}\n\n\tcc.cpOption.reporter.Clear()\n\tckFiles, _ := ioutil.ReadDir(cc.cpOption.cpDir)\n\tif err == nil && len(ckFiles) == 0 {\n\t\tLogInfo(\"begin Remove checkpointDir %s\\n\", cc.cpOption.cpDir)\n\t\tos.RemoveAll(cc.cpOption.cpDir)\n\t}\n\treturn err\n}", "func RunCommandWithOutputLiveWrapper(c *OSCommand, command string, output func(string) string) error {\n\treturn c.RunCommand(command)\n}", "func RunCommandWithOutputLiveWrapper(c *OSCommand, command string, output func(string) string) error {\n\tcmd := c.ExecutableFromString(command)\n\tcmd.Env = append(cmd.Env, \"LANG=en_US.UTF-8\", \"LC_ALL=en_US.UTF-8\")\n\n\tvar stderr bytes.Buffer\n\tcmd.Stderr = &stderr\n\n\tptmx, err := pty.Start(cmd)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tscanner := bufio.NewScanner(ptmx)\n\t\tscanner.Split(scanWordsWithNewLines)\n\t\tfor scanner.Scan() {\n\t\t\ttoOutput := strings.Trim(scanner.Text(), \" \")\n\t\t\t_, _ = ptmx.WriteString(output(toOutput))\n\t\t}\n\t}()\n\n\terr = cmd.Wait()\n\tptmx.Close()\n\tif err != nil {\n\t\treturn errors.New(stderr.String())\n\t}\n\n\treturn nil\n}", "func Run(cmd *exec.Cmd) (*RunResult, error) {\n\trr := &RunResult{Args: cmd.Args}\n\n\tvar outb, errb bytes.Buffer\n\tcmd.Stdout, rr.Stdout = &outb, &outb\n\tcmd.Stderr, rr.Stderr = &errb, &errb\n\n\tstart := time.Now()\n\tklog.V(1).Infof(\"Running: %s\", cmd)\n\terr := cmd.Run()\n\trr.Duration = time.Since(start)\n\n\tif err != nil {\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\trr.ExitCode = exitError.ExitCode()\n\t\t}\n\t\tklog.Errorf(\"cmd.Run returned error: %v\", err)\n\t}\n\n\tklog.V(1).Infof(\"Completed: %s (duration: %s, exit code: %d, err: %v)\", cmd, rr.Duration, rr.ExitCode, err)\n\tif len(rr.Stderr.Bytes()) > 0 {\n\t\tklog.Warningf(\"%s\", rr.Stderr.String())\n\t}\n\n\tif err == nil {\n\t\treturn rr, err\n\t}\n\treturn rr, fmt.Errorf(\"%s: %w, stderr=%s\", cmd.Args, err, errb.String())\n}", "func RunCommand(ctx context.Context, opts *RunCommandOptions) error {\n\tif opts == nil {\n\t\treturn ErrNilOptions\n\t}\n\n\tif opts.Image != \"\" {\n\t\treturn RunCommandInDocker(ctx, opts)\n\t}\n\n\tp, err := syntax.NewParser().Parse(strings.NewReader(opts.Command), \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tenviron := opts.Env\n\tif len(environ) == 0 {\n\t\tenviron = os.Environ()\n\t}\n\n\tr, err := interp.New(\n\t\tinterp.Dir(opts.Dir),\n\t\tinterp.Env(expand.ListEnviron(environ...)),\n\n\t\tinterp.OpenHandler(func(ctx context.Context, path string, flag int, perm os.FileMode) (io.ReadWriteCloser, error) {\n\t\t\tif path == \"/dev/null\" {\n\t\t\t\treturn devNull{}, nil\n\t\t\t}\n\t\t\treturn interp.DefaultOpenHandler()(ctx, path, flag, perm)\n\t\t}),\n\n\t\tinterp.StdIO(opts.Stdin, opts.Stdout, opts.Stderr),\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = r.Run(ctx, p)\n\n\treturn err\n}" ]
[ "0.76657516", "0.7013193", "0.69211733", "0.6870896", "0.6709051", "0.6662063", "0.6636994", "0.66365516", "0.6481154", "0.641191", "0.638604", "0.6359089", "0.62244153", "0.6218016", "0.6202877", "0.6187682", "0.6128655", "0.6123047", "0.6107656", "0.6102932", "0.6080359", "0.60370785", "0.6019991", "0.60100603", "0.59655905", "0.5962173", "0.5955876", "0.59511906", "0.5941558", "0.59358925", "0.5932919", "0.59074116", "0.58599424", "0.5837056", "0.58186996", "0.58035785", "0.5796723", "0.57743734", "0.5768767", "0.56700695", "0.56366307", "0.5630849", "0.5624871", "0.56147504", "0.5576696", "0.55706644", "0.55564463", "0.5551141", "0.5549851", "0.55305624", "0.55142814", "0.5512394", "0.54925114", "0.54675186", "0.5465054", "0.54401916", "0.5438714", "0.5429205", "0.542327", "0.54184854", "0.5414409", "0.53821266", "0.53791183", "0.5376684", "0.5374243", "0.53685653", "0.5367809", "0.53664976", "0.53591347", "0.5344003", "0.53356934", "0.5326108", "0.53254944", "0.5310952", "0.5299318", "0.5298311", "0.529226", "0.5291037", "0.5283872", "0.52785504", "0.5277611", "0.52625656", "0.52582014", "0.52556115", "0.52528155", "0.5238326", "0.52364945", "0.5236348", "0.52325803", "0.52316606", "0.5228719", "0.5225458", "0.5222095", "0.5217167", "0.520536", "0.52042603", "0.51996773", "0.519867", "0.5197277", "0.5195657" ]
0.70666355
1
RunCommandWithOutput is a wrapper around the SSH client to run a command abstracts the SSH connection details from the EC2 client interface RunCommandWithOutput provides the stdout and stderr from the command
func (ins *EC2RemoteClient) RunCommandWithOutput(cmd string) (exitStatus int, stdoutBuf bytes.Buffer, stderrBuf bytes.Buffer, err error) { exitStatus, stdoutBuf, stderrBuf, err = ins.cmdClient.RunCommandWithOutput(cmd) return exitStatus, stdoutBuf, stderrBuf, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *Host) ExecWithOutput(cmd string) (string, error) {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer session.Close()\n\n\toutput, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\treturn strings.TrimSpace(string(output)), nil\n}", "func (sc *sshclient) RunWithResults(address string, command string) (string, error) {\n\tclient, err := ssh.Dial(\"tcp\", address, sc.config)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not connect to address %s:%v \", address, err)\n\t}\n\n\t// Each ClientConn can support multiple interactive sessions,\n\t// represented by a Session.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not create session at address %s:%v \", address, err)\n\t}\n\tdefer session.Close()\n\n\tresultdata, err := session.Output(command)\n\tif err != nil {\n\t\treturn string(resultdata), fmt.Errorf(\"Command '%s' at address %s produced an error:%v \", command, address, err)\n\t}\n\n\treturn string(resultdata), nil\n}", "func runCommandWithOutput(execCmd *exec.Cmd) (string, int, error) {\n\tresult := icmd.RunCmd(transformCmd(execCmd))\n\treturn result.Combined(), result.ExitCode, result.Error\n}", "func (client *SSHClient) Run(command string, stdout io.Writer, stderr io.Writer) error {\n\tsession, err := client.cryptoClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer session.Close()\n\n\tsession.Stdout = stdout\n\tsession.Stderr = stderr\n\n\treturn session.Run(command)\n}", "func RunCommandAndStoreOutput(vmi *v1.VirtualMachineInstance, command string, timeout time.Duration) (string, error) {\n\tvirtClient := kubevirt.Client()\n\n\topts := &kubecli.SerialConsoleOptions{ConnectionTimeout: timeout}\n\tstream, err := virtClient.VirtualMachineInstance(vmi.Namespace).SerialConsole(vmi.Name, opts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tconn := stream.AsConn()\n\tdefer conn.Close()\n\n\t_, err = fmt.Fprintf(conn, \"%s\\n\", command)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tscanner := bufio.NewScanner(conn)\n\tif !skipInput(scanner) {\n\t\treturn \"\", fmt.Errorf(\"failed to run [%s] at VMI %s (skip input)\", command, vmi.Name)\n\t}\n\tif !scanner.Scan() {\n\t\treturn \"\", fmt.Errorf(\"failed to run [%s] at VMI %s\", command, vmi.Name)\n\t}\n\treturn scanner.Text(), nil\n}", "func (s *SSHer) Run(cmd string) (output []byte, err error) {\n\tvar session *ssh.Session\n\tif session, err = s.client.NewSession(); err != nil {\n\t\treturn\n\t}\n\tdefer session.Close()\n\n\tif output, err = session.CombinedOutput(cmd); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (self *Client) RunCommand(cmd *Command) (string, []error) {\n var (\n output string\n errs []error\n )\n\n //- Compile our \"Valid\" and \"Error\" REGEX patterns, if not done already.\n // This will allow us to reuse it with compiling it every time.\n cmd.CompileCmdRegex()\n\n\tcmd.LogCommandConfig() //- DEBUG\n\n //- \"Write\" the command to the remote SSH session.\n self.StdinPipe.Write([]byte(cmd.Exec))\n\n //- Loop until we've gotten all output from the remote SSH Session.\n done := false\n lastError := \"\"\n for done != true {\n b, _ := self.StdoutPipe.ReadByte()\n output = output + string(b)\n\n //- Check for errors, if we have any ErrorPatterns to test.\n if len(cmd.ErrorPatterns) > 0 {\n if matchedError, errDesc := testRegex(output, cmd.ErrorRegex); matchedError == true {\n if lastError != errDesc {\n errs = append(errs, fmt.Errorf(\"Matched error pattern: %s\", errDesc))\n lastError = errDesc\n }\n }\n }\n\n //- Check for Valid output. Continue retrieving bytes until we see a\n // \"valid\" pattern.\n if done, _ = testRegex(output, cmd.ValidRegex); done == true {\n //- Make sure there isn't any more left to read.\n//\t\t\ttime.Sleep(time.Second)\n if buff := self.StdoutPipe.Buffered(); buff != 0 {\n done = false\n }\n }\n }\n\n return output, errs\n}", "func ExecuteWithOutput(cmd *exec.Cmd) (outStr string, err error) {\n\t// connect to stdout and stderr for filtering purposes\n\terrPipe, err := cmd.StderrPipe()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"cmd\": cmd.Args,\n\t\t}).Fatal(\"Couldn't connect to command's stderr\")\n\t}\n\toutPipe, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"cmd\": cmd.Args,\n\t\t}).Fatal(\"Couldn't connect to command's stdout\")\n\t}\n\t_ = bufio.NewReader(errPipe)\n\toutReader := bufio.NewReader(outPipe)\n\n\t// start the command and filter the output\n\tif err = cmd.Start(); err != nil {\n\t\treturn \"\", err\n\t}\n\toutScanner := bufio.NewScanner(outReader)\n\tfor outScanner.Scan() {\n\t\toutStr += outScanner.Text() + \"\\n\"\n\t\tif log.GetLevel() == log.DebugLevel {\n\t\t\tfmt.Println(outScanner.Text())\n\t\t}\n\t}\n\terr = cmd.Wait()\n\treturn outStr, err\n}", "func RunSSHCommand(SSHHandle *ssh.Client, cmd string, sudo bool, bg bool, logger *log.Logger) (retCode int, stdout, stderr []string) {\n\tlogger.Println(\"Running cmd \" + cmd)\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\tsshSession, err := SSHHandle.NewSession()\n\tif err != nil {\n\t\tlogger.Printf(\"SSH session creation failed! %s\", err)\n\t\treturn -1, nil, nil\n\t}\n\tdefer sshSession.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err = sshSession.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\tlogger.Println(\"SSH session Pty creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tsshOut, err := sshSession.StdoutPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StdoutPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\tsshErr, err := sshSession.StderrPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StderrPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tshout := io.MultiWriter(&stdoutBuf, (*LogWriter)(logger))\n\tssherr := io.MultiWriter(&stderrBuf, (*LogWriter)(logger))\n\n\tgo func() {\n\t\tio.Copy(shout, sshOut)\n\t}()\n\tgo func() {\n\n\t\tio.Copy(ssherr, sshErr)\n\t}()\n\n\tif bg {\n\t\tcmd = \"nohup sh -c \\\"\" + cmd + \" 2>&1 >/dev/null </dev/null & \\\"\"\n\t} else {\n\t\tcmd = \"sh -c \\\"\" + cmd + \"\\\"\"\n\t}\n\n\tif sudo {\n\t\tcmd = SudoCmd(cmd)\n\t}\n\n\tlogger.Println(\"Running command : \" + cmd)\n\tif err = sshSession.Run(cmd); err != nil {\n\t\tlogger.Println(\"failed command : \" + cmd)\n\t\tswitch v := err.(type) {\n\t\tcase *ssh.ExitError:\n\t\t\tretCode = v.Waitmsg.ExitStatus()\n\t\tdefault:\n\t\t\tretCode = -1\n\t\t}\n\t} else {\n\t\tlogger.Println(\"sucess command : \" + cmd)\n\t\tretCode = 0\n\t}\n\n\tstdout = strings.Split(stdoutBuf.String(), \"\\n\")\n\tstderr = strings.Split(stderrBuf.String(), \"\\n\")\n\tlogger.Println(stdout)\n\tlogger.Println(stderr)\n\tlogger.Println(\"Return code : \" + strconv.Itoa(retCode))\n\n\treturn retCode, stdout, stderr\n\n}", "func (client *Client) Run(command string, silent bool) (output string, err error) {\n\tkeys := ssh.Auth{\n\t\tKeys: []string{client.PrivateKeyFile},\n\t}\n\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \"SSH-2.0-MyCustomClient-1.0\", client.Port, &keys, nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\tif !silent {\n\t\tlog.Printf(\"Running: ssh -i \\\"%s\\\" %s@%s %s\", client.PrivateKeyFile, client.User, client.Host, command)\n\t}\n\tr, _, err := sshterm.Start(command)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to start command - %s\", err)\n\t}\n\tsshterm.Wait()\n\tresponse, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to read response - %s\", err)\n\t}\n\treturn string(response), nil\n}", "func (e *SSHExecutor) Execute(cmd string, sudo bool, timeout ...time.Duration) ([]byte, []byte, error) {\n\t// try to acquire root permission\n\tif e.Sudo || sudo {\n\t\tcmd = fmt.Sprintf(\"sudo -H -u root bash -c \\\"%s\\\"\", cmd)\n\t}\n\n\t// set a basic PATH in case it's empty on login\n\tcmd = fmt.Sprintf(\"PATH=$PATH:/usr/bin:/usr/sbin %s\", cmd)\n\n\tif e.Locale != \"\" {\n\t\tcmd = fmt.Sprintf(\"export LANG=%s; %s\", e.Locale, cmd)\n\t}\n\n\t// run command on remote host\n\t// default timeout is 60s in easyssh-proxy\n\tif len(timeout) == 0 {\n\t\ttimeout = append(timeout, executeDefaultTimeout)\n\t}\n\n\tstdout, stderr, done, err := e.Config.Run(cmd, timeout...)\n\n\tzap.L().Info(\"SSHCommand\",\n\t\tzap.String(\"host\", e.Config.Server),\n\t\tzap.String(\"port\", e.Config.Port),\n\t\tzap.String(\"cmd\", cmd),\n\t\tzap.Error(err),\n\t\tzap.String(\"stdout\", stdout),\n\t\tzap.String(\"stderr\", stderr))\n\n\tif err != nil {\n\t\tbaseErr := ErrSSHExecuteFailed.\n\t\t\tWrap(err, \"Failed to execute command over SSH for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t\tif len(stdout) > 0 || len(stderr) > 0 {\n\t\t\toutput := strings.TrimSpace(strings.Join([]string{stdout, stderr}, \"\\n\"))\n\t\t\tbaseErr = baseErr.\n\t\t\t\tWithProperty(cliutil.SuggestionFromFormat(\"Command output on remote host %s:\\n%s\\n\",\n\t\t\t\t\te.Config.Server,\n\t\t\t\t\tcolor.YellowString(output)))\n\t\t}\n\t\treturn []byte(stdout), []byte(stderr), baseErr\n\t}\n\n\tif !done { // timeout case,\n\t\treturn []byte(stdout), []byte(stderr), ErrSSHExecuteTimedout.\n\t\t\tWrap(err, \"Execute command over SSH timedout for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t}\n\n\treturn []byte(stdout), []byte(stderr), nil\n}", "func (s *SSHRunner) RunCmd(cmd *exec.Cmd) (*RunResult, error) {\n\tif cmd.Stdin != nil {\n\t\treturn nil, fmt.Errorf(\"SSHRunner does not support stdin - you could be the first to add it\")\n\t}\n\n\trr := &RunResult{Args: cmd.Args}\n\tklog.Infof(\"Run: %v\", rr.Command())\n\n\tvar outb, errb io.Writer\n\tstart := time.Now()\n\n\tif cmd.Stdout == nil {\n\t\tvar so bytes.Buffer\n\t\toutb = io.MultiWriter(&so, &rr.Stdout)\n\t} else {\n\t\toutb = io.MultiWriter(cmd.Stdout, &rr.Stdout)\n\t}\n\n\tif cmd.Stderr == nil {\n\t\tvar se bytes.Buffer\n\t\terrb = io.MultiWriter(&se, &rr.Stderr)\n\t} else {\n\t\terrb = io.MultiWriter(cmd.Stderr, &rr.Stderr)\n\t}\n\n\tsess, err := s.session()\n\tif err != nil {\n\t\treturn rr, errors.Wrap(err, \"NewSession\")\n\t}\n\n\tdefer func() {\n\t\tif err := sess.Close(); err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tklog.Errorf(\"session close: %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = teeSSH(sess, shellquote.Join(cmd.Args...), outb, errb)\n\telapsed := time.Since(start)\n\n\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\trr.ExitCode = exitError.ExitCode()\n\t}\n\t// Decrease log spam\n\tif elapsed > (1 * time.Second) {\n\t\tklog.Infof(\"Completed: %s: (%s)\", rr.Command(), elapsed)\n\t}\n\tif err == nil {\n\t\treturn rr, nil\n\t}\n\n\treturn rr, fmt.Errorf(\"%s: %v\\nstdout:\\n%s\\nstderr:\\n%s\", rr.Command(), err, rr.Stdout.String(), rr.Stderr.String())\n}", "func (v *vcsCmd) runOutput(dir string, cmd string, keyval ...string) ([]byte, error) {\n\treturn v.run1(dir, cmd, keyval, true)\n}", "func SSHRunCommand(client *ssh.Client, cmd string) (string, error) {\n\tsession, err := client.NewSession()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer session.Close()\n\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tsession.Stdout = &stdout\n\tsession.Stderr = &stderr\n\n\terr = session.Run(cmd)\n\n\toutput := stdout.String() + stderr.String()\n\n\tif err != nil {\n\t\treturn output, fmt.Errorf(\"failed to execute command \\\"%s\\\" via SSH client: %s\", cmd, err)\n\t}\n\n\treturn output, nil\n}", "func RunWithOutput(cmd *exec.Cmd, name string, settings ...SettingsFunc) string {\n\tr := DefaultRunner()\n\treturn r.RunWithOutput(cmd, name, settings...)\n}", "func (ins *EC2RemoteClient) RunCommand(cmd string) (exitStatus int, err error) {\n\texitStatus, err = ins.cmdClient.RunCommand(cmd)\n\treturn exitStatus, err\n}", "func (svc *SSHService) Run(hostName, cmd string) (int, string, string, error) {\n\tvar stdOut, stdErr string\n\tvar retCode int\n\tvar err error\n\n\thostSvc := NewHostService(svc.provider)\n\thost, err := hostSvc.Get(hostName)\n\tif err != nil {\n\t\treturn 0, \"\", \"\", logicErrf(err, \"no host found with name or id '%s'\", hostName)\n\t}\n\n\t// retrieve ssh config to perform some commands\n\tssh, err := svc.GetConfig(host)\n\n\tif err != nil {\n\t\treturn 0, \"\", \"\", infraErr(err)\n\t}\n\n\terr = retry.WhileUnsuccessfulDelay1SecondWithNotify(\n\t\tfunc() error {\n\t\t\tretCode, stdOut, stdErr, err = svc.run(ssh, cmd)\n\t\t\treturn err\n\t\t},\n\t\t2*time.Minute,\n\t\tfunc(t retry.Try, v Verdict.Enum) {\n\t\t\tif v == Verdict.Retry {\n\t\t\t\tlog.Printf(\"Remote SSH service on host '%s' isn't ready, retrying...\\n\", hostName)\n\t\t\t}\n\t\t},\n\t)\n\tif err != nil {\n\t\terr = infraErr(err)\n\t}\n\n\treturn retCode, stdOut, stdErr, err\n}", "func (e *TranslateCommandExecutor) ExecuteCommandWithOutput(command string, arg ...string) (string, error) {\n\ttransCommand, transArgs := e.Translator(command, arg...)\n\treturn e.Executor.ExecuteCommandWithOutput(transCommand, transArgs...)\n}", "func ExecCommandOutput(cmd string, args []string) (string, int, error) {\n\tLogDebug.Print(\"ExecCommandOutput called with \", cmd, args)\n\tc := exec.Command(cmd, args...)\n\tvar b bytes.Buffer\n\tc.Stdout = &b\n\tc.Stderr = &b\n\n\tif err := c.Start(); err != nil {\n\t\treturn \"\", 999, err\n\t}\n\n\t//TODO we could set a timeout here if needed\n\n\terr := c.Wait()\n\tout := string(b.Bytes())\n\n\tfor _, line := range strings.Split(out, \"\\n\") {\n\t\tLogDebug.Print(\"out :\", line)\n\t}\n\n\tif err != nil {\n\t\t//check the rc of the exec\n\t\tif badnews, ok := err.(*exec.ExitError); ok {\n\t\t\tif status, ok := badnews.Sys().(syscall.WaitStatus); ok {\n\t\t\t\treturn out, status.ExitStatus(), fmt.Errorf(\"rc=%d\", status.ExitStatus())\n\t\t\t}\n\t\t} else {\n\t\t\treturn out, 888, fmt.Errorf(\"unknown error\")\n\t\t}\n\t}\n\n\treturn out, 0, nil\n}", "func RunCommandWithOutputLiveWrapper(c *OSCommand, command string, output func(string) string) error {\n\treturn c.RunCommand(command)\n}", "func RunCommandWithOutputLiveWrapper(c *OSCommand, command string, output func(string) string) error {\n\tcmd := c.ExecutableFromString(command)\n\tcmd.Env = append(cmd.Env, \"LANG=en_US.UTF-8\", \"LC_ALL=en_US.UTF-8\")\n\n\tvar stderr bytes.Buffer\n\tcmd.Stderr = &stderr\n\n\tptmx, err := pty.Start(cmd)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tscanner := bufio.NewScanner(ptmx)\n\t\tscanner.Split(scanWordsWithNewLines)\n\t\tfor scanner.Scan() {\n\t\t\ttoOutput := strings.Trim(scanner.Text(), \" \")\n\t\t\t_, _ = ptmx.WriteString(output(toOutput))\n\t\t}\n\t}()\n\n\terr = cmd.Wait()\n\tptmx.Close()\n\tif err != nil {\n\t\treturn errors.New(stderr.String())\n\t}\n\n\treturn nil\n}", "func (c *Communicator) run(cmd *exec.Cmd, remote *packer.RemoteCmd, stdin_w io.WriteCloser, outputFile *os.File, exitCodePath string) {\n\t// For Docker, remote communication must be serialized since it\n\t// only supports single execution.\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\t// Clean up after ourselves by removing our temporary files\n\tdefer os.Remove(outputFile.Name())\n\tdefer os.Remove(exitCodePath)\n\n\t// Tail the output file and send the data to the stdout listener\n\ttail, err := tail.TailFile(outputFile.Name(), tail.Config{\n\t\tPoll: true,\n\t\tReOpen: true,\n\t\tFollow: true,\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"Error tailing output file: %s\", err)\n\t\tremote.SetExited(254)\n\t\treturn\n\t}\n\tdefer tail.Stop()\n\n\t// Modify the remote command so that all the output of the commands\n\t// go to a single file and so that the exit code is redirected to\n\t// a single file. This lets us determine both when the command\n\t// is truly complete (because the file will have data), what the\n\t// exit status is (because Docker loses it because of the pty, not\n\t// Docker's fault), and get the output (Docker bug).\n\tremoteCmd := fmt.Sprintf(\"(%s) >%s 2>&1; echo $? >%s\",\n\t\tremote.Command,\n\t\tfilepath.Join(c.ContainerDir, filepath.Base(outputFile.Name())),\n\t\tfilepath.Join(c.ContainerDir, filepath.Base(exitCodePath)))\n\n\t// Start the command\n\tlog.Printf(\"Executing in container %s: %#v\", c.ContainerId, remoteCmd)\n\tif err := cmd.Start(); err != nil {\n\t\tlog.Printf(\"Error executing: %s\", err)\n\t\tremote.SetExited(254)\n\t\treturn\n\t}\n\n\tgo func() {\n\t\tdefer stdin_w.Close()\n\n\t\t// This sleep needs to be here because of the issue linked to below.\n\t\t// Basically, without it, Docker will hang on reading stdin forever,\n\t\t// and won't see what we write, for some reason.\n\t\t//\n\t\t// https://github.com/dotcloud/docker/issues/2628\n\t\ttime.Sleep(2 * time.Second)\n\n\t\tstdin_w.Write([]byte(remoteCmd + \"\\n\"))\n\t}()\n\n\t// Start a goroutine to read all the lines out of the logs. These channels\n\t// allow us to stop the go-routine and wait for it to be stopped.\n\tstopTailCh := make(chan struct{})\n\tdoneCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(doneCh)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-tail.Dead():\n\t\t\t\treturn\n\t\t\tcase line := <-tail.Lines:\n\t\t\t\tif remote.Stdout != nil {\n\t\t\t\t\tremote.Stdout.Write([]byte(line.Text + \"\\n\"))\n\t\t\t\t} else {\n\t\t\t\t\tlog.Printf(\"Command stdout: %#v\", line.Text)\n\t\t\t\t}\n\t\t\tcase <-time.After(2 * time.Second):\n\t\t\t\t// If we're done, then return. Otherwise, keep grabbing\n\t\t\t\t// data. This gives us a chance to flush all the lines\n\t\t\t\t// out of the tailed file.\n\t\t\t\tselect {\n\t\t\t\tcase <-stopTailCh:\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar exitRaw []byte\n\tvar exitStatus int\n\tvar exitStatusRaw int64\n\terr = cmd.Wait()\n\tif exitErr, ok := err.(*exec.ExitError); ok {\n\t\texitStatus = 1\n\n\t\t// There is no process-independent way to get the REAL\n\t\t// exit status so we just try to go deeper.\n\t\tif status, ok := exitErr.Sys().(syscall.WaitStatus); ok {\n\t\t\texitStatus = status.ExitStatus()\n\t\t}\n\n\t\t// Say that we ended, since if Docker itself failed, then\n\t\t// the command must've not run, or so we assume\n\t\tgoto REMOTE_EXIT\n\t}\n\n\t// Wait for the exit code to appear in our file...\n\tlog.Println(\"Waiting for exit code to appear for remote command...\")\n\tfor {\n\t\tfi, err := os.Stat(exitCodePath)\n\t\tif err == nil && fi.Size() > 0 {\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\n\t// Read the exit code\n\texitRaw, err = ioutil.ReadFile(exitCodePath)\n\tif err != nil {\n\t\tlog.Printf(\"Error executing: %s\", err)\n\t\texitStatus = 254\n\t\tgoto REMOTE_EXIT\n\t}\n\n\texitStatusRaw, err = strconv.ParseInt(string(bytes.TrimSpace(exitRaw)), 10, 0)\n\tif err != nil {\n\t\tlog.Printf(\"Error executing: %s\", err)\n\t\texitStatus = 254\n\t\tgoto REMOTE_EXIT\n\t}\n\texitStatus = int(exitStatusRaw)\n\tlog.Printf(\"Executed command exit status: %d\", exitStatus)\n\nREMOTE_EXIT:\n\t// Wait for the tail to finish\n\tclose(stopTailCh)\n\t<-doneCh\n\n\t// Set the exit status which triggers waiters\n\tremote.SetExited(exitStatus)\n}", "func (this Scanner) executeCommand(cmd string, session *ssh.Session) (string, error) {\n\t//Runs CombinedOutput, which takes cmd and returns stderr and stdout of the command\n\tout, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Convert our output to a string\n\ttmpOut := string(out)\n\ttmpOut = strings.Replace(tmpOut, \"\\n\", \"<br>\", -1)\n\n\t// Return a string version of our result\n\treturn tmpOut, nil\n}", "func executeWithOutput(cmd string, args ...string) string {\n\tout, err := exec.Command(cmd, args...).Output()\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\treturn string(out)\n}", "func execCmdWithOutput(arg0 string, args ...string) (string, error) {\n\tcmd := exec.Command(arg0, args...)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif cmd_err := cmd.Start(); cmd_err != nil {\n\t\treturn \"\", cmd_err\n\t}\n\n\toutput, err_out := ioutil.ReadAll(stdout)\n\tif err_out != nil {\n\t\treturn \"\", err_out\n\t}\n\n\treturn string(output), nil\n}", "func (c *Client) Run(ctx context.Context, cmds []*Command) error {\n\turl := c.Host + \":\" + c.Port\n\tclient, err := ssh.Dial(\"tcp\", url, c.Sshconfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in ssh.Dial to %v %w\", url, err)\n\t}\n\n\tdefer client.Close()\n\tsession, err := client.NewSession()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in client.NewSession to %v %w\", url, err)\n\t}\n\tdefer session.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err := session.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\treturn fmt.Errorf(\"error in session.RequestPty to %v %w\", url, err)\n\t}\n\n\tw, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in session.StdinPipe to %v %w\", url, err)\n\t}\n\tr, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in session.StdoutPipe to %v %w\", url, err)\n\t}\n\tin, out := listener(w, r, c.Prompt)\n\tif err := session.Start(\"/bin/sh\"); err != nil {\n\t\treturn fmt.Errorf(\"error in session.Start to %v %w\", url, err)\n\t}\n\n\t<-out // ignore login output\n\tfor _, cmd := range cmds {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.New(\"canceled by context\")\n\n\t\tdefault:\n\t\t\tlogf(cmd.OutputLevel, \"[%v]: cmd [%v] starting...\", c.Host, cmd.Input)\n\n\t\t\tin <- cmd\n\t\t\terr := cmd.wait(ctx, out)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[%v]: Error in cmd [%v] at waiting %w\", c.Host, cmd.Input, err)\n\t\t\t}\n\n\t\t\tif outputs, ok := cmd.output(); ok {\n\t\t\t\tfor _, output := range outputs {\n\t\t\t\t\tfmt.Println(output)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdoNext, err := cmd.Callback(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[%v]: Error in cmd [%v] Callback %w\", c.Host, cmd.Input, err)\n\t\t\t}\n\n\t\t\tif doNext && cmd.NextCommand != nil {\n\t\t\t\tnextCmd := cmd.NextCommand(cmd)\n\n\t\t\t\tlogf(nextCmd.OutputLevel, \"[%v]: next cmd [%v] starting...\", c.Host, nextCmd.Input)\n\n\t\t\t\tin <- nextCmd\n\t\t\t\terr = nextCmd.wait(ctx, out)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"[%v]: Error in next cmd [%v] at waiting %w\", c.Host, cmd.Input, err)\n\t\t\t\t}\n\n\t\t\t\tif outputs, ok := nextCmd.output(); ok {\n\t\t\t\t\tfor _, output := range outputs {\n\t\t\t\t\t\tfmt.Println(output)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t_, err := nextCmd.Callback(nextCmd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"[%v]: Error in next cmd [%v] Callback %w\", c.Host, nextCmd.Input, err)\n\t\t\t\t}\n\n\t\t\t\tlogf(nextCmd.OutputLevel, \"[%v]: next cmd [%v] done\", c.Host, nextCmd.Input)\n\n\t\t\t}\n\n\t\t\tlogf(cmd.OutputLevel, \"[%v]: cmd [%v] done\", c.Host, cmd.Input)\n\t\t}\n\t}\n\tsession.Close()\n\n\treturn nil\n}", "func runWithOutput(ctx context.Context, state *core.BuildState, label core.AnnotatedOutputLabel, args []string, outputMode process.OutputMode, remote, env, detach, inTmp bool, dir string) error {\n\treturn process.RunWithOutput(outputMode, label.String(), func() ([]byte, error) {\n\t\tout, _, err := run(ctx, state, label, args, true, outputMode != process.Default, remote, env, detach, inTmp, dir, \"\")\n\t\treturn out, err\n\t})\n}", "func (client *SSHClient) run(command string, resultdir string, sink *bufio.ReadWriter) error {\n\ts := &ssh.Session{}\n\terr := errors.New(\"\")\n\n\tif s, err = client.create(); err != nil {\n\t\treturn err\n\t}\n\tdefer s.Close()\n\n\tso, _ := s.StdoutPipe()\n\tif resultdir != \"\" {\n\t\tresultfile := strings.Replace(command, \" \", \"_\", -1)\n\t\tresultfile = strings.Replace(resultfile, \"/\", \"-\", -1)\n\t\tresultfile = strings.Replace(resultfile, \".\", \"\", -1)\n\t\trfname := filepath.Join(resultdir, resultfile)\n\t\trf := &os.File{}\n\t\tif rf, err = os.Create(rfname); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer rf.Close()\n\t\tgo io.Copy(rf, so)\n\t\terr = s.Run(command)\n\t\treturn err\n\t} else {\n\t\tgo io.Copy(sink, so)\n\t}\n\treturn nil\n}", "func (fs *Fs) ExecCommandOutput(name string, args ...string) ([]byte, error) {\n\treturn exec.Command(name, args...).Output() // #nosec G204\n}", "func runCommandOutput(dir, command string, args ...string) ([]byte, error) {\n\tcmd := exec.Command(command, args...)\n\tcmd.Dir = dir\n\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"error running '%s':\\n%s\\n\", strings.Join(append([]string{command}, args...), \" \"), output))\n\t}\n\n\treturn output, nil\n}", "func ExecuteWithOutput(s string, obj interface{}, settings ...SettingsFunc) string {\n\tr := DefaultRunner()\n\treturn r.ExecuteWithOutput(s, obj, settings...)\n}", "func (s *sshNativeTask) run() (interface{}, error) {\n\tclient, err := s.newClient()\n\t// create session\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\n\t// run cmd\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tsession.Stdout = &stdout\n\tsession.Stderr = &stderr\n\n\tctx := createContext(s.Host)\n\tif err := session.Run(s.Cmd); err != nil {\n\t\t// if of type ExitError, then its a remote issue, add to code\n\t\twaitmsg, ok := err.(*ssh.ExitError)\n\t\tif ok {\n\t\t\tctx.Response.Code = waitmsg.ExitStatus()\n\t\t} else {\n\t\t\t// else return err\n\t\t\treturn ctx, err\n\t\t}\n\t}\n\n\tctx.Response.Stdout = stdout.String()\n\tctx.Response.Stderr = stderr.String()\n\n\treturn ctx, nil\n}", "func (svc *SSHService) run(ssh *system.SSHConfig, cmd string) (int, string, string, error) {\n\t// Create the command\n\tsshCmd, err := ssh.Command(cmd)\n\tif err != nil {\n\t\treturn 0, \"\", \"\", err\n\t}\n\treturn sshCmd.Run()\n}", "func Run(c *cli.Context) {\n\tport, err := osExpandAndVerifyGlobal(c, \"port\")\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tcommand, err := osExpandAndVerify(c, \"command\")\n\tif err != nil {\n\t\tfail(err)\n\t}\n\thost, err := osExpandAndVerify(c, \"host\")\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tuser, err := osExpandAndVerify(c, \"user\")\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tconnection := c.String(\"connection\")\n\tif connection == ansible.ConnectionWinRM {\n\t\tpassword, err := osExpandAndVerify(c, \"password\")\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t}\n\t\terr = winrm.RemoteWinRmCommand(user, password, host, port, command, nil, nil, \"\")\n\t} else {\n\t\tprivatekey, err := osExpandAndVerify(c, \"privatekey\")\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t}\n\t\tenvVars := make(map[string]string)\n\t\terr = ssh.RemoteSSHCommand(user, privatekey, host, port, command, envVars)\n\t}\n\tif err != nil {\n\t\tlog.Err(\"Failed: %v\", err)\n\t}\n}", "func (s *SSHClient) Run(command string) (string, error) {\n\tif err := s.createClient(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn s.run(command)\n}", "func RunCmdWithOutput(cmdName string, cmdArgs []string) ([]byte, error) {\n\tcmdLog := fmt.Sprintf(\"%s %s\", cmdName, strings.Join(cmdArgs, \" \"))\n\tout, err := exec.Command(cmdName, cmdArgs...).Output()\n\tif err != nil {\n\t\treturn []byte(\"\"), fmt.Errorf(\"failed execute command; cmd=%s; err=%v\", cmdLog, err)\n\t}\n\treturn out, nil\n}", "func RunCommandAndReturn(host string, command string) (string, error) {\n\tvar output bytes.Buffer\n\tRunCommand(host, command, os.Stdin, &output, os.Stderr)\n\treturn output.String(), nil\n}", "func (t *TestRunner) execDebuggableWithOutput(name string, args []string, env []string, afterStart func() string, chToStdin <-chan string) ([]byte, error) {\n\tdebug := isLaunchedByDebugger\n\tif debug {\n\t\targs = append(args, \"--await-continue\")\n\t}\n\tc := exec.Command(name, args...)\n\n\t// add environment variables\n\tif env != nil {\n\t\tc.Env = env\n\t}\n\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tstdin, err := c.StdinPipe()\n\tif err != nil {\n\t\treturn make([]byte, 0), err\n\t}\n\n\tc.Stdout = &stdout\n\tc.Stderr = &stderr\n\n\t// instead of err := c.Run(), we do the following\n\trunErr := c.Start()\n\tif runErr == nil {\n\t\tdefer func() {\n\t\t\t_ = c.Process.Kill() // in case we never finish c.Wait() below, and get panicked or killed\n\t\t}()\n\n\t\tif debug {\n\t\t\tbeginAzCopyDebugging(stdin)\n\t\t}\n\n\t\t// perform a specific post-start action\n\t\tif afterStart != nil {\n\t\t\tmsgToApp := afterStart() // perform a local action, here in the test suite, that may optionally produce a message to send to the the app\n\t\t\tif msgToApp != \"\" {\n\t\t\t\t_, _ = stdin.Write([]byte(msgToApp + \"\\n\")) // TODO: maybe change this to use chToStdIn\n\t\t\t}\n\t\t}\n\n\t\t// allow on-going messages to stdin\n\t\tif chToStdin != nil {\n\t\t\tgo func() {\n\t\t\t\tfor {\n\t\t\t\t\tmsg, ok := <-chToStdin\n\t\t\t\t\tif ok {\n\t\t\t\t\t\t_, _ = stdin.Write([]byte(msg + \"\\n\"))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\n\t\t// wait for completion\n\t\trunErr = c.Wait()\n\t}\n\n\t// back to normal exec.Cmd.Output() processing\n\tif runErr != nil {\n\t\tif ee, ok := runErr.(*exec.ExitError); ok {\n\t\t\tee.Stderr = stderr.Bytes()\n\t\t}\n\t}\n\treturn stdout.Bytes(), runErr\n}", "func (c *SSHConnection) RunCommand(cmd string) ([]byte, error) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.lastUsed = time.Now()\n\n\tif c.client == nil {\n\t\treturn nil, errors.New(\"not connected\")\n\t}\n\n\tsession, err := c.client.NewSession()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not open session\")\n\t}\n\tdefer session.Close()\n\n\tvar b = &bytes.Buffer{}\n\tsession.Stdout = b\n\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not run command\")\n\t}\n\n\treturn b.Bytes(), nil\n}", "func (client *ExternalClient) Output(pty bool, args ...string) (string, error) {\n\targs = append(client.BaseArgs, args...)\n\tcmd := getSSHCmd(client.BinaryPath, pty, args...)\n\t// for pseudo-tty and sudo to work correctly Stdin must be set to os.Stdin\n\tif pty {\n\t\tcmd.Stdin = os.Stdin\n\t}\n\toutput, err := cmd.CombinedOutput()\n\treturn string(output), err\n}", "func ExecuteShellAndReturnOutput(\n\tcliConfig schema.CliConfiguration,\n\tcommand string,\n\tname string,\n\tdir string,\n\tenv []string,\n\tdryRun bool,\n) (string, error) {\n\tvar b bytes.Buffer\n\n\tu.LogDebug(cliConfig, \"\\nExecuting command:\")\n\tu.LogDebug(cliConfig, command)\n\n\tif dryRun {\n\t\treturn \"\", nil\n\t}\n\n\terr := shellRunner(command, name, dir, env, &b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn b.String(), nil\n}", "func runCommand(command string, commandPath string) (stdOut string, stdErr string, exitCode int, err error) {\n\treturn runCommandWithTimeout(command, commandPath, \"1h\")\n}", "func (r *Remoter) Output(waitCtx context.Context, cmd string) (string, []byte, error) {\n\t// cannot use defer close(r.wait()) , defer may delay called,\n\t// and cause a race condition\n\tclt := r.clt\n\tssn, err := clt.NewSession()\n\tif err != nil {\n\t\treturn cmd, nil, err\n\t}\n\t// stdout stderr all in one\n\t// BUG: there will have a race condition\n\t// sub routine and this routine operate same r.closer\n\tnoNeedWait, waitGrp := r.wait(waitCtx)\n\tb, err := ssn.CombinedOutput(cmd)\n\t// tell sub routine to exit\n\tclose(noNeedWait)\n\t// wait sub routine exit\n\twaitGrp.Wait()\n\t_ = ssn.Close()\n\treturn cmd, b, err\n}", "func (runner *SSHRunner) Run(command string) (string, error) {\n\treturn runner.runSSHCommandFromDriver(command, false)\n}", "func RunCommand(host string, command string, reader io.Reader, stdOut io.Writer, stdErr io.Writer) error {\n\tsession, err := SSHSession(host)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err := session.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\tsession.Close()\n\t\treturn fmt.Errorf(\"request for pseudo terminal failed: %s\", err)\n\t}\n\n\tsession.Stdout = stdOut\n\tsession.Stdin = reader\n\tsession.Stderr = stdErr\n\terr = session.Run(command)\n\n\treturn nil\n}", "func (v *VCS) runOutput(dir string, cmdline string, kv ...string) ([]byte, error) {\n\treturn v.run1(dir, cmdline, kv, true)\n}", "func (client *Client) Run() {\n\tret, val, msg := client.executeCommand()\n\tlog.Printf(\"Execute command result: %v\", ret)\n\tlog.Printf(\"Execute command value: %v\", val)\n\tlog.Printf(\"Execute command message: %v\", msg)\n}", "func (s *SSH) Run(command string) (outStr string, err error) {\n\toutChan, doneChan, err := s.stream(command)\n\tif err != nil {\n\t\treturn outStr, err\n\t}\n\n\tdone := false\n\tfor !done {\n\t\tselect {\n\t\tcase <-doneChan:\n\t\t\tdone = true\n\t\tcase line := <-outChan:\n\t\t\t// TODO ew.. this is nasty\n\t\t\toutStr += line + \"\\n\"\n\n\t\t}\n\t}\n\n\treturn outStr, err\n}", "func (e *remoteExecutor) Execute(command []string, in io.Reader, out, errOut io.Writer) error {\n\tklog.V(3).Infof(\"Remote executor running command: %s\", strings.Join(command, \" \"))\n\texecOptions := &kexec.ExecOptions{\n\t\tStreamOptions: kexec.StreamOptions{\n\t\t\tNamespace: e.Namespace,\n\t\t\tPodName: e.PodName,\n\t\t\tContainerName: e.ContainerName,\n\t\t\tIOStreams: genericclioptions.IOStreams{\n\t\t\t\tIn: in,\n\t\t\t\tOut: out,\n\t\t\t\tErrOut: errOut,\n\t\t\t},\n\t\t\tStdin: in != nil,\n\t\t},\n\t\tExecutor: &kexec.DefaultRemoteExecutor{},\n\t\tPodClient: e.Client.CoreV1(),\n\t\tConfig: e.Config,\n\t\tCommand: command,\n\t}\n\terr := execOptions.Validate()\n\tif err != nil {\n\t\tklog.V(4).Infof(\"Error from remote command validation: %v\", err)\n\t\treturn err\n\t}\n\terr = execOptions.Run()\n\tif err != nil {\n\t\tklog.V(4).Infof(\"Error from remote execution: %v\", err)\n\t}\n\treturn err\n}", "func (k *SshCMD)RemoteRun(user string, addr string, cmd string) (string, error) {\n\t// privateKey could be read from a file, or retrieved from another storage\n\t// source, such as the Secret Service / GNOME Keyring\n\t// Authentication\n\tconfig := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(k.rsa),\n\t\t\t//ssh.Password(\"jack2017\"),\n\t\t},\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t\t//alternatively, you could use a password\n\t\t/*\n\t\t\tAuth: []ssh.AuthMethod{\n\t\t\t\tssh.Password(\"PASSWORD\"),\n\t\t\t},\n\t\t*/\n\t}\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", addr+\":22222\", config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer session.Close()\n\tvar b bytes.Buffer // import \"bytes\"\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\tsession.Stderr = os.Stderr\n\t// Finally, run the command\n\terr = session.Run(cmd)\n\treturn b.String(), err\n}", "func Exec(command string) (stdOut, stdErr *bytes.Buffer, err error) {\n\tc := cleanCommand(command)\n\tcmd := exec.Command(cli.Name, c...)\n\n\tvar stdOutBytes, stdErrBytes []byte\n\tvar errStdout, errStderr error\n\tstdOutIn, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tstdErrIn, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfmt.Printf(\"$ %s \\n\", strings.Join(cmd.Args, \" \"))\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tstdOutBytes, errStdout = copyAndCapture(os.Stdout, stdOutIn)\n\t\twg.Done()\n\t}()\n\tstdErrBytes, errStderr = copyAndCapture(os.Stderr, stdErrIn)\n\twg.Wait()\n\terr = cmd.Wait()\n\tif err != nil {\n\t\tfmt.Println(stdOut.String())\n\t\tfmt.Println(stdErr.String())\n\t}\n\tif errStdout != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to capture stdout: %w\", errStdout)\n\t}\n\tif errStderr != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to capture stderr: %w\", errStderr)\n\t}\n\treturn bytes.NewBuffer(stdOutBytes), bytes.NewBuffer(stdErrBytes), err\n}", "func (r *RemoteExecutor) RunWithStdout(name string, args ...string) (string, error) {\n\tcmd := name\n\tfor _, arg := range args {\n\t\tcmd = fmt.Sprintf(\"%s \\\"%s\\\"\", cmd, arg)\n\t}\n\tstdout, stderr, err := r.Client.RunCommand(cmd)\n\t// To fetch the stderr after executing command.\n\tStdErrSudoPassword = string(stderr)\n\tzap.S().Debug(\"Running command \", cmd, \"stdout:\", string(stdout), \"stderr:\", string(stderr))\n\treturn string(stdout), err\n}", "func (cmd *EnvironmentCommand) executeCommand(client *ssh.Client, cmdLine string) error {\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tcmd.currentSession = session\n\tsession.Stdin = os.Stdin\n\tif cmd.SuppressOutput {\n\t\tsession.Stdout = &cmd.OutputBuffer\n\t\tsession.Stderr = &cmd.ErrorBuffer\n\t} else {\n\t\tsession.Stdout = io.MultiWriter(os.Stdout, &cmd.OutputBuffer)\n\t\tsession.Stderr = io.MultiWriter(os.Stderr, &cmd.ErrorBuffer)\n\t}\n\treturn session.Run(cmdLine)\n}", "func (sshConfig *SSHConfig) Run(cmd string) (string, error) {\n\tb, err1 := sshConfig.rawRun(cmd)\n\treturn string(b), err1\n}", "func testCommand(t *testing.T, client ssh.Client, command string) error {\n\t// To avoid mixing the output streams of multiple commands running in\n\t// parallel tests, we combine stdout and stderr on the remote host, and\n\t// capture stdout and write it to the test log here.\n\tstdout := new(bytes.Buffer)\n\tif err := client.Run(command+\" 2>&1\", stdout, os.Stderr); err != nil {\n\t\tt.Logf(\"`%s` failed with %v:\\n%s\", command, err, stdout.String())\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *SSHClient) Execute(host, cmd string) (string, error) {\n\thostname := fmt.Sprintf(\"%s.%s.%s:%d\", host, s.projectID, DropletDomain, defaultSSHPort)\n\n\tpemBytes, err := s.repo.GetKey(s.projectID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(pemBytes)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"parse key failed: %v\", err)\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: \"workshop\",\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"dialing\")\n\tconn, err := ssh.Dial(\"tcp\", hostname, config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"creating session\")\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer session.Close()\n\n\tvar buf bytes.Buffer\n\tsession.Stdout = &buf\n\n\ts.log.WithFields(logrus.Fields{\n\t\t\"hostname\": hostname,\n\t\t\"cmd\": cmd}).\n\t\tInfo(\"running command\")\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\ts.log.WithField(\"output\", buf.String()).WithError(err).Error(\"ssh client run returned non zero result\")\n\t\treturn \"\", fmt.Errorf(\"%s\\n%s\", err, buf.String())\n\t}\n\n\treturn buf.String(), nil\n}", "func ConnectCommandOutput(args []string) string {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"At least one argument must be supplied to use this command\")\n\t}\n\n\tcs := strings.Join(args, \" \")\n\tpn := conf.GetConfig().Tokaido.Project.Name + \".tok\"\n\n\tr := utils.CommandSubstitution(\"ssh\", []string{\"-q\", \"-o UserKnownHostsFile=/dev/null\", \"-o StrictHostKeyChecking=no\", pn, \"-C\", cs}...)\n\n\tutils.DebugString(r)\n\n\treturn r\n}", "func (gitCommand *GitCommand) RunAndGetOutput() []byte {\n\tstdout, err := gitCommand.Run(false)\n\tif err != nil {\n\t\treturn []byte{}\n\t}\n\n\tdata, err := ioutil.ReadAll(stdout)\n\tif err != nil {\n\t\treturn []byte{}\n\t}\n\n\treturn data\n}", "func Run(cmd *exec.Cmd) (*RunResult, error) {\n\trr := &RunResult{Args: cmd.Args}\n\n\tvar outb, errb bytes.Buffer\n\tcmd.Stdout, rr.Stdout = &outb, &outb\n\tcmd.Stderr, rr.Stderr = &errb, &errb\n\n\tstart := time.Now()\n\tklog.V(1).Infof(\"Running: %s\", cmd)\n\terr := cmd.Run()\n\trr.Duration = time.Since(start)\n\n\tif err != nil {\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\trr.ExitCode = exitError.ExitCode()\n\t\t}\n\t}\n\n\tklog.V(1).Infof(\"Completed: %s (duration: %s, exit code: %d, err: %v)\", cmd, rr.Duration, rr.ExitCode, err)\n\tif len(rr.Stderr.Bytes()) > 0 {\n\t\tklog.V(1).Infof(\"stderr:\\n%s\\n\", rr.Stderr.String())\n\t}\n\n\treturn rr, err\n}", "func Run(cmd *exec.Cmd) (string, error) {\n\tklog.V(4).Infof(\"Executing: %s\", cmd)\n\n\tr, w := io.Pipe()\n\tcmd.Stdout = w\n\tcmd.Stderr = w\n\tbuffer := new(bytes.Buffer)\n\tr2 := io.TeeReader(r, buffer)\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tscanner := bufio.NewScanner(r2)\n\t\tfor scanner.Scan() {\n\t\t\tklog.V(5).Infof(\"%s: %s\", cmd.Path, scanner.Text())\n\t\t}\n\t}()\n\terr := cmd.Run()\n\tw.Close()\n\twg.Wait()\n\tklog.V(4).Infof(\"%s terminated, with %d bytes of output and error %v\", cmd.Path, buffer.Len(), err)\n\n\toutput := string(buffer.Bytes())\n\tif err != nil {\n\t\terr = fmt.Errorf(\"command %q failed: %v\\nOutput: %s\", cmd, err, output)\n\t}\n\treturn output, err\n}", "func Run(cl *cli.CliClient, args ...string) (string, string, error) {\n\toldArgs := os.Args\n\tos.Args = append([]string{\"scootcl\"}, args...)\n\tdefer func() {\n\t\tos.Args = oldArgs\n\t}()\n\n\toutput := captureOutput()\n\tdefer output.Reset()\n\n\terr := cl.Exec()\n\tstdout, stderr := output.WaitAndReset() // Reset early so we can use stdout/stderr and write to uncaptured stdout/stderr\n\treturn stdout, stderr, err\n}", "func (r *RemoteShell) Execute(ctx context.Context, cmd string) ([]byte, error) {\n\tsshCmd, err := r.conn.CommandContext(ctx, cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sshCmd.CombinedOutput()\n}", "func (c *Command) RunCommand(instanceIDs []*string) (err error) {\n\tinput := ssm.SendCommandInput{\n\t\tTimeoutSeconds: aws.Int64(30),\n\t\tInstanceIds: instanceIDs,\n\t\tMaxConcurrency: &c.MaxConcurrency,\n\t\tMaxErrors: &c.MaxErrors,\n\t\tDocumentName: aws.String(\"AWS-RunShellScript\"),\n\t\tComment: &c.Comment,\n\t\tCloudWatchOutputConfig: &ssm.CloudWatchOutputConfig{\n\t\t\tCloudWatchLogGroupName: &c.LogGroup,\n\t\t\tCloudWatchOutputEnabled: aws.Bool(true),\n\t\t},\n\t}\n\n\tinput.Parameters = map[string][]*string{\n\t\t\"commands\": aws.StringSlice([]string{strings.Join(c.Command, \" \")}),\n\t\t\"executionTimeout\": aws.StringSlice([]string{fmt.Sprintf(\"%d\", c.ExecutionTimeout)}),\n\t}\n\n\toutput, err := ssmSvc.SendCommand(&input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error invoking SendCommand: %s\", err)\n\t}\n\n\tc.SSMCommand = output.Command\n\n\t// Wait for each instance to finish\n\tvar wg sync.WaitGroup\n\n\tfor _, instanceID := range instanceIDs {\n\t\twg.Add(1)\n\t\tgo Stream(&c.LogGroup, output.Command.CommandId, instanceID)\n\t\tgo WaitForInstance(output.Command.CommandId, instanceID, &wg)\n\t}\n\n\twg.Wait()\n\n\ttime.Sleep(10 * time.Second)\n\treturn nil\n}", "func rcRunCommand(ctx context.Context, in Params) (out Params, err error) {\n\tcommand, err := in.GetString(\"command\")\n\tif err != nil {\n\t\tcommand = \"\"\n\t}\n\n\tvar opt = map[string]string{}\n\terr = in.GetStructMissingOK(\"opt\", &opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar arg = []string{}\n\terr = in.GetStructMissingOK(\"arg\", &arg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturnType, err := in.GetString(\"returnType\")\n\tif err != nil {\n\t\treturnType = \"COMBINED_OUTPUT\"\n\t}\n\n\tvar httpResponse http.ResponseWriter\n\thttpResponse, err = in.GetHTTPResponseWriter()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"response object is required\\n\" + err.Error())\n\t}\n\n\tvar allArgs = []string{}\n\tif command != \"\" {\n\t\t// Add the command e.g.: ls to the args\n\t\tallArgs = append(allArgs, command)\n\t}\n\t// Add all from arg\n\tallArgs = append(allArgs, arg...)\n\n\t// Add flags to args for e.g. --max-depth 1 comes in as { max-depth 1 }.\n\t// Convert it to [ max-depth, 1 ] and append to args list\n\tfor key, value := range opt {\n\t\tif len(key) == 1 {\n\t\t\tallArgs = append(allArgs, \"-\"+key)\n\t\t} else {\n\t\t\tallArgs = append(allArgs, \"--\"+key)\n\t\t}\n\t\tallArgs = append(allArgs, value)\n\t}\n\n\t// Get the path for the current executable which was used to run rclone.\n\tex, err := os.Executable()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcmd := exec.CommandContext(ctx, ex, allArgs...)\n\n\tif returnType == \"COMBINED_OUTPUT\" {\n\t\t// Run the command and get the output for error and stdout combined.\n\n\t\tout, err := cmd.CombinedOutput()\n\n\t\tif err != nil {\n\t\t\treturn Params{\n\t\t\t\t\"result\": string(out),\n\t\t\t\t\"error\": true,\n\t\t\t}, nil\n\t\t}\n\t\treturn Params{\n\t\t\t\"result\": string(out),\n\t\t\t\"error\": false,\n\t\t}, nil\n\t} else if returnType == \"STREAM_ONLY_STDOUT\" {\n\t\tcmd.Stdout = httpResponse\n\t} else if returnType == \"STREAM_ONLY_STDERR\" {\n\t\tcmd.Stderr = httpResponse\n\t} else if returnType == \"STREAM\" {\n\t\tcmd.Stdout = httpResponse\n\t\tcmd.Stderr = httpResponse\n\t} else {\n\t\treturn nil, fmt.Errorf(\"unknown returnType %q\", returnType)\n\t}\n\n\terr = cmd.Run()\n\treturn nil, err\n}", "func RemoteRun(user string, addr string, port int, sshKey []byte, cmd string) (string, string, error) {\n\t// Create the Signer for this private key.\n\tsigner, err := ssh.ParsePrivateKey(sshKey)\n\tif err != nil {\n\t\treturn \"\", \"error in ssh.ParsePrivateKey()\", err\n\t}\n\n\t// Authentication\n\tconfig := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: func(string, net.Addr, ssh.PublicKey) error { return nil },\n\t}\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", addr, port), config)\n\tif err != nil {\n\t\treturn \"\", \"error in ssh.Dial()\", err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn \"\", \"error in NewSession()\", err\n\t}\n\tdefer session.Close()\n\tvar bOut, bErr bytes.Buffer\n\tsession.Stdout = &bOut // get output\n\tsession.Stderr = &bErr // get error\n\n\terr = session.Run(cmd)\n\treturn bOut.String(), bErr.String(), err\n}", "func (r *MockRunner) RunOut(cmd *exec.Cmd) ([]byte, error) {\n\targs := r.Called(cmd)\n\treturn args.Get(0).([]byte), args.Error(1)\n}", "func (c *Client) Exec(cmd string) ([]byte, error) {\n\tsession, err := c.SSHClient.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\n\treturn session.CombinedOutput(cmd)\n}", "func GetCommandOutput(command string, timeout time.Duration, arg ...string) ([]byte, error) {\n\tvar err error\n\tvar stdOut bytes.Buffer\n\tvar stdErr bytes.Buffer\n\tvar c = make(chan []byte)\n\tcmd := exec.Command(command, arg...)\n\tcmd.Stdout = &stdOut\n\tcmd.Stderr = &stdErr\n\tif err = cmd.Start(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%s %s\", err.Error(), stdErr.String())\n\t}\n\tgo func() {\n\t\terr = cmd.Wait()\n\t\tc <- stdOut.Bytes()\n\t}()\n\ttime.AfterFunc(timeout, func() {\n\t\tcmd.Process.Kill()\n\t\terr = errors.New(\"Maxruntime exceeded\")\n\t\tc <- nil\n\t})\n\tresponse := <-c\n\tif err != nil {\n\t\tfmt.Errorf(\"%s %s\", err.Error(), stdErr.String())\n\t}\n\treturn response, nil\n}", "func (s WebSSHBenchmark) runCommand(ctx context.Context, tc *client.TeleportClient, webSess *webSession, host, command string) error {\n\tstream, err := connectToHost(ctx, tc, webSess, host)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tdefer stream.Close()\n\n\tif _, err := io.WriteString(stream, command); err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tif _, err := io.Copy(tc.Stdout, stream); err != nil && !errors.Is(err, io.EOF) {\n\t\treturn trace.Wrap(err)\n\t}\n\n\treturn nil\n}", "func (r *Remoter) Run(waitCtx context.Context, cmds []string, stdout io.Writer, stderr io.Writer) error {\n\n\tclt := r.clt\n\tssn, err := clt.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer ssn.Close()\n\n\t// not know why use this\n\t// keep it for someday I know this\n\t//modes := ssh.TerminalModes{\n\t// ssh.ECHO: 0, // disable echoing\n\t// ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t// ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t//}\n\t//_ = modes\n\t//if err := ssn.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t// return nil\n\t//}\n\n\tshellInput, err := ssn.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tssn.Stdout = stdout\n\tssn.Stderr = stderr\n\terr = ssn.Shell()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, cmd := range cmds {\n\t\t_, err = fmt.Fprintf(shellInput, \"%s\\n\", cmd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// we must have exit to return `Wait()`\n\t_, err = fmt.Fprintf(shellInput, \"exit\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t// all command after exit will not run\n\tnoNeedWait, waitGrp := r.wait(waitCtx)\n\terr = ssn.Wait()\n\tclose(noNeedWait)\n\twaitGrp.Wait()\n\treturn err\n}", "func Run(cmd *exec.Cmd) (*RunResult, error) {\n\trr := &RunResult{Args: cmd.Args}\n\n\tvar outb, errb bytes.Buffer\n\tcmd.Stdout, rr.Stdout = &outb, &outb\n\tcmd.Stderr, rr.Stderr = &errb, &errb\n\n\tstart := time.Now()\n\tklog.V(1).Infof(\"Running: %s\", cmd)\n\terr := cmd.Run()\n\trr.Duration = time.Since(start)\n\n\tif err != nil {\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\trr.ExitCode = exitError.ExitCode()\n\t\t}\n\t\tklog.Errorf(\"cmd.Run returned error: %v\", err)\n\t}\n\n\tklog.V(1).Infof(\"Completed: %s (duration: %s, exit code: %d, err: %v)\", cmd, rr.Duration, rr.ExitCode, err)\n\tif len(rr.Stderr.Bytes()) > 0 {\n\t\tklog.Warningf(\"%s\", rr.Stderr.String())\n\t}\n\n\tif err == nil {\n\t\treturn rr, err\n\t}\n\treturn rr, fmt.Errorf(\"%s: %w, stderr=%s\", cmd.Args, err, errb.String())\n}", "func ExecuteWithInheritedStdOutAndStdErr(command *exec.Cmd, currentWorkingDirectory string) error {\n\tpreCommandExecute(command, currentWorkingDirectory)\n\n\t// not an error - command error output printed to out stdout (like logging)\n\tcommand.Stdout = os.Stderr\n\tcommand.Stderr = os.Stderr\n\terr := command.Run()\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\treturn nil\n}", "func Run(connectAs string, connectTo string, key string) {\n\ttarget := connectAs + \"@\" + connectTo\n\tlog.Info(\"Connecting as \" + target)\n\n\texecutable := \"sshpass\"\n\tparams := []string{\n\t\t\"-p\", key, \"ssh\", \"-o\", \"StrictHostKeyChecking=no\", \"-t\", \"-t\", target,\n\t}\n\tlog.Infof(\"Launching: %s %s\", executable, strings.Join(params, \" \"))\n\n\tif log.GetLevel() == log.DebugLevel {\n\t\tfor i, param := range params {\n\t\t\tif param == \"ssh\" {\n\t\t\t\ti = i + 1\n\t\t\t\t// Yes: this is crazy, but this inserts an element into a slice\n\t\t\t\tparams = append(params[:i], append([]string{\"-v\"}, params[i:]...)...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tcmd := exec.Command(executable, params...)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\terr := cmd.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd.Wait()\n\tlog.Infof(\"Just ran subprocess %d, exiting\\n\", cmd.Process.Pid)\n}", "func (h *Host) Exec(cmd string) error {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tstdout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstderr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.Debugf(\"executing command: %s\", cmd)\n\tif err := session.Start(cmd); err != nil {\n\t\treturn err\n\t}\n\n\tmultiReader := io.MultiReader(stdout, stderr)\n\toutputScanner := bufio.NewScanner(multiReader)\n\n\tfor outputScanner.Scan() {\n\t\tlogrus.Debugf(\"%s: %s\", h.FullAddress(), outputScanner.Text())\n\t}\n\tif err := outputScanner.Err(); err != nil {\n\t\tlogrus.Errorf(\"%s: %s\", h.FullAddress(), err.Error())\n\t}\n\n\treturn nil\n}", "func execute(cmd string, in []byte) Result {\n\tcommand := exec.Command(\"bash\", \"-c\", cmd)\n\n\tstdin, err := command.StdinPipe()\n\n\tif err != nil {\n\t\treturn Result{Text: make([]byte, 0), Err: err}\n\t}\n\n\tstdout, err := command.StdoutPipe()\n\n\tif err != nil {\n\t\treturn Result{Text: make([]byte, 0), Err: err}\n\t}\n\n\tstderr, err := command.StderrPipe()\n\n\tif err != nil {\n\t\treturn Result{Text: make([]byte, 0), Err: err}\n\t}\n\n\t// run the command\n\n\tif err := command.Start(); err != nil {\n\t\treturn Result{Text: make([]byte, 0), Err: err}\n\t}\n\n\tdefer func() {\n\t\t// releases the resources\n\t\tcommand.Wait()\n\t}()\n\n\t// write in to stdin\n\tstdin.Write(in)\n\tstdin.Close()\n\n\t// read stdout as a result\n\tresult, err := ioutil.ReadAll(stdout)\n\tstdout.Close()\n\n\tif err != nil {\n\t\treturn Result{Text: make([]byte, 0), Err: err}\n\t}\n\n\t// read stderr for possible errors\n\tmsgs, err := ioutil.ReadAll(stderr)\n\tstderr.Close()\n\n\tif len(msgs) > 0 {\n\t\treturn Result{Text: msgs, Err: errors.New(\"stderr\")}\n\t}\n\n\tif err != nil {\n\t\treturn Result{Text: make([]byte, 0), Err: err}\n\t}\n\n\treturn Result{Text: result, Err: nil}\n}", "func RunOut(cmd *exec.Cmd) ([]byte, error) {\n\treturn DefaultRunner.RunOut(cmd)\n}", "func (m *MinikubeRunner) RunCommand(cmdStr string, failError bool, waitForRun ...bool) (string, string, error) {\n\tprofileArg := fmt.Sprintf(\"-p=%s \", m.Profile)\n\tcmdStr = profileArg + cmdStr\n\tcmdArgs := strings.Split(cmdStr, \" \")\n\tpath, _ := filepath.Abs(m.BinaryPath)\n\n\tcmd := exec.Command(path, cmdArgs...)\n\tLogf(\"Run: %s\", cmd.Args)\n\tstdout, stderr, err := m.teeRun(cmd, waitForRun...)\n\tif err != nil {\n\t\texitCode := \"\"\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\texitCode = string(exitError.Stderr)\n\t\t}\n\t\terrMsg := fmt.Sprintf(\"Error RunCommand : %s \\n\\t Begin RunCommand log block ---> \\n\\t With Profile: %s \\n\\t With ExitCode: %q \\n\\t With STDOUT %s \\n\\t With STDERR %s \\n\\t <--- End of RunCommand log block\", cmdStr, m.Profile, exitCode, stdout, stderr)\n\t\tif failError {\n\t\t\tm.T.Fatalf(errMsg)\n\t\t} else {\n\t\t\tm.T.Logf(errMsg)\n\t\t}\n\t}\n\treturn stdout, stderr, err\n}", "func RunWithOutputE(cmd *exec.Cmd, name string, settings ...SettingsFunc) (out string, err error) {\n\tr := DefaultRunner()\n\treturn r.RunWithOutputE(cmd, name, settings...)\n}", "func (*CmdRunner) RunOut(cmd *exec.Cmd) ([]byte, error) {\n\tfmt.Println(strings.Join(cmd.Args, \" \"))\n\treturn cmd.CombinedOutput()\n}", "func (t *TestCluster) SSH(m platform.Machine, cmd string) ([]byte, error) {\n\tvar stdout, stderr []byte\n\tvar err error\n\tf := func() {\n\t\tstdout, stderr, err = m.SSH(cmd)\n\t}\n\n\terrMsg := fmt.Sprintf(\"ssh: %s\", cmd)\n\t// If f does not before the test timeout, the RunWithExecTimeoutCheck\n\t// will end this goroutine and mark the test as failed\n\tt.H.RunWithExecTimeoutCheck(f, errMsg)\n\tif len(stderr) > 0 {\n\t\tfor _, line := range strings.Split(string(stderr), \"\\n\") {\n\t\t\tt.Log(line)\n\t\t}\n\t}\n\treturn stdout, err\n}", "func executeCommandCapturingStdout(args ...string) (string, string) {\n\n\t// We substitute our own pipe for stdout to collect the terminal output\n\t// but must be careful to always restore stadt and close the pripe files.\n\toriginalStdout := os.Stdout\n\treadFile, writeFile, err := os.Pipe()\n\tif err != nil {\n\t\tfmt.Printf(\"Could not capture stdout: %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t// Be careful to both put stdout back in its proper place, and restore any\n\t// tricks that we played on our child packages to get them to cooperate in our testing.\n\tdefer func() {\n\n\t\t// Restore stdout piping\n\t\tos.Stdout = originalStdout\n\t\twriteFile.Close()\n\t\treadFile.Close()\n\t}()\n\n\t// Set our own pipe as stdout\n\tos.Stdout = writeFile\n\n\t// Run the command with a random token value that does not matter because we won't actually\n\t// be calling AWS and so it won't be able to object\n\toutput := executeCommand(args...)\n\n\t// Restore stdout and close the write end of the pipe so that we can collect the output\n\tos.Stdout = originalStdout\n\twriteFile.Close()\n\n\t// Gather the output into a byte buffer\n\toutputBytes, err := ioutil.ReadAll(readFile)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to read pipe for stdout: : %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t// Return the executeCommand output and stdout\n\treturn output, string(outputBytes)\n}", "func (m *MinikubeRunner) SSH(cmdStr string) (string, error) {\n\tprofileArg := fmt.Sprintf(\"-p=%s\", m.Profile)\n\tpath, _ := filepath.Abs(m.BinaryPath)\n\n\tcmd := exec.Command(path, profileArg, \"ssh\", cmdStr)\n\tLogf(\"SSH: %s\", cmdStr)\n\tstdout, err := cmd.CombinedOutput()\n\tLogf(\"Output: %s\", stdout)\n\tif err, ok := err.(*exec.ExitError); ok {\n\t\treturn string(stdout), err\n\t}\n\treturn string(stdout), nil\n}", "func (eCmd *Exec) Run() int {\n\tif eCmd.allocatePTY && !isTerminal() {\n\t\tlog.Error(\"Cannot allocate pseudo-terminal without a terminal\")\n\t\treturn 1\n\t}\n\n\tlocalClient, err := eCmd.clientGetter.Client(eCmd.common.host)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn 1\n\t}\n\tdefer localClient.Close()\n\n\tcontainerClient, err := eCmd.clientGetter.ContainerClient(\n\t\tlocalClient, eCmd.targetContainer)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error getting container client\")\n\t\treturn 1\n\t}\n\n\tcontainer, err := util.GetContainer(containerClient, eCmd.targetContainer)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error getting container information\")\n\t\treturn 1\n\t}\n\n\terr = eCmd.SSHClient.Connect(containerClient.Host(), eCmd.privateKey)\n\tif err != nil {\n\t\tlog.WithError(err).Info(\"Error opening SSH connection\")\n\t\treturn 1\n\t}\n\tdefer eCmd.SSHClient.Disconnect()\n\n\tif eCmd.allocatePTY {\n\t\tif err = eCmd.SSHClient.RequestPTY(); err != nil {\n\t\t\tlog.WithError(err).Info(\"Error requesting pseudo-terminal\")\n\t\t\treturn 1\n\t\t}\n\t}\n\n\tvar flags string\n\tif eCmd.allocatePTY {\n\t\tflags = \"-it\"\n\t}\n\tcommand := strings.Join(\n\t\t[]string{\"docker exec\", flags, container.DockerID, eCmd.command}, \" \")\n\tif err = eCmd.SSHClient.Run(command); err != nil {\n\t\tlog.WithError(err).Info(\"Error running command over SSH\")\n\t\treturn 1\n\t}\n\n\treturn 0\n}", "func (client *NativeClient) Output(command string) (string, error) {\n\tsession, err := client.session(command)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\toutput, err := session.CombinedOutput(command)\n\tdefer session.Close()\n\n\treturn string(bytes.TrimSpace(output)), wrapError(err)\n}", "func (i ClusterInstance) Exec(log *logging.Logger, command string) (string, error) {\n\tstdout, err := i.runRemoteCommand(log, command, \"\", false)\n\tif err != nil {\n\t\treturn stdout, maskAny(err)\n\t}\n\treturn stdout, nil\n}", "func (r *RemoteExecutor) Run(name string, args ...string) error {\n\t_, err := r.RunWithStdout(name, args...)\n\treturn err\n}", "func executeCmd(remote_host string) string {\n\treadConfig(\"config\")\n\t//\tconfig, err := sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t//\tif err != nil {\n\t//\t\tlog.Fatal(err)\n\t//\t}\n\tvar config *ssh.ClientConfig\n\n\tif Conf.Method == \"password\" {\n\t\tconfig = sshAuthPassword(Conf.SshUser, Conf.SshPassword)\n\t} else if Conf.Method == \"key\" {\n\t\tconfig = sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t\t//\t\tif err != nil {\n\t\t//\t\t\tlog.Fatal(err)\n\t\t//\t\t}\n\t} else {\n\t\tlog.Fatal(`Please set method \"password\" or \"key\" at configuration file`)\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", remote_host+\":\"+Conf.SshPort, config)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to dial: \", err)\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to create session: \", err)\n\t}\n\tdefer session.Close()\n\n\tvar b bytes.Buffer\n\tsession.Stdout = &b\n\tif err := session.Run(Conf.Command); err != nil {\n\t\tlog.Fatal(\"Failed to run: \" + err.Error())\n\t}\n\tfmt.Println(\"\\x1b[31;1m\" + remote_host + \"\\x1b[0m\")\n\treturn b.String()\n}", "func (sh *Shell) runCommandUnix(cmd string, timeout time.Duration) (out string, err error) {\n\n\t// Forge token and command, and send to remote\n\ttoken := randStringBytesRmndr()\n\tforgedCmd := sh.forgeCommand(cmd, token)\n\n\tif err = sh.write(forgedCmd, timeout); err != nil {\n\t\tsh.Log.Error(err)\n\t\treturn\n\t}\n\tsh.Log.Debugf(tui.Green(\"command: \") + tui.Bold(cmd))\n\n\t// 2. Read connection.\n\tdone := make(chan struct{})\n\tprocessed := make(chan string, 1)\n\tgo func(chan struct{}, chan string) {\n\t\tdefer close(done)\n\t\tfor {\n\t\t\tselect {\n\t\t\tdefault:\n\t\t\t\t// Read all output until one/both tokens are found\n\t\t\t\toutput, err := sh.readCommandOuput(cmd, token, sh.tokenIndex)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn // We already logged the error\n\t\t\t\t}\n\n\t\t\t\t// Process output\n\t\t\t\tout, err = sh.processRawLine(output, cmd, token)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn // We already logged the error\n\t\t\t\t}\n\t\t\t\tprocessed <- out\n\t\t\t\treturn\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(done, processed)\n\n\t// We wait either for the response body, or a timeout.\n\tfor {\n\t\tselect {\n\t\tcase out = <-processed:\n\t\t\tsh.Log.Debugf(tui.Dim(\"result: \") + tui.Bold(cmd))\n\t\t\treturn out, nil\n\t\tcase <-time.After(timeout):\n\t\t\tclose(done)\n\t\t\t// We still give out, in case it has something in it still.\n\t\t\treturn out, fmt.Errorf(\"reading command result from conn stream timed out\")\n\t\t}\n\t}\n}", "func (factory *Factory) ExecuteCmd(\n\tnamespace string,\n\tname string,\n\tcontainer string,\n\tcommand string,\n\tprintOutput bool,\n) (string, string, error) {\n\tcmd := []string{\n\t\t\"/bin/bash\",\n\t\t\"-c\",\n\t\tcommand,\n\t}\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\terr := factory.ExecuteCommandRaw(namespace, name, container, cmd, nil, &stdout, &stderr, false)\n\tsout := stdout.String()\n\tserr := stderr.String()\n\t// TODO: Stream these to our own stdout as we run.\n\tif printOutput {\n\t\tif sout != \"\" && !strings.Contains(serr, \"constructing many client\") {\n\t\t\tlog.Println(sout)\n\t\t}\n\t\t// Callers of this used to skip printing serr if err was nil, but we never populate serr\n\t\t// if err is nil; always print for now.\n\t\tif serr != \"\" &&\n\t\t\t!strings.Contains(\n\t\t\t\tserr,\n\t\t\t\t\"constructing many client\",\n\t\t\t) { // ignoring constructing many client message\n\t\t\tlog.Println(serr)\n\t\t}\n\t}\n\treturn sout, serr, err\n}", "func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\n\tvar b bytes.Buffer // import \"bytes\"\n\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", net.JoinHostPort(addr, \"22\"), config)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stderr = os.Stderr // get output\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\n\t// Finally, run the command\n\tfullCmd := \". ~/.nix-profile/etc/profile.d/nix.sh && cd \" + workDir + \" && nix-shell \" + nixConf + \" --command '\" + cmd + \"'\"\n\tfmt.Println(fullCmd)\n\terr = session.Run(fullCmd)\n\treturn b, err\n}", "func (scp *SCP) Run(_ string) (*entities.CommandResult, derrors.Error) {\n\n\tconn, err := connection.NewSSHConnection(\n\t\tscp.TargetHost, scp.getTargetPort(),\n\t\tscp.Credentials.Username, scp.Credentials.Password, \"\", scp.Credentials.PrivateKey)\n\tif err != nil {\n\t\treturn nil, derrors.NewInternalError(errors.SSHConnectionError, err).WithParams(scp.TargetHost)\n\t}\n\tstart := time.Now()\n\terr = conn.Copy(scp.Source, scp.Destination, false)\n\tif err != nil {\n\t\treturn nil, derrors.NewInternalError(errors.SSHConnectionError, err).WithParams(scp.TargetHost)\n\t}\n\n\treturn entities.NewSuccessCommand([]byte(scp.String() + \": OK \" + time.Since(start).String())), nil\n}", "func Execute(command []string, dir string, env []string) Result {\n\tvar result Result\n\tresult.Command = command\n\tvar cmd *goexec.Cmd\n\tswitch len(command) {\n\tcase 1:\n\t\tcmd = goexec.Command(command[0])\n\tdefault:\n\t\tcmd = goexec.Command(command[0], command[1:]...)\n\t}\n\tcmd.Dir = dir\n\tcmd.Env = os.Environ()\n\tfor _, e := range env {\n\t\tcmd.Env = append(cmd.Env, e)\n\t}\n\t// cmd := goexec.Command(\"/bin/bash\", \"-c\", command)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tresult.Error = err\n\t\treturn result\n\t}\n\tstderr, err := cmd.StderrPipe()\n\tif err := cmd.Start(); err != nil {\n\t\tresult.Error = err\n\t\treturn result\n\t}\n\n\tbb := bytes.NewBuffer([]byte{})\n\t_, err = bb.ReadFrom(stdout)\n\tresult.Stdout = bb.String()\n\n\tbe := bytes.NewBuffer([]byte{})\n\t_, err = be.ReadFrom(stderr)\n\tresult.Stderr = be.String()\n\n\tvar waitStatus syscall.WaitStatus\n\tif err := cmd.Wait(); err != nil {\n\t\tif exitError, ok := err.(*goexec.ExitError); ok {\n\t\t\twaitStatus = exitError.Sys().(syscall.WaitStatus)\n\t\t\tresult.ExitStatus = waitStatus.ExitStatus()\n\t\t\tresult.Error = errors.New(exitError.Error())\n\t\t}\n\t} else {\n\t\t// Success\n\t\twaitStatus = cmd.ProcessState.Sys().(syscall.WaitStatus)\n\t\tresult.ExitStatus = waitStatus.ExitStatus()\n\t}\n\n\tif result.Error == nil {\n\t\tresult.Error = exitStatusError(result)\n\t}\n\treturn result\n}", "func (ex Exec) ExecuteCommand(command string, args []string) (outStr string, errStr string) {\n\n\tvar logger = log.WithFields(log.Fields{\n\t\t\"command\": command,\n\t\t\"args\": strings.Join(args, \",\"),\n\t})\n\n\tw := &logrusWriter{\n\t\tentry: logger,\n\t}\n\n\tcmd := exec.Command(command, args...)\n\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\tstdoutIn, _ := cmd.StdoutPipe()\n\tstderrIn, _ := cmd.StderrPipe()\n\n\tvar errStdout, errStderr error\n\tstdout := io.MultiWriter(os.Stdout, &stdoutBuf, w)\n\tstderr := io.MultiWriter(os.Stderr, &stderrBuf, w)\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err.Error(),\n\t\t}).Errorf(\"unable to start the execute the command: %v\", strings.Join(args, \",\"))\n\t\terrStr = err.Error()\n\n\t} else {\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\n\t\tgo func() {\n\t\t\t_, errStdout = io.Copy(stdout, stdoutIn)\n\t\t\twg.Done()\n\t\t}()\n\n\t\t_, errStderr = io.Copy(stderr, stderrIn)\n\t\twg.Wait()\n\n\t\terr = cmd.Wait()\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"err\": err.Error(),\n\t\t\t}).Error(\"Problems waiting for command to complete\")\n\t\t\terrStr = err.Error()\n\t\t\treturn\n\t\t}\n\t\tif errStdout != nil || errStderr != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"err\": err.Error(),\n\t\t\t}).Error(\"failed to capture stdout or stderr\")\n\t\t\terrStr = err.Error()\n\t\t\treturn\n\t\t}\n\n\t\toutStr, errStr = string(stdoutBuf.Bytes()), string(stderrBuf.Bytes())\n\t}\n\treturn\n}", "func Run(t *testing.T, binaryPath string, args ...string) (string, int) {\n\tctx := context.Background()\n\tif true {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithTimeout(ctx, 30*time.Second)\n\t\tdefer cancel()\n\t}\n\tcmd := exec.CommandContext(context.Background(), binaryPath, args...)\n\n\t// Set up a chain of pipes. Out is a buffer to return STDOUT.\n\t// The command's STDERR will only go to the bufio scanner for dumping to the\n\t// test log. The command's STDOUT will be duplicated to write both to the\n\t// test log and to an in-memory buffer, to be returned as a string.\n\tvar out bytes.Buffer\n\tpout, pin := io.Pipe()\n\tmin := io.MultiWriter(pin, &out)\n\n\tcmd.Stdout = min\n\tcmd.Stderr = pin\n\n\tgo func() {\n\t\tscanner := bufio.NewScanner(pout)\n\t\tfor scanner.Scan() {\n\t\t\tt.Log(scanner.Text())\n\t\t}\n\t}()\n\n\tch := make(chan error, 1)\n\n\tgo func() {\n\t\terr := cmd.Start()\n\t\tif err != nil {\n\t\t\tch <- errors.Wrapf(err, \"Failed to start process\")\n\t\t\treturn\n\t\t}\n\t\terr = cmd.Wait()\n\t\tif _, ok := err.(*exec.ExitError); err != nil && !ok {\n\t\t\t// We have an err, and it's not an ExitError (trapping a non-zero exit\n\t\t\t// code).\n\t\t\tch <- errors.Wrapf(err, \"Failed to wait\")\n\t\t\treturn\n\t\t}\n\n\t\tch <- nil\n\t\tclose(ch)\n\t}()\n\n\tselect {\n\tcase err := <-ch:\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Command failed:\\n%s\", err.Error())\n\t\t}\n\tcase <-ctx.Done():\n\t\tt.Errorf(\"Command timed out\")\n\t}\n\n\treturn out.String(), cmd.ProcessState.ExitCode()\n}", "func ExecSSH(ctx context.Context, id Identity, cmd []string, opts plugin.ExecOptions) (plugin.ExecCommand, error) {\n\t// find port, username, etc from .ssh/config\n\tport, err := ssh_config.GetStrict(id.Host, \"Port\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := id.User\n\tif user == \"\" {\n\t\tif user, err = ssh_config.GetStrict(id.Host, \"User\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif user == \"\" {\n\t\tuser = \"root\"\n\t}\n\n\tstrictHostKeyChecking, err := ssh_config.GetStrict(id.Host, \"StrictHostKeyChecking\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconnection, err := sshConnect(id.Host, port, user, strictHostKeyChecking != \"no\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to connect: %s\", err)\n\t}\n\n\t// Run command via session\n\tsession, err := connection.NewSession()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create session: %s\", err)\n\t}\n\n\tif opts.Tty {\n\t\t// sshd only processes signal codes if a TTY has been allocated. So set one up when requested.\n\t\tmodes := ssh.TerminalModes{ssh.ECHO: 0, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400}\n\t\tif err := session.RequestPty(\"xterm\", 40, 80, modes); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to setup a TTY: %v\", err)\n\t\t}\n\t}\n\n\texecCmd := plugin.NewExecCommand(ctx)\n\tsession.Stdin, session.Stdout, session.Stderr = opts.Stdin, execCmd.Stdout(), execCmd.Stderr()\n\n\tif opts.Elevate {\n\t\tcmd = append([]string{\"sudo\"}, cmd...)\n\t}\n\n\tcmdStr := shellquote.Join(cmd...)\n\tif err := session.Start(cmdStr); err != nil {\n\t\treturn nil, err\n\t}\n\texecCmd.SetStopFunc(func() {\n\t\t// Close the session on context cancellation. Copying will block until there's more to read\n\t\t// from the exec output. For an action with no more output it may never return.\n\t\t// If a TTY is setup and the session is still open, send Ctrl-C over before closing it.\n\t\tif opts.Tty {\n\t\t\tactivity.Record(ctx, \"Sent SIGINT on context termination: %v\", session.Signal(ssh.SIGINT))\n\t\t}\n\t\tactivity.Record(ctx, \"Closing session on context termination for %v: %v\", id.Host, session.Close())\n\t})\n\n\t// Wait for session to complete and stash result.\n\tgo func() {\n\t\terr := session.Wait()\n\t\tactivity.Record(ctx, \"Closing session for %v: %v\", id.Host, session.Close())\n\t\texecCmd.CloseStreamsWithError(nil)\n\t\tif err == nil {\n\t\t\texecCmd.SetExitCode(0)\n\t\t} else if exitErr, ok := err.(*ssh.ExitError); ok {\n\t\t\texecCmd.SetExitCode(exitErr.ExitStatus())\n\t\t} else {\n\t\t\texecCmd.SetExitCodeErr(err)\n\t\t}\n\t}()\n\treturn execCmd, nil\n}", "func (client *MockPodExecClient) RunPodExecCommand(ctx context.Context, streamOptions *remotecommand.StreamOptions, baseCmd []string) (string, string, error) {\n\n\tvar mockPodExecReturnContext *MockPodExecReturnContext = &MockPodExecReturnContext{}\n\tvar command string\n\t// This is to prevent the crash in the case where streamOptions.Stdin is anything other than *strings.Reader\n\t// In most of the cases the base command will be /bin/sh but if it is something else, it can be reading from\n\t// a io.Reader pipe. For e.g. tarring a file, writing to a write pipe and then untarring it on the pod by reading\n\t// from the reader pipe.\n\tif baseCmd[0] == \"/bin/sh\" {\n\t\tvar cmdStr string\n\t\tstreamOptionsCmd := streamOptions.Stdin.(*strings.Reader)\n\t\tfor i := 0; i < int(streamOptionsCmd.Size()); i++ {\n\t\t\tcmd, _, _ := streamOptionsCmd.ReadRune()\n\t\t\tcmdStr = cmdStr + string(cmd)\n\t\t}\n\n\t\tmockPodExecReturnContext, command = client.GetMockPodExecReturnContextAndKey(ctx, cmdStr)\n\t\tif mockPodExecReturnContext == nil {\n\t\t\terr := fmt.Errorf(\"mockPodExecReturnContext is nil\")\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t}\n\n\t// check if the command is already added or not in the list of GotCmdList\n\tvar found bool\n\tfor i := range client.GotCmdList {\n\t\tif command == client.GotCmdList[i] {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\tclient.GotCmdList = append(client.GotCmdList, command)\n\t}\n\n\treturn mockPodExecReturnContext.StdOut, mockPodExecReturnContext.StdErr, mockPodExecReturnContext.Err\n}", "func (h Client) Exec(arg ...string) (string, string, error) {\n\tcmd := exec.Command(h.HelmExecutable, arg...)\n\n\tklog.V(8).Infof(\"running helm command: %v\", cmd)\n\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\n\tcmd.Stdout = &stdoutBuf\n\tcmd.Stderr = &stderrBuf\n\n\terr := cmd.Run()\n\toutStr, errStr := stdoutBuf.String(), stderrBuf.String()\n\tif err != nil {\n\t\tklog.V(8).Infof(\"stdout: %s\", outStr)\n\t\tklog.V(7).Infof(\"stderr: %s\", errStr)\n\t\treturn \"\", errStr, fmt.Errorf(\"exit code %d running command %s\", cmd.ProcessState.ExitCode(), cmd.String())\n\t}\n\n\treturn outStr, errStr, nil\n}", "func ExecCmdAndSeeOutput(command string) {\n\tfields, err := shlex.Split(command)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd := exec.Command(fields[0], fields[1:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Run() // waits for it to complete\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func run(command string, args ...string) []byte {\n\toutput, err := exec.Command(command, args...).Output()\n\tcheck(err)\n\treturn output\n}", "func (sc *SSHClient) Command(cmd string) (io.Reader, error) {\n\tfmt.Println(cmd)\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := &bytes.Buffer{}\n\twriter := io.MultiWriter(os.Stdout, buf)\n\tgo io.Copy(writer, out)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo io.Copy(os.Stderr, outerr)\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}" ]
[ "0.6952449", "0.6858897", "0.6641178", "0.6570179", "0.64580804", "0.64087915", "0.6398316", "0.63903344", "0.6342059", "0.62891215", "0.621401", "0.6113792", "0.61105305", "0.6021509", "0.60071635", "0.5958194", "0.5943652", "0.5935481", "0.58707535", "0.5860281", "0.5839429", "0.5835095", "0.5824955", "0.58092886", "0.58008784", "0.579574", "0.57873815", "0.57865983", "0.57767695", "0.5771195", "0.57335436", "0.5728821", "0.57243705", "0.5704108", "0.56987834", "0.56833386", "0.565882", "0.5649816", "0.5644983", "0.56423193", "0.56360775", "0.5628585", "0.562299", "0.5620153", "0.56103706", "0.56078506", "0.5578368", "0.55750674", "0.55526865", "0.554927", "0.5510799", "0.55075645", "0.5499391", "0.548735", "0.5476644", "0.5472206", "0.5466915", "0.5461022", "0.5432296", "0.5430715", "0.5424622", "0.5422221", "0.5420344", "0.54111874", "0.5391957", "0.5388664", "0.53774273", "0.537482", "0.53476256", "0.5339855", "0.53293896", "0.5328229", "0.5325472", "0.5312768", "0.530931", "0.5290637", "0.52759224", "0.5260441", "0.5253105", "0.5249724", "0.5248456", "0.52249944", "0.5222513", "0.5222244", "0.5193993", "0.5181712", "0.5176853", "0.5176376", "0.5168402", "0.51663023", "0.5165333", "0.51611507", "0.5158013", "0.515055", "0.5150512", "0.5144046", "0.5130403", "0.5121411", "0.51126754", "0.5092435" ]
0.8034174
0
BackgroundCommand is a wrapper around the SSH client to run a command abstracts the SSH connection details from the EC2 client interface
func (ins *EC2RemoteClient) BackgroundCommand(cmd string, discardOutput bool) (int, error) { exitStatus, err := ins.cmdClient.BackgroundCommand(cmd, discardOutput) return exitStatus, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func cmdSSH() {\n\tswitch state := status(B2D.VM); state {\n\tcase vmUnregistered:\n\t\tlog.Fatalf(\"%s is not registered.\", B2D.VM)\n\tcase vmRunning:\n\t\tcmdParts := append(strings.Fields(B2D.SSHPrefix), fmt.Sprintf(\"%d\", B2D.SSHPort), \"docker@localhost\")\n\t\tif err := cmd(cmdParts[0], cmdParts[1:]...); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\tdefault:\n\t\tlog.Fatalf(\"%s is not running.\", B2D.VM)\n\t}\n}", "func SSH(params *SSHInput) error {\n\t// read the manifest\n\tzoneManifest, err := ReadManifest(params.ManifestPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tborderEIP, err := getTerraformOutput(\"border_eip\", zoneManifest.TerraformState)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\targs := []string{\n\t\t\"-q\",\n\t\t\"-o\",\n\t\tfmt.Sprintf(\n\t\t\t\"ProxyCommand=ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -W %%h:%%p ubuntu@%s\", borderEIP),\n\t\t\"-o\", \"UserKnownHostsFile=/dev/null\",\n\t\t\"-o\", \"StrictHostKeyChecking=no\",\n\t\tfmt.Sprintf(\"ubuntu@%s\", params.Host),\n\t}\n\targs = append(args, params.Args...)\n\n\tcmd := exec.Command(\"ssh\", args...)\n\tcmd.Env = os.Environ()\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}", "func RunSSHCommand(SSHHandle *ssh.Client, cmd string, sudo bool, bg bool, logger *log.Logger) (retCode int, stdout, stderr []string) {\n\tlogger.Println(\"Running cmd \" + cmd)\n\tvar stdoutBuf, stderrBuf bytes.Buffer\n\tsshSession, err := SSHHandle.NewSession()\n\tif err != nil {\n\t\tlogger.Printf(\"SSH session creation failed! %s\", err)\n\t\treturn -1, nil, nil\n\t}\n\tdefer sshSession.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err = sshSession.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\tlogger.Println(\"SSH session Pty creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tsshOut, err := sshSession.StdoutPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StdoutPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\tsshErr, err := sshSession.StderrPipe()\n\tif err != nil {\n\t\tlogger.Println(\"SSH session StderrPipe creation failed!\")\n\t\treturn -1, nil, nil\n\t}\n\n\tshout := io.MultiWriter(&stdoutBuf, (*LogWriter)(logger))\n\tssherr := io.MultiWriter(&stderrBuf, (*LogWriter)(logger))\n\n\tgo func() {\n\t\tio.Copy(shout, sshOut)\n\t}()\n\tgo func() {\n\n\t\tio.Copy(ssherr, sshErr)\n\t}()\n\n\tif bg {\n\t\tcmd = \"nohup sh -c \\\"\" + cmd + \" 2>&1 >/dev/null </dev/null & \\\"\"\n\t} else {\n\t\tcmd = \"sh -c \\\"\" + cmd + \"\\\"\"\n\t}\n\n\tif sudo {\n\t\tcmd = SudoCmd(cmd)\n\t}\n\n\tlogger.Println(\"Running command : \" + cmd)\n\tif err = sshSession.Run(cmd); err != nil {\n\t\tlogger.Println(\"failed command : \" + cmd)\n\t\tswitch v := err.(type) {\n\t\tcase *ssh.ExitError:\n\t\t\tretCode = v.Waitmsg.ExitStatus()\n\t\tdefault:\n\t\t\tretCode = -1\n\t\t}\n\t} else {\n\t\tlogger.Println(\"sucess command : \" + cmd)\n\t\tretCode = 0\n\t}\n\n\tstdout = strings.Split(stdoutBuf.String(), \"\\n\")\n\tstderr = strings.Split(stderrBuf.String(), \"\\n\")\n\tlogger.Println(stdout)\n\tlogger.Println(stderr)\n\tlogger.Println(\"Return code : \" + strconv.Itoa(retCode))\n\n\treturn retCode, stdout, stderr\n\n}", "func (client *Client) Run(command string, silent bool) (output string, err error) {\n\tkeys := ssh.Auth{\n\t\tKeys: []string{client.PrivateKeyFile},\n\t}\n\tsshterm, err := ssh.NewNativeClient(client.User, client.Host, \"SSH-2.0-MyCustomClient-1.0\", client.Port, &keys, nil)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to request shell - %s\", err)\n\t}\n\tif !silent {\n\t\tlog.Printf(\"Running: ssh -i \\\"%s\\\" %s@%s %s\", client.PrivateKeyFile, client.User, client.Host, command)\n\t}\n\tr, _, err := sshterm.Start(command)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to start command - %s\", err)\n\t}\n\tsshterm.Wait()\n\tresponse, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to read response - %s\", err)\n\t}\n\treturn string(response), nil\n}", "func (host *Host) SSH(job *Job, command string) (err error) {\n\tproc, err := host.startSSH(job, command)\n\tclose(proc.Stdin())\n\tfor {\n\t\tselect {\n\t\tcase line, ok := <-proc.Stdout():\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thost.logger.Println(line)\n\t\tcase line, ok := <-proc.Stderr():\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thost.logger.Println(line)\n\t\tcase err = <-proc.Done():\n\t\t\treturn err\n\t\tcase <-time.After(job.Timeout):\n\t\t\treturn ErrorTimeout\n\t\tcase <-host.cancel:\n\t\t\tif proc.IsAlive() {\n\t\t\t\tproc.Signal(os.Interrupt)\n\t\t\t}\n\t\t\treturn ErrorCancel\n\t\t}\n\t}\n}", "func executeCmd(remote_host string) string {\n\treadConfig(\"config\")\n\t//\tconfig, err := sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t//\tif err != nil {\n\t//\t\tlog.Fatal(err)\n\t//\t}\n\tvar config *ssh.ClientConfig\n\n\tif Conf.Method == \"password\" {\n\t\tconfig = sshAuthPassword(Conf.SshUser, Conf.SshPassword)\n\t} else if Conf.Method == \"key\" {\n\t\tconfig = sshAuthKey(Conf.SshUser, Conf.SshKeyPath, Conf.Passphrase)\n\t\t//\t\tif err != nil {\n\t\t//\t\t\tlog.Fatal(err)\n\t\t//\t\t}\n\t} else {\n\t\tlog.Fatal(`Please set method \"password\" or \"key\" at configuration file`)\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", remote_host+\":\"+Conf.SshPort, config)\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to dial: \", err)\n\t}\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to create session: \", err)\n\t}\n\tdefer session.Close()\n\n\tvar b bytes.Buffer\n\tsession.Stdout = &b\n\tif err := session.Run(Conf.Command); err != nil {\n\t\tlog.Fatal(\"Failed to run: \" + err.Error())\n\t}\n\tfmt.Println(\"\\x1b[31;1m\" + remote_host + \"\\x1b[0m\")\n\treturn b.String()\n}", "func sshAgent() (io.ReadWriteCloser, error) {\r\n cmd := exec.Command(\"wsl\", \"bash\", \"-c\", \"PS1=x source ~/.bashrc; socat - UNIX:\\\\$SSH_AUTH_SOCK\")\r\n stdin, err := cmd.StdinPipe()\r\n if err != nil {\r\n return nil, err\r\n }\r\n stdout, err := cmd.StdoutPipe()\r\n if err != nil {\r\n return nil, err\r\n }\r\n if err := cmd.Start(); err != nil {\r\n return nil, err\r\n }\r\n return &sshAgentCmd{stdout, stdin, cmd}, nil\r\n}", "func (s *SSHClient) Execute(host, cmd string) (string, error) {\n\thostname := fmt.Sprintf(\"%s.%s.%s:%d\", host, s.projectID, DropletDomain, defaultSSHPort)\n\n\tpemBytes, err := s.repo.GetKey(s.projectID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(pemBytes)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"parse key failed: %v\", err)\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: \"workshop\",\n\t\tAuth: []ssh.AuthMethod{ssh.PublicKeys(signer)},\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"dialing\")\n\tconn, err := ssh.Dial(\"tcp\", hostname, config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ts.log.WithField(\"hostname\", hostname).Info(\"creating session\")\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer session.Close()\n\n\tvar buf bytes.Buffer\n\tsession.Stdout = &buf\n\n\ts.log.WithFields(logrus.Fields{\n\t\t\"hostname\": hostname,\n\t\t\"cmd\": cmd}).\n\t\tInfo(\"running command\")\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\ts.log.WithField(\"output\", buf.String()).WithError(err).Error(\"ssh client run returned non zero result\")\n\t\treturn \"\", fmt.Errorf(\"%s\\n%s\", err, buf.String())\n\t}\n\n\treturn buf.String(), nil\n}", "func (ssh *SSHConfig) CommandContext(ctx context.Context, cmdString string) (*SSHCommand, error) {\n\ttunnels, sshConfig, err := ssh.CreateTunnels()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, cmdString, false)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tcmd := exec.CommandContext(ctx, \"bash\", \"-c\", sshCmdString)\n\tsshCommand := SSHCommand{\n\t\tcmd: cmd,\n\t\ttunnels: tunnels,\n\t\tkeyFile: keyFile,\n\t}\n\treturn &sshCommand, nil\n}", "func (c *Client) Run(ctx context.Context, cmds []*Command) error {\n\turl := c.Host + \":\" + c.Port\n\tclient, err := ssh.Dial(\"tcp\", url, c.Sshconfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in ssh.Dial to %v %w\", url, err)\n\t}\n\n\tdefer client.Close()\n\tsession, err := client.NewSession()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in client.NewSession to %v %w\", url, err)\n\t}\n\tdefer session.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 0, // disable echoing\n\t\tssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud\n\t\tssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud\n\t}\n\n\tif err := session.RequestPty(\"xterm\", 80, 40, modes); err != nil {\n\t\treturn fmt.Errorf(\"error in session.RequestPty to %v %w\", url, err)\n\t}\n\n\tw, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in session.StdinPipe to %v %w\", url, err)\n\t}\n\tr, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error in session.StdoutPipe to %v %w\", url, err)\n\t}\n\tin, out := listener(w, r, c.Prompt)\n\tif err := session.Start(\"/bin/sh\"); err != nil {\n\t\treturn fmt.Errorf(\"error in session.Start to %v %w\", url, err)\n\t}\n\n\t<-out // ignore login output\n\tfor _, cmd := range cmds {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.New(\"canceled by context\")\n\n\t\tdefault:\n\t\t\tlogf(cmd.OutputLevel, \"[%v]: cmd [%v] starting...\", c.Host, cmd.Input)\n\n\t\t\tin <- cmd\n\t\t\terr := cmd.wait(ctx, out)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[%v]: Error in cmd [%v] at waiting %w\", c.Host, cmd.Input, err)\n\t\t\t}\n\n\t\t\tif outputs, ok := cmd.output(); ok {\n\t\t\t\tfor _, output := range outputs {\n\t\t\t\t\tfmt.Println(output)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdoNext, err := cmd.Callback(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[%v]: Error in cmd [%v] Callback %w\", c.Host, cmd.Input, err)\n\t\t\t}\n\n\t\t\tif doNext && cmd.NextCommand != nil {\n\t\t\t\tnextCmd := cmd.NextCommand(cmd)\n\n\t\t\t\tlogf(nextCmd.OutputLevel, \"[%v]: next cmd [%v] starting...\", c.Host, nextCmd.Input)\n\n\t\t\t\tin <- nextCmd\n\t\t\t\terr = nextCmd.wait(ctx, out)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"[%v]: Error in next cmd [%v] at waiting %w\", c.Host, cmd.Input, err)\n\t\t\t\t}\n\n\t\t\t\tif outputs, ok := nextCmd.output(); ok {\n\t\t\t\t\tfor _, output := range outputs {\n\t\t\t\t\t\tfmt.Println(output)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t_, err := nextCmd.Callback(nextCmd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"[%v]: Error in next cmd [%v] Callback %w\", c.Host, nextCmd.Input, err)\n\t\t\t\t}\n\n\t\t\t\tlogf(nextCmd.OutputLevel, \"[%v]: next cmd [%v] done\", c.Host, nextCmd.Input)\n\n\t\t\t}\n\n\t\t\tlogf(cmd.OutputLevel, \"[%v]: cmd [%v] done\", c.Host, cmd.Input)\n\t\t}\n\t}\n\tsession.Close()\n\n\treturn nil\n}", "func (s *SSHClient) Run(command string) (string, error) {\n\tif err := s.createClient(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn s.run(command)\n}", "func (s *SSHOrch) ExecSSH(userserver, cmd string) string {\n\tclient := s.doLookup(userserver)\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to create session:\", err)\n\t}\n\tdefer session.Close()\n\t/*\n\t\tstdout, err := session.StdoutPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stdout:\", err)\n\t\t}\n\n\t\tstderr, err := session.StderrPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Failed to pipe session stderr:\", err)\n\t\t}\n\t*/\n\n\tbuf, err := session.CombinedOutput(cmd)\n\tif err != nil {\n\t\tlog.Fatalln(\"Failed to execute cmd:\", err)\n\t}\n\n\t// Network read pushed to background\n\t/*readExec := func(r io.Reader, ch chan []byte) {\n\t\tif str, err := ioutil.ReadAll(r); err != nil {\n\t\t\tch <- str\n\t\t}\n\t}\n\toutCh := make(chan []byte)\n\tgo readExec(stdout, outCh)\n\t*/\n\treturn string(buf)\n}", "func (e *SSHExecutor) Execute(cmd string, sudo bool, timeout ...time.Duration) ([]byte, []byte, error) {\n\t// try to acquire root permission\n\tif e.Sudo || sudo {\n\t\tcmd = fmt.Sprintf(\"sudo -H -u root bash -c \\\"%s\\\"\", cmd)\n\t}\n\n\t// set a basic PATH in case it's empty on login\n\tcmd = fmt.Sprintf(\"PATH=$PATH:/usr/bin:/usr/sbin %s\", cmd)\n\n\tif e.Locale != \"\" {\n\t\tcmd = fmt.Sprintf(\"export LANG=%s; %s\", e.Locale, cmd)\n\t}\n\n\t// run command on remote host\n\t// default timeout is 60s in easyssh-proxy\n\tif len(timeout) == 0 {\n\t\ttimeout = append(timeout, executeDefaultTimeout)\n\t}\n\n\tstdout, stderr, done, err := e.Config.Run(cmd, timeout...)\n\n\tzap.L().Info(\"SSHCommand\",\n\t\tzap.String(\"host\", e.Config.Server),\n\t\tzap.String(\"port\", e.Config.Port),\n\t\tzap.String(\"cmd\", cmd),\n\t\tzap.Error(err),\n\t\tzap.String(\"stdout\", stdout),\n\t\tzap.String(\"stderr\", stderr))\n\n\tif err != nil {\n\t\tbaseErr := ErrSSHExecuteFailed.\n\t\t\tWrap(err, \"Failed to execute command over SSH for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t\tif len(stdout) > 0 || len(stderr) > 0 {\n\t\t\toutput := strings.TrimSpace(strings.Join([]string{stdout, stderr}, \"\\n\"))\n\t\t\tbaseErr = baseErr.\n\t\t\t\tWithProperty(cliutil.SuggestionFromFormat(\"Command output on remote host %s:\\n%s\\n\",\n\t\t\t\t\te.Config.Server,\n\t\t\t\t\tcolor.YellowString(output)))\n\t\t}\n\t\treturn []byte(stdout), []byte(stderr), baseErr\n\t}\n\n\tif !done { // timeout case,\n\t\treturn []byte(stdout), []byte(stderr), ErrSSHExecuteTimedout.\n\t\t\tWrap(err, \"Execute command over SSH timedout for '%s@%s:%s'\", e.Config.User, e.Config.Server, e.Config.Port).\n\t\t\tWithProperty(ErrPropSSHCommand, cmd).\n\t\t\tWithProperty(ErrPropSSHStdout, stdout).\n\t\t\tWithProperty(ErrPropSSHStderr, stderr)\n\t}\n\n\treturn []byte(stdout), []byte(stderr), nil\n}", "func (s *Server) DoBackground(target string, cmds ...Command) error {\n\t// ensure command id is generated\n\tfor _, cmd := range cmds {\n\t\tcmd.ID = randomCommandID()\n\n\t\t// put in command queue\n\t\tif err := s.putCommandQueue(target, cmd); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// put in callback list\n\t\ts.registerCommandCallback(cmd.ID, cmd)\n\t}\n\n\treturn nil\n}", "func (client *ExternalClient) Shell(pty bool, args ...string) error {\n\targs = append(client.BaseArgs, args...)\n\tcmd := getSSHCmd(client.BinaryPath, pty, args...)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}", "func ExecBackgroundCtx(ctx context.Context, cmd *cobra.Command, stdIn io.Reader, stdOut, stdErr io.Writer, args ...string) *errgroup.Group {\n\tcmd.SetIn(stdIn)\n\tcmd.SetOut(io.MultiWriter(stdOut, debugStdout))\n\tcmd.SetErr(io.MultiWriter(stdErr, debugStderr))\n\n\tif args == nil {\n\t\targs = []string{}\n\t}\n\tcmd.SetArgs(args)\n\n\teg := &errgroup.Group{}\n\teg.Go(func() error {\n\t\tdefer cmd.SetIn(nil)\n\t\treturn cmd.ExecuteContext(ctx)\n\t})\n\n\treturn eg\n}", "func (sc *sshclient) RunInterativeShell(address string) {\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tgo func() {\n\t\tif err := sc.runclient(ctx, address); err != nil {\n\t\t\tkuttilog.Print(0, err)\n\t\t}\n\t\tcancel()\n\t}()\n\n\tselect {\n\tcase <-sig:\n\t\tcancel()\n\tcase <-ctx.Done():\n\t}\n}", "func (h *Host) Exec(cmd string) error {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tstdout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstderr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.Debugf(\"executing command: %s\", cmd)\n\tif err := session.Start(cmd); err != nil {\n\t\treturn err\n\t}\n\n\tmultiReader := io.MultiReader(stdout, stderr)\n\toutputScanner := bufio.NewScanner(multiReader)\n\n\tfor outputScanner.Scan() {\n\t\tlogrus.Debugf(\"%s: %s\", h.FullAddress(), outputScanner.Text())\n\t}\n\tif err := outputScanner.Err(); err != nil {\n\t\tlogrus.Errorf(\"%s: %s\", h.FullAddress(), err.Error())\n\t}\n\n\treturn nil\n}", "func call_ssh(cmd string, user string, hosts []string) (result string, error bool) {\n\tresults := make(chan string, 100)\n\ttimeout := time.After(5 * time.Second)\n\n\tfor _, hostname := range hosts {\n\t\tgo func(hostname string) {\n\t\t\tresults <- remote_runner.ExecuteCmd(cmd, user, hostname)\n\t\t}(hostname)\n\t}\n\n\tfor i := 0; i < len(hosts); i++ {\n\t\tselect {\n\t\tcase res := <-results:\n\t\t\t//fmt.Print(res)\n\t\t\tresult = res\n\t\t\terror = false\n\t\tcase <-timeout:\n\t\t\t//fmt.Println(\"Timed out!\")\n\t\t\tresult = \"Time out!\"\n\t\t\terror = true\n\t\t}\n\t}\n\treturn\n}", "func (s *HostListener) SSH(ctx context.Context, in *protocol.Reference) (sc *protocol.SshConfig, err error) {\n\tdefer fail.OnExitConvertToGRPCStatus(&err)\n\tdefer fail.OnExitWrapError(&err, \"cannot get host SSH information\")\n\tdefer fail.OnPanic(&err)\n\n\tif s == nil {\n\t\treturn nil, fail.InvalidInstanceError()\n\t}\n\tif in == nil {\n\t\treturn nil, fail.InvalidParameterError(\"in\", \"cannot be nil\")\n\t}\n\tif ctx == nil {\n\t\treturn nil, fail.InvalidParameterError(\"ctx\", \"cannot be nil\")\n\t}\n\n\tif ok, err := govalidator.ValidateStruct(in); err == nil && !ok {\n\t\tlogrus.Warnf(\"Structure validation failure: %v\", in) // FIXME: Generate json tags in protobuf\n\t}\n\n\tref, refLabel := srvutils.GetReference(in)\n\tif ref == \"\" {\n\t\treturn nil, fail.InvalidRequestError(\"neither name nor id given as reference\")\n\t}\n\n\tjob, xerr := PrepareJob(ctx, in.GetTenantId(), fmt.Sprintf(\"/host/%s/sshconfig\", ref))\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\tdefer job.Close()\n\n\ttracer := debug.NewTracer(job.Task(), tracing.ShouldTrace(\"listeners.host\"), \"(%s)\", refLabel).WithStopwatch().Entering()\n\tdefer tracer.Exiting()\n\tdefer fail.OnExitLogError(&err, tracer.TraceMessage())\n\n\tsshHandler := handlers.NewSSHHandler(job)\n\tsshConfig, xerr := sshHandler.GetConfig(ref)\n\tif xerr != nil {\n\t\treturn nil, xerr\n\t}\n\n\ttracer.Trace(\"SSH config of host %s successfully loaded\", refLabel)\n\treturn converters.SSHConfigFromAbstractToProtocol(*sshConfig), nil\n}", "func (bc *BaseCluster) SSH(m Machine, cmd string) ([]byte, []byte, error) {\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tclient, err := bc.SSHClient(m.IP())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer client.Close()\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stdout = &stdout\n\tsession.Stderr = &stderr\n\terr = session.Run(cmd)\n\toutBytes := bytes.TrimSpace(stdout.Bytes())\n\terrBytes := bytes.TrimSpace(stderr.Bytes())\n\treturn outBytes, errBytes, err\n}", "func (t *TestCluster) SSH(m platform.Machine, cmd string) ([]byte, error) {\n\tvar stdout, stderr []byte\n\tvar err error\n\tf := func() {\n\t\tstdout, stderr, err = m.SSH(cmd)\n\t}\n\n\terrMsg := fmt.Sprintf(\"ssh: %s\", cmd)\n\t// If f does not before the test timeout, the RunWithExecTimeoutCheck\n\t// will end this goroutine and mark the test as failed\n\tt.H.RunWithExecTimeoutCheck(f, errMsg)\n\tif len(stderr) > 0 {\n\t\tfor _, line := range strings.Split(string(stderr), \"\\n\") {\n\t\t\tt.Log(line)\n\t\t}\n\t}\n\treturn stdout, err\n}", "func SSHRunCommand(client *ssh.Client, cmd string) (string, error) {\n\tsession, err := client.NewSession()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdefer session.Close()\n\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tsession.Stdout = &stdout\n\tsession.Stderr = &stderr\n\n\terr = session.Run(cmd)\n\n\toutput := stdout.String() + stderr.String()\n\n\tif err != nil {\n\t\treturn output, fmt.Errorf(\"failed to execute command \\\"%s\\\" via SSH client: %s\", cmd, err)\n\t}\n\n\treturn output, nil\n}", "func execStopContainerOnGc(sshClientConfig *ssh.ClientConfig, svcMasterIP string, containerName string,\n\tgcMasterIP string, svcNamespace string) error {\n\tsshSecretName := GetAndExpectStringEnvVar(sshSecretName)\n\tcmdToGetPrivateKey := fmt.Sprintf(\"kubectl get secret %s -n %s -o\"+\n\t\t\"jsonpath={'.data.ssh-privatekey'} | base64 -d > key\", sshSecretName, svcNamespace)\n\tframework.Logf(\"Invoking command '%v' on host %v\", cmdToGetPrivateKey,\n\t\tsvcMasterIP)\n\tcmdResult, err := sshExec(sshClientConfig, svcMasterIP,\n\t\tcmdToGetPrivateKey)\n\tif err != nil || cmdResult.Code != 0 {\n\t\tfssh.LogResult(cmdResult)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tcmdToGetPrivateKey, svcMasterIP, err)\n\t}\n\n\tenablePermissionCmd := \"chmod 600 key\"\n\tframework.Logf(\"Invoking command '%v' on host %v\", enablePermissionCmd,\n\t\tsvcMasterIP)\n\tcmdResult, err = sshExec(sshClientConfig, svcMasterIP,\n\t\tenablePermissionCmd)\n\tif err != nil || cmdResult.Code != 0 {\n\t\tfssh.LogResult(cmdResult)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tenablePermissionCmd, svcMasterIP, err)\n\t}\n\n\tcmdToGetContainerInfo := fmt.Sprintf(\"ssh -o 'StrictHostKeyChecking=no' -i key %s@%s \"+\n\t\t\"'sudo -i crictl ps| grep %s' > container.log 2> /dev/null\", gcNodeUser, gcMasterIP, containerName)\n\tframework.Logf(\"Invoking command '%v' on host %v\", cmdToGetContainerInfo,\n\t\tsvcMasterIP)\n\tcmdResult, err = sshExec(sshClientConfig, svcMasterIP,\n\t\tcmdToGetContainerInfo)\n\tif err != nil || cmdResult.Code != 0 {\n\t\tfssh.LogResult(cmdResult)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tcmdToGetContainerInfo, svcMasterIP, err)\n\t}\n\n\tcmdToGetContainerId := \"cat container.log | awk '{print $1}' | tr -d '\\n'\"\n\tframework.Logf(\"Invoking command '%v' on host %v\", cmdToGetContainerInfo,\n\t\tsvcMasterIP)\n\tcmdResult, err = sshExec(sshClientConfig, svcMasterIP,\n\t\tcmdToGetContainerId)\n\tif err != nil || cmdResult.Code != 0 {\n\t\tfssh.LogResult(cmdResult)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tcmdToGetContainerId, svcMasterIP, err)\n\t}\n\tcontainerID := cmdResult.Stdout\n\n\tcontainerStopCmd := fmt.Sprintf(\"ssh -o 'StrictHostKeyChecking=no' -i key %s@%s \"+\n\t\t\"'sudo -i crictl stop %s' 2> /dev/null\", gcNodeUser, gcMasterIP, containerID)\n\tframework.Logf(\"Invoking command '%v' on host %v\", containerStopCmd,\n\t\tsvcMasterIP)\n\tcmdResult, err = sshExec(sshClientConfig, svcMasterIP,\n\t\tcontainerStopCmd)\n\tif err != nil || cmdResult.Code != 0 {\n\t\tfssh.LogResult(cmdResult)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tcontainerStopCmd, svcMasterIP, err)\n\t}\n\n\t// delete the temporary log file\n\tcmd := \"rm container.log\"\n\tframework.Logf(\"Invoking command '%v' on host %v\", cmd,\n\t\tsvcMasterIP)\n\tresult, err := sshExec(sshClientConfig, svcMasterIP,\n\t\tcmd)\n\tif err != nil || result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\treturn fmt.Errorf(\"couldn't execute command: %s on host: %v , error: %s\",\n\t\t\tcmd, svcMasterIP, err)\n\t}\n\treturn nil\n}", "func (this Scanner) Scan(target, cmd string, cred scanners.Credential, outChan chan scanners.Result) {\n\t// Add port 22 to the target if we didn't get a port from the user.\n\tif !strings.Contains(target, \":\") {\n\t\ttarget = target + \":22\"\n\t}\n\n\tvar config ssh.ClientConfig\n\tvar err error\n\n\t// Let's assume that we connected successfully and declare the data as such, we can edit it later if we failed\n\tresult := scanners.Result{\n\t\tHost: target,\n\t\tAuth: cred,\n\t\tMessage: \"Successfully connected\",\n\t\tStatus: true,\n\t\tOutput: \"\",\n\t}\n\n\t// Depending on the authentication type, run the correct connection function\n\tswitch cred.Type {\n\tcase \"basic\":\n\t\tconfig, err = this.prepPassConfig(cred.Account, cred.AuthData)\n\tcase \"sshkey\":\n\t\tconfig, err = this.prepCertConfig(cred.Account, cred.AuthData)\n\t}\n\n\t// Return if we got an error.\n\tif err != nil {\n\t\tresult.Message = err.Error()\n\t\tresult.Status = false\n\t}\n\n\t_, session, err := this.connect(cred.Account, target, config)\n\n\t// If we got an error, let's set the data properly\n\tif err != nil {\n\t\tresult.Message = err.Error()\n\t\tresult.Status = false\n\t}\n\n\t// If we didn't get an error and we have a command to run, let's do it.\n\tif err == nil && cmd != \"\" {\n\t\t// Execute the command\n\t\tresult.Output, err = this.executeCommand(cmd, session)\n\t\tif err != nil {\n\t\t\t// If we got an error, let's give the user some output.\n\t\t\tresult.Output = \"Script Error: \" + err.Error()\n\t\t}\n\t}\n\n\t// Finally, let's pass our result to the proper channel to write out to the user\n\toutChan <- result\n}", "func Exec(cmds []string, host config.Host, pwd string, force bool) (string, error) {\n\tvar err error\n\tvar auth goph.Auth\n\tvar callback ssh.HostKeyCallback\n\n\tif force {\n\t\tcallback = ssh.InsecureIgnoreHostKey()\n\t} else {\n\t\tif callback, err = DefaultKnownHosts(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif host.Keyfile != \"\" {\n\t\t// Start new ssh connection with private key.\n\t\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\n\t\t\tif os.Getenv(\"GO\") == \"DEBUG\" {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\t// ssh: this private key is passphrase protected\n\t\t\tpwd = common.AskPass(\"Private key passphrase: \")\n\t\t\tif auth, err = goph.Key(host.Keyfile, pwd); err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif pwd == \"\" {\n\t\t\tpwd = common.AskPass(\n\t\t\t\tfmt.Sprintf(\"%s@%s's password: \", host.User, host.Addr),\n\t\t\t)\n\t\t}\n\t\tauth = goph.Password(pwd)\n\t}\n\n\tif os.Getenv(\"GO\") == \"DEBUG\" {\n\t\tfmt.Println(host, pwd, force)\n\t}\n\n\tclient, err := goph.NewConn(&goph.Config{\n\t\tUser: host.User,\n\t\tAddr: host.Addr,\n\t\tPort: host.Port,\n\t\tAuth: auth,\n\t\tTimeout: 5 * time.Second,\n\t\tCallback: callback,\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Defer closing the network connection.\n\tdefer client.Close()\n\n\t// Execute your command.\n\tout, err := client.Run(strings.Join(cmds, \" && \"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Get your output as []byte.\n\treturn string(out), nil\n}", "func (client *SSHClient) Run(command string, stdout io.Writer, stderr io.Writer) error {\n\tsession, err := client.cryptoClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer session.Close()\n\n\tsession.Stdout = stdout\n\tsession.Stderr = stderr\n\n\treturn session.Run(command)\n}", "func main() {\n\tprintln(\"ENTER THE ADDRESS TO CONNECT (ex: \\\"185.20.227.83:22\\\"):\") //185.20.227.83:22\n\tline, _, _ := bufio.NewReader(os.Stdin).ReadLine()\n\taddr := string(line)\n\tprintln(\"CHOOSE A CONNECTION METHOD \\\"PASSWORD\\\" OR \\\"KEY\\\" (ex: \\\"PASSWORD\\\"):\")\n\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\n\tconnMethod := string(line)\n\n\tvar config *ssh.ClientConfig\n\tif connMethod == \"PASSWORD\" {\n\t\tconfig = getConfigWithPass()\n\t} else if connMethod == \"KEY\" {\n\t\tconfig = getConfigWithKey()\n\t} else {\n\t\tlog.Fatal(\"INCORRECT METHOD\")\n\t\treturn\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", addr, config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tprintln(\"ENTER \\\"EXIT\\\" TO QUIT\")\n\tfor {\n\t\tfmt.Println(\"ENTER THE COMMAND:\")\n\t\tline, _, _ = bufio.NewReader(os.Stdin).ReadLine()\n\t\tcommand := string(line)\n\t\tfmt.Println(\"YOUR COMMAND:\", command)\n\t\tif command == \"EXIT\" {\n\t\t\tbreak\n\t\t}\n\t\tsendCommandToServer(client, command)\n\t}\n}", "func (s WebSSHBenchmark) runCommand(ctx context.Context, tc *client.TeleportClient, webSess *webSession, host, command string) error {\n\tstream, err := connectToHost(ctx, tc, webSess, host)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tdefer stream.Close()\n\n\tif _, err := io.WriteString(stream, command); err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tif _, err := io.Copy(tc.Stdout, stream); err != nil && !errors.Is(err, io.EOF) {\n\t\treturn trace.Wrap(err)\n\t}\n\n\treturn nil\n}", "func (i InputBackgroundRemote) construct() InputBackgroundClass { return &i }", "func testCommand(t *testing.T, client ssh.Client, command string) error {\n\t// To avoid mixing the output streams of multiple commands running in\n\t// parallel tests, we combine stdout and stderr on the remote host, and\n\t// capture stdout and write it to the test log here.\n\tstdout := new(bytes.Buffer)\n\tif err := client.Run(command+\" 2>&1\", stdout, os.Stderr); err != nil {\n\t\tt.Logf(\"`%s` failed with %v:\\n%s\", command, err, stdout.String())\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Cloud) setsshClient(client ssh.Clienter) {\n\tc.sshClient = client\n}", "func (s *BaseAspidaListener) EnterConnectionSSH(ctx *ConnectionSSHContext) {}", "func (m *MinikubeRunner) SSH(cmdStr string) (string, error) {\n\tprofileArg := fmt.Sprintf(\"-p=%s\", m.Profile)\n\tpath, _ := filepath.Abs(m.BinaryPath)\n\n\tcmd := exec.Command(path, profileArg, \"ssh\", cmdStr)\n\tLogf(\"SSH: %s\", cmdStr)\n\tstdout, err := cmd.CombinedOutput()\n\tLogf(\"Output: %s\", stdout)\n\tif err, ok := err.(*exec.ExitError); ok {\n\t\treturn string(stdout), err\n\t}\n\treturn string(stdout), nil\n}", "func (sc *SSHClient) InteractiveCommand(cmd string) error {\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tin, err := session.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo processOut(out, in)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo processOut(outerr, in)\n\terr = session.Shell()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(in, \"%s\\n\", cmd)\n\treturn session.Wait()\n}", "func (sc *SSHClient) Command(cmd string) (io.Reader, error) {\n\tfmt.Println(cmd)\n\tsession, err := sc.client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\tout, err := session.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := &bytes.Buffer{}\n\twriter := io.MultiWriter(os.Stdout, buf)\n\tgo io.Copy(writer, out)\n\touterr, err := session.StderrPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo io.Copy(os.Stderr, outerr)\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}", "func (c *Client) Exec(cmd string) ([]byte, error) {\n\tsession, err := c.SSHClient.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\n\treturn session.CombinedOutput(cmd)\n}", "func (s *SSHRunner) client() (*ssh.Client, error) {\n\tif s.c != nil {\n\t\treturn s.c, nil\n\t}\n\n\tc, err := sshutil.NewSSHClient(s.d)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"new client\")\n\t}\n\ts.c = c\n\treturn s.c, nil\n}", "func (cc *CommandRestClient) Put(id string, cID string, body string, ctx context.Context) (string, error) {\n\treturn clients.PutRequest(cc.url+\"/\"+id+\"/command/\"+cID, []byte(body), ctx)\n}", "func init() {\n\tcmd := cli.Command{\n\t\tName: \"ssh\",\n\t\tUsage: \"create and manage ssh certificates\",\n\t\tUsageText: \"step ssh <subcommand> [arguments] [global-flags] [subcommand-flags]\",\n\t\tDescription: `**step ssh** command group provides facilities to sign SSH certificates.\n\n## EXAMPLES\n\nGenerate a new SSH key pair and user certificate:\n'''\n$ step ssh certificate joe@work id_ecdsa\n'''\n\nGenerate a new SSH key pair and host certificate:\n'''\n$ step ssh certificate --host internal.example.com ssh_host_ecdsa_key\n'''\n\nAdd a new user certificate to the agent:\n'''\n$ step ssh login joe@example.com\n'''\n\nRemove a certificate from the agent:\n'''\n$ step ssh logout joe@example.com\n'''\n\nList all keys in the agent:\n'''\n$ step ssh list\n'''\n\nConfigure a user environment with the SSH templates:\n'''\n$ step ssh config\n'''\n\nInspect an ssh certificate file:\n'''\n$ step ssh inspect id_ecdsa-cert.pub\n'''\n\nInspect an ssh certificate in the agent:\n'''\n$ step ssh list --raw joe@example.com | step ssh inspect\n'''\n\nList all the hosts you have access to:\n'''\n$ step ssh hosts\n'''\n\nLogin into one host:\n'''\n$ ssh internal.example.com\n'''`,\n\t\tSubcommands: cli.Commands{\n\t\t\tcertificateCommand(),\n\t\t\tcheckHostCommand(),\n\t\t\tconfigCommand(),\n\t\t\tfingerPrintCommand(),\n\t\t\thostsCommand(),\n\t\t\tinspectCommand(),\n\t\t\tlistCommand(),\n\t\t\tloginCommand(),\n\t\t\tlogoutCommand(),\n\t\t\tneedsRenewalCommand(),\n\t\t\t// proxyCommand(),\n\t\t\tproxycommandCommand(),\n\t\t\trekeyCommand(),\n\t\t\trenewCommand(),\n\t\t\trevokeCommand(),\n\t\t},\n\t}\n\n\tcommand.Register(cmd)\n}", "func (ssh *SSHConfig) Exec(cmdString string) error {\n\ttunnels, sshConfig, err := ssh.CreateTunnels()\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, cmdString, false)\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tbash, err := exec.LookPath(\"bash\")\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tvar args []string\n\tif cmdString == \"\" {\n\t\targs = []string{sshCmdString}\n\t} else {\n\t\targs = []string{\"-c\", sshCmdString}\n\t}\n\terr = syscall.Exec(bash, args, nil)\n\tnerr := utils.LazyRemove(keyFile.Name())\n\tif nerr != nil {\n\t}\n\treturn err\n}", "func Test_SSH(t *testing.T) {\n\tvar cipherList []string\n\tsession, err := connect(username, password, ip, key, port, cipherList, nil)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tdefer session.Close()\n\n\tcmdlist := strings.Split(cmd, \";\")\n\tstdinBuf, err := session.StdinPipe()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar outbt, errbt bytes.Buffer\n\tsession.Stdout = &outbt\n\n\tsession.Stderr = &errbt\n\terr = session.Shell()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tfor _, c := range cmdlist {\n\t\tc = c + \"\\n\"\n\t\tstdinBuf.Write([]byte(c))\n\n\t}\n\tsession.Wait()\n\tt.Log((outbt.String() + errbt.String()))\n\treturn\n}", "func ExecSSH(ctx context.Context, id Identity, cmd []string, opts plugin.ExecOptions) (plugin.ExecCommand, error) {\n\t// find port, username, etc from .ssh/config\n\tport, err := ssh_config.GetStrict(id.Host, \"Port\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := id.User\n\tif user == \"\" {\n\t\tif user, err = ssh_config.GetStrict(id.Host, \"User\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif user == \"\" {\n\t\tuser = \"root\"\n\t}\n\n\tstrictHostKeyChecking, err := ssh_config.GetStrict(id.Host, \"StrictHostKeyChecking\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconnection, err := sshConnect(id.Host, port, user, strictHostKeyChecking != \"no\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to connect: %s\", err)\n\t}\n\n\t// Run command via session\n\tsession, err := connection.NewSession()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create session: %s\", err)\n\t}\n\n\tif opts.Tty {\n\t\t// sshd only processes signal codes if a TTY has been allocated. So set one up when requested.\n\t\tmodes := ssh.TerminalModes{ssh.ECHO: 0, ssh.TTY_OP_ISPEED: 14400, ssh.TTY_OP_OSPEED: 14400}\n\t\tif err := session.RequestPty(\"xterm\", 40, 80, modes); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to setup a TTY: %v\", err)\n\t\t}\n\t}\n\n\texecCmd := plugin.NewExecCommand(ctx)\n\tsession.Stdin, session.Stdout, session.Stderr = opts.Stdin, execCmd.Stdout(), execCmd.Stderr()\n\n\tif opts.Elevate {\n\t\tcmd = append([]string{\"sudo\"}, cmd...)\n\t}\n\n\tcmdStr := shellquote.Join(cmd...)\n\tif err := session.Start(cmdStr); err != nil {\n\t\treturn nil, err\n\t}\n\texecCmd.SetStopFunc(func() {\n\t\t// Close the session on context cancellation. Copying will block until there's more to read\n\t\t// from the exec output. For an action with no more output it may never return.\n\t\t// If a TTY is setup and the session is still open, send Ctrl-C over before closing it.\n\t\tif opts.Tty {\n\t\t\tactivity.Record(ctx, \"Sent SIGINT on context termination: %v\", session.Signal(ssh.SIGINT))\n\t\t}\n\t\tactivity.Record(ctx, \"Closing session on context termination for %v: %v\", id.Host, session.Close())\n\t})\n\n\t// Wait for session to complete and stash result.\n\tgo func() {\n\t\terr := session.Wait()\n\t\tactivity.Record(ctx, \"Closing session for %v: %v\", id.Host, session.Close())\n\t\texecCmd.CloseStreamsWithError(nil)\n\t\tif err == nil {\n\t\t\texecCmd.SetExitCode(0)\n\t\t} else if exitErr, ok := err.(*ssh.ExitError); ok {\n\t\t\texecCmd.SetExitCode(exitErr.ExitStatus())\n\t\t} else {\n\t\t\texecCmd.SetExitCodeErr(err)\n\t\t}\n\t}()\n\treturn execCmd, nil\n}", "func connect() cli.Command { // nolint: gocyclo\n\tcommand := cli.Command{\n\t\tName: \"connect\",\n\t\tAliases: []string{\"conn\"},\n\t\tUsage: \"Get a shell from a vm\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"user\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"ssh login user\",\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: \"private key path (default: ~/.ssh/id_rsa)\",\n\t\t\t},\n\t\t},\n\t\tAction: func(c *cli.Context) error {\n\t\t\tvar name, loginUser, key string\n\t\t\tvar vmID int\n\t\t\tnameFound := false\n\t\t\tnargs := c.NArg()\n\t\t\tswitch {\n\t\t\tcase nargs == 1:\n\t\t\t\t// Parse flags\n\t\t\t\tif c.String(\"user\") != \"\" {\n\t\t\t\t\tloginUser = c.String(\"user\")\n\t\t\t\t} else {\n\t\t\t\t\tusr, _ := user.Current()\n\t\t\t\t\tloginUser = usr.Name\n\t\t\t\t}\n\n\t\t\t\tif c.String(\"key\") != \"\" {\n\t\t\t\t\tkey, _ = filepath.Abs(c.String(\"key\"))\n\t\t\t\t} else {\n\t\t\t\t\tusr, err := user.Current()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\n\t\t\t\t\tkey = usr.HomeDir + \"/.ssh/id_rsa\"\n\t\t\t\t}\n\t\t\t\tname = c.Args().First()\n\t\t\t\tcli, err := client.NewEnvClient()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tlistArgs := filters.NewArgs()\n\t\t\t\tlistArgs.Add(\"ancestor\", VMLauncherContainerImage)\n\t\t\t\tcontainers, err := cli.ContainerList(context.Background(),\n\t\t\t\t\ttypes.ContainerListOptions{\n\t\t\t\t\t\tQuiet: false,\n\t\t\t\t\t\tSize: false,\n\t\t\t\t\t\tAll: true,\n\t\t\t\t\t\tLatest: false,\n\t\t\t\t\t\tSince: \"\",\n\t\t\t\t\t\tBefore: \"\",\n\t\t\t\t\t\tLimit: 0,\n\t\t\t\t\t\tFilters: listArgs,\n\t\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tfor id, container := range containers {\n\t\t\t\t\tif container.Names[0][1:] == name {\n\t\t\t\t\t\tnameFound = true\n\t\t\t\t\t\tvmID = id\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !nameFound {\n\t\t\t\t\tfmt.Printf(\"Unable to find a running vm with name: %s\", name)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t} else {\n\t\t\t\t\tvmIP := containers[vmID].NetworkSettings.Networks[\"bridge\"].IPAddress\n\t\t\t\t\tgetNewSSHConn(loginUser, vmIP, key)\n\t\t\t\t}\n\n\t\t\tcase nargs == 0:\n\t\t\t\tfmt.Println(\"No name provided as argument.\")\n\t\t\t\tos.Exit(1)\n\n\t\t\tcase nargs > 1:\n\t\t\t\tfmt.Println(\"Only one argument is allowed\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn command\n}", "func (ssh *SSHConfig) Enter() error {\n\ttunnels, sshConfig, err := ssh.CreateTunnels()\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, \"\", false)\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tbash, err := exec.LookPath(\"bash\")\n\tif err != nil {\n\t\tfor _, t := range tunnels {\n\t\t\tnerr := t.Close()\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error closing ssh tunnel: %v\", nerr)\n\t\t\t}\n\t\t}\n\t\tif keyFile != nil {\n\t\t\tnerr := utils.LazyRemove(keyFile.Name())\n\t\t\tif nerr != nil {\n\t\t\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tproc := exec.Command(bash, \"-c\", sshCmdString)\n\tproc.Stdin = os.Stdin\n\tproc.Stdout = os.Stdout\n\tproc.Stderr = os.Stderr\n\terr = proc.Run()\n\tnerr := utils.LazyRemove(keyFile.Name())\n\tif nerr != nil {\n\t\tlog.Warnf(\"Error removing file %v\", nerr)\n\t}\n\treturn err\n}", "func ExecCmdBgWithSudoAndCtx(ctx context.Context, command string) (int, chan error) {\n\tcmdStatus := make(chan error)\n\n\t// Use sudo to raise privileges (sysattrs require capabilities).\n\tif !strings.HasPrefix(command, \"sudo\") {\n\t\tcommand = fmt.Sprintf(\"sudo %s\", command)\n\t}\n\n\tcommand, args, err := ParseCmd(command)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to parse command\\n\")\n\t\tcmdStatus <- &failedToParseCmd{command: command, err: err}\n\t\treturn -1, cmdStatus\n\t}\n\n\tcmd := exec.Command(command, args...) // CommandContext can't be used due to sudo privileges\n\tcmd.Stderr = os.Stderr\n\n\tpid := atomic.Int64{}\n\twg := sync.WaitGroup{}\n\n\t// Start the command in a separate, pinned and locked goroutine (to a single CPU and OS thread).\n\t// TODO: Adjust here so amount of CPUs is controlled ?\n\n\twg.Add(1)\n\tgo func(pid *atomic.Int64) {\n\t\t// Will make the command to inherit the current process' CPU affinity.\n\t\tPinProccessToCPU() // pin this goroutine to a specific CPU\n\t\truntime.LockOSThread() // wire this goroutine to a specific OS thread\n\t\tdefer runtime.UnlockOSThread() // unlock the thread when we're done\n\n\t\terr := cmd.Start()\n\t\tif err != nil {\n\t\t\t// This isn't a cmd exec failed error, but rather a cmd start failed error.\n\t\t\tpid.Store(-1)\n\t\t\tcmdStatus <- &failedToStartCommand{command: command, err: err}\n\t\t} else {\n\t\t\tgo func() {\n\t\t\t\t// Note: cmd exec failed errors are async and happen here on cmd.Wait().\n\t\t\t\tpid.Store(int64(cmd.Process.Pid)) // store PID\n\t\t\t\terr := cmd.Wait() // block until command exits\n\t\t\t\tpid.Store(-1) // so PID is non positive on failed executions\n\t\t\t\tcmdStatus <- err // signal command exited\n\t\t\t}()\n\t\t}\n\n\t\ttime.Sleep(1 * time.Second) // wait 1 sec for the command to start (or not)\n\t\twg.Done() // signal command started\n\t}(&pid)\n\n\twg.Wait() // synchronize: wait for 1 sec feedback (cmd has started or not)\n\n\t// Kill the command if the context is canceled (and signal that it was killed).\n\n\tgo func(pid *atomic.Int64) {\n\t\t<-ctx.Done()\n\t\tp := pid.Load()\n\t\tif p > 0 {\n\t\t\t// discover all child processes\n\t\t\tchildPIDs, err := DiscoverChildProcesses(int(p))\n\t\t\tif err != nil {\n\t\t\t\tcmdStatus <- &failedToKillProcess{command: command, err: err}\n\t\t\t}\n\t\t\t// kill all child processes (sudo creates childs in new process group)\n\t\t\tfor _, childPID := range childPIDs {\n\t\t\t\terr := SudoKillProcess(childPID, false)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcmdStatus <- &failedToKillProcess{command: command, err: err}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcmdStatus <- nil // signal command exited\n\t}(&pid)\n\n\t// Return the PID (or -1) and the channel to wait for the command to exit.\n\treturn int(pid.Load()), cmdStatus\n}", "func SSHClient(shell, port string) (err error) {\n\tif !util.IsCommandExist(\"ssh\") {\n\t\terr = fmt.Errorf(\"ssh must be installed\")\n\t\treturn\n\t}\n\n\t// is port mapping already done?\n\tlport := strconv.Itoa(util.RandInt(2048, 65535))\n\tto := \"127.0.0.1:\" + port\n\texists := false\n\tfor _, p := range PortFwds {\n\t\tif p.Agent == CurrentTarget && p.To == to {\n\t\t\texists = true\n\t\t\tlport = p.Lport // use the correct port\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !exists {\n\t\t// start sshd server on target\n\t\tcmd := fmt.Sprintf(\"!sshd %s %s %s\", shell, port, uuid.NewString())\n\t\tif shell != \"bash\" {\n\t\t\terr = SendCmdToCurrentTarget(cmd)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tCliPrintInfo(\"Starting sshd (%s) on target %s\", shell, strconv.Quote(CurrentTarget.Tag))\n\n\t\t\t// wait until sshd is up\n\t\t\tdefer func() {\n\t\t\t\tCmdResultsMutex.Lock()\n\t\t\t\tdelete(CmdResults, cmd)\n\t\t\t\tCmdResultsMutex.Unlock()\n\t\t\t}()\n\t\t\tfor {\n\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\tres, exists := CmdResults[cmd]\n\t\t\t\tif exists {\n\t\t\t\t\tif strings.Contains(res, \"success\") {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr = fmt.Errorf(\"Start sshd failed: %s\", res)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// set up port mapping for the ssh session\n\t\tCliPrintInfo(\"Setting up port mapping for sshd\")\n\t\tpf := &PortFwdSession{}\n\t\tpf.Ctx, pf.Cancel = context.WithCancel(context.Background())\n\t\tpf.Lport, pf.To = lport, to\n\t\tgo func() {\n\t\t\terr = pf.RunPortFwd()\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"PortFwd failed: %v\", err)\n\t\t\t\tCliPrintError(\"Start port mapping for sshd: %v\", err)\n\t\t\t}\n\t\t}()\n\t\tCliPrintInfo(\"Waiting for response from %s\", CurrentTarget.Tag)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t// wait until the port mapping is ready\n\texists = false\nwait:\n\tfor i := 0; i < 100; i++ {\n\t\tif exists {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tfor _, p := range PortFwds {\n\t\t\tif p.Agent == CurrentTarget && p.To == to {\n\t\t\t\texists = true\n\t\t\t\tbreak wait\n\t\t\t}\n\t\t}\n\t}\n\tif !exists {\n\t\terr = errors.New(\"Port mapping unsuccessful\")\n\t\treturn\n\t}\n\n\t// let's do the ssh\n\tsshPath, err := exec.LookPath(\"ssh\")\n\tif err != nil {\n\t\tCliPrintError(\"ssh not found, please install it first: %v\", err)\n\t}\n\tsshCmd := fmt.Sprintf(\"%s -p %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1\",\n\t\tsshPath, lport)\n\tCliPrintSuccess(\"Opening SSH session for %s in new window. \"+\n\t\t\"If that fails, please execute command %s manaully\",\n\t\tCurrentTarget.Tag, strconv.Quote(sshCmd))\n\n\t// agent name\n\tname := CurrentTarget.Hostname\n\tlabel := Targets[CurrentTarget].Label\n\tif label != \"nolabel\" && label != \"-\" {\n\t\tname = label\n\t}\n\treturn TmuxNewWindow(fmt.Sprintf(\"%s-%s\", name, shell), sshCmd)\n}", "func (c *service) Client() *ssh.Client {\n\treturn c.client\n}", "func Bootstrap(host, sshConfigPath, executable string, minionConfig *MinionConfig, masterCreds *Creds) (*Client, error) {\n\tvar gofigureClient *Client\n\n\tsshConfig, connectString, err := ssher.ClientConfig(host, sshConfigPath)\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\n\tsshConn, err := ssh.Dial(\"tcp\", connectString, sshConfig)\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\tdefer sshConn.Close()\n\n\t// TODO kill existing process?\n\n\tsftpClient, err := sftp.NewClient(sshConn)\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\tdefer sftpClient.Close()\n\n\terr = putfile(sftpClient, executable, path.Base(executable), 0700)\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\n\tfor _, filename := range []string{\n\t\tminionConfig.Creds.CAFile,\n\t\tminionConfig.Creds.CertFile,\n\t\tminionConfig.Creds.KeyFile,\n\t} {\n\t\terr = putfile(sftpClient, filename, path.Base(filename), 0600)\n\t\tif err != nil {\n\t\t\treturn gofigureClient, err\n\t\t}\n\t}\n\n\tsession, err := sshConn.NewSession()\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\tdefer session.Close()\n\n\terr = session.Start(fmt.Sprintf(\"./%s serve --bind %s --port %d --caFile %s --certFile %s --keyFile %s </dev/null &>/dev/null\",\n\t\tpath.Base(executable),\n\t\tminionConfig.Bind,\n\t\tminionConfig.Port,\n\t\tpath.Base(minionConfig.Creds.CAFile),\n\t\tpath.Base(minionConfig.Creds.CertFile),\n\t\tpath.Base(minionConfig.Creds.KeyFile),\n\t))\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\n\tsplitConnectString := strings.Split(connectString, \":\")\n\tgrpcConnectString := fmt.Sprintf(\"%s:%d\", splitConnectString[0], minionConfig.Port)\n\n\tconn, err := ConnectGRPC(grpcConnectString, masterCreds.CAFile, masterCreds.CertFile, masterCreds.KeyFile)\n\tif err != nil {\n\t\treturn gofigureClient, err\n\t}\n\n\treturn &Client{GofigureClient: pb.NewGofigureClient(conn)}, nil\n}", "func (ins *EC2RemoteClient) RunCommand(cmd string) (exitStatus int, err error) {\n\texitStatus, err = ins.cmdClient.RunCommand(cmd)\n\treturn exitStatus, err\n}", "func Run(c *cli.Context) {\n\tport, err := osExpandAndVerifyGlobal(c, \"port\")\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tcommand, err := osExpandAndVerify(c, \"command\")\n\tif err != nil {\n\t\tfail(err)\n\t}\n\thost, err := osExpandAndVerify(c, \"host\")\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tuser, err := osExpandAndVerify(c, \"user\")\n\tif err != nil {\n\t\tfail(err)\n\t}\n\tconnection := c.String(\"connection\")\n\tif connection == ansible.ConnectionWinRM {\n\t\tpassword, err := osExpandAndVerify(c, \"password\")\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t}\n\t\terr = winrm.RemoteWinRmCommand(user, password, host, port, command, nil, nil, \"\")\n\t} else {\n\t\tprivatekey, err := osExpandAndVerify(c, \"privatekey\")\n\t\tif err != nil {\n\t\t\tfail(err)\n\t\t}\n\t\tenvVars := make(map[string]string)\n\t\terr = ssh.RemoteSSHCommand(user, privatekey, host, port, command, envVars)\n\t}\n\tif err != nil {\n\t\tlog.Err(\"Failed: %v\", err)\n\t}\n}", "func Exec(config *ssh.ClientConfig, addr string, workDir string, cmd string, nixConf string) (bytes.Buffer, error) {\n\tvar b bytes.Buffer // import \"bytes\"\n\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", net.JoinHostPort(addr, \"22\"), config)\n\tif err != nil {\n\t\treturn b, err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn b, err\n\t}\n\tdefer session.Close()\n\n\tsession.Stderr = os.Stderr // get output\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\n\t// Finally, run the command\n\tfullCmd := \". ~/.nix-profile/etc/profile.d/nix.sh && cd \" + workDir + \" && nix-shell \" + nixConf + \" --command '\" + cmd + \"'\"\n\tfmt.Println(fullCmd)\n\terr = session.Run(fullCmd)\n\treturn b, err\n}", "func (c *SSHCommand) Start() error {\n\treturn c.cmd.Start()\n}", "func (s *SSHer) Run(cmd string) (output []byte, err error) {\n\tvar session *ssh.Session\n\tif session, err = s.client.NewSession(); err != nil {\n\t\treturn\n\t}\n\tdefer session.Close()\n\n\tif output, err = session.CombinedOutput(cmd); err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func newSSHClient(user, pass, host string) (*ssh.Client, error) {\n\tsshConfig := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{ssh.Password(pass)},\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\tsshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()\n\tclient, err := ssh.Dial(\"tcp\", host, sshConfig)\n\tif err != nil {\n\t\treturn nil, errors.New(strings.Join([]string{\"ssh dial error: \", err.Error()}, \"\"))\n\t}\n\treturn client, nil\n}", "func NewClientSSH(client *ssh.Client) Client {\n\treturn &sshClient{client: client}\n}", "func (e *EdgeSwitchClient) newClient() (*ssh.Client, error) {\n\tsshConfig := &ssh.ClientConfig{\n\t\tUser: DEFAULT_USER,\n\t\tAuth: []ssh.AuthMethod{ssh.Password(DEFAULT_USER)},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t}\n\n\tclient, err := ssh.Dial(\"tcp\", e.ipaddress, sshConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func (s *replayService) Client() *ssh.Client {\n\treturn &ssh.Client{}\n}", "func (svc *SSHService) Run(hostName, cmd string) (int, string, string, error) {\n\tvar stdOut, stdErr string\n\tvar retCode int\n\tvar err error\n\n\thostSvc := NewHostService(svc.provider)\n\thost, err := hostSvc.Get(hostName)\n\tif err != nil {\n\t\treturn 0, \"\", \"\", logicErrf(err, \"no host found with name or id '%s'\", hostName)\n\t}\n\n\t// retrieve ssh config to perform some commands\n\tssh, err := svc.GetConfig(host)\n\n\tif err != nil {\n\t\treturn 0, \"\", \"\", infraErr(err)\n\t}\n\n\terr = retry.WhileUnsuccessfulDelay1SecondWithNotify(\n\t\tfunc() error {\n\t\t\tretCode, stdOut, stdErr, err = svc.run(ssh, cmd)\n\t\t\treturn err\n\t\t},\n\t\t2*time.Minute,\n\t\tfunc(t retry.Try, v Verdict.Enum) {\n\t\t\tif v == Verdict.Retry {\n\t\t\t\tlog.Printf(\"Remote SSH service on host '%s' isn't ready, retrying...\\n\", hostName)\n\t\t\t}\n\t\t},\n\t)\n\tif err != nil {\n\t\terr = infraErr(err)\n\t}\n\n\treturn retCode, stdOut, stdErr, err\n}", "func testSSHToPublicHost(t *testing.T, terraformOptions *terraform.Options) {\n\t//get the GCP instance\n\tproject := terraformOptions.Vars[\"project\"].(string)\n\tinstanceName := terraformOptions.Vars[\"name\"].(string)\n\tinstance := gcp.FetchInstance(t, project, instanceName)\n\n\t// generate a ssh key pair\n\tkeyPair := ssh.GenerateRSAKeyPair(t, 2048)\n\n\t// add the public ssh key to the compute engine metadata\n\tsshUsername := \"terratest\"\n\tpublicKey := keyPair.PublicKey\n\tinstance.AddSshKey(t, sshUsername, publicKey)\n\n\t// Run `terraform output` to get the value of an output variable\n\tpublicInstanceIP := terraform.Output(t, terraformOptions, \"compute_engine_public_ip\")\n\n\t// We're going to try to SSH to the instance IP, using the Key Pair we created earlier, and the user \"terratest\",\n\t// as we know the Instance is running an Ubuntu AMI that has such a user\n\tpublicHost := ssh.Host{\n\t\tHostname: publicInstanceIP,\n\t\tSshKeyPair: keyPair,\n\t\tSshUserName: sshUsername,\n\t}\n\n\t// It can take a minute or so for the Instance to boot up, so retry a few times\n\tmaxRetries := 10\n\ttimeBetweenRetries := 5 * time.Second\n\tdescription := fmt.Sprintf(\"SSH to public host %s\", publicInstanceIP)\n\n\t// Run a simple echo command on the server\n\texpectedText := \"Hello, World\"\n\tcommand := fmt.Sprintf(\"echo -n '%s'\", expectedText)\n\n\t// Verify that we can SSH to the Instance and run commands\n\tretry.DoWithRetry(t, description, maxRetries, timeBetweenRetries, func() (string, error) {\n\t\tactualText, err := ssh.CheckSshCommandE(t, publicHost, command)\n\n\t\tif err != nil {\n\t\t\tlogger.Log(t, emoji.Sprint(\"--- :cross_mark: FAIL: testSSHToPublicHost\"))\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tif strings.TrimSpace(actualText) != expectedText {\n\t\t\tlogger.Log(t, emoji.Sprint(\"--- :cross_mark: FAIL: testSSHToPublicHost\"))\n\t\t\treturn \"\", fmt.Errorf(\"Expected SSH command to return '%s' but got '%s'\", expectedText, actualText)\n\t\t}\n\n\t\tlogger.Log(t, emoji.Sprint(\"--- :check_mark_button: PASS: testSSHToPublicHost\"))\n\t\treturn \"\", nil\n\t})\n}", "func DialSSHWithPassword(addr string, username string, password string, cb ssh.HostKeyCallback) (Client, error) {\n\treturn dialSSH(addr, username, ssh.Password(password), cb)\n}", "func (client *Client) Shell() error {\n\tsession, err := client.StartSession(true, true)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to contact server[%s]: %s\", client.Config.Host, err)\n\t}\n\tdefer session.Close()\n\n\t// Start remote shell\n\tif err := session.Shell(); err != nil {\n\t\treturn fmt.Errorf(\"failed to start shell: %s\", err)\n\t}\n\n\t// wait for the ssh connection the be created and for the shell to stop before continuing\n\t// Wait for the SCP connection to close, meaning it has consumed all\n\t// our data and has completed. Or has errored.\n\n\tif err := session.Wait(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CheckSshCommandWithRetry(t testing.TestingT, host Host, command string, retries int, sleepBetweenRetries time.Duration, f ...func(testing.TestingT, Host, string) (string, error)) string {\n\thandler := CheckSshCommandE\n\tif f != nil {\n\t\thandler = f[0]\n\t}\n\tout, err := CheckSshCommandWithRetryE(t, host, command, retries, sleepBetweenRetries, handler)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn out\n}", "func (client *SSHClient) RunCommand(cmd *SSHCommand) error {\n\tvar (\n\t\tsession *ssh.Session\n\t\terr error\n\t)\n\tif session, err = client.newSession(); err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\tif err = client.prepareCommand(session, cmd); err != nil {\n\t\treturn err\n\t}\n\t// Must sleep here.\n\ttime.Sleep(5)\n\terr = session.Run(cmd.Path)\n\treturn err\n}", "func (c *Config) Shell(inReader io.Reader, outWriter, errWriter io.Writer) error {\n\terr := c.setClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.Close()\n\n\tsession, err := c.client.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tsession.Stdout = ansicolor.NewAnsiColorWriter(outWriter)\n\tsession.Stderr = ansicolor.NewAnsiColorWriter(errWriter)\n\tsession.Stdin = inReader\n\t// in, _ := session.StdinPipe()\n\n\tmodes := ssh.TerminalModes{\n\t\t// ssh.ECHO: 0, // Disable echoing\n\t\t// ssh.IGNCR: 1, // Ignore CR on input\n\t\tssh.ECHO: 1, // Print what I type\n\t\tssh.ECHOCTL: 0, // Don't print control chars\n\t\tssh.TTY_OP_ISPEED: 115200, // baud in\n\t\tssh.TTY_OP_OSPEED: 115200, // baud out\n\t}\n\n\th, w := 80, 40\n\tvar termFD int\n\tvar ok bool\n\tif termFD, ok = isTerminal(inReader); ok {\n\t\tw, h, _ = terminal.GetSize(termFD)\n\t}\n\n\ttermState, _ := terminal.MakeRaw(termFD)\n\tdefer terminal.Restore(termFD, termState)\n\n\t// Request pseudo terminal\n\t// if err := session.RequestPty(\"xterm\", h, w, modes); err != nil {\n\t// if err := session.RequestPty(\"xterm-256color\", h, w, modes); err != nil {\n\t// if err := session.RequestPty(\"vt220\", h, w, modes); err != nil {\n\t// if err := session.RequestPty(\"vt100\", h, w, modes); err != nil {\n\tif err := session.RequestPty(\"xterm-256color\", h, w, modes); err != nil {\n\t\treturn fmt.Errorf(\"request for pseudo terminal failed: %s\", err)\n\t}\n\n\t// Start remote shell\n\tif err := session.Shell(); err != nil {\n\t\treturn fmt.Errorf(\"failed to start shell: %s\", err)\n\t}\n\n\treturn session.Wait()\n\n\t// // Handle control + C\n\t// ch := make(chan os.Signal, 1)\n\t// signal.Notify(ch, os.Interrupt)\n\t// go func() {\n\t// \tfor {\n\t// \t\t<-ch\n\t// \t\tfmt.Println(\"^C\")\n\t// \t\tfmt.Fprint(in, \"\\n\")\n\t// \t\t//fmt.Fprint(in, '\\t')\n\t// \t}\n\t// }()\n\n\t// // Accepting commands\n\t// for {\n\t// \treader := bufio.NewReader(i)\n\t// \tstr, _ := reader.ReadString('\\n')\n\t// \tfmt.Fprint(in, str)\n\t// }\n}", "func CheckSshCommandWithRetryE(t testing.TestingT, host Host, command string, retries int, sleepBetweenRetries time.Duration, f ...func(testing.TestingT, Host, string) (string, error)) (string, error) {\n\thandler := CheckSshCommandE\n\tif f != nil {\n\t\thandler = f[0]\n\t}\n\treturn retry.DoWithRetryE(t, fmt.Sprintf(\"Checking SSH connection to %s\", host.Hostname), retries, sleepBetweenRetries, func() (string, error) {\n\t\treturn handler(t, host, command)\n\t})\n}", "func (s *sshNativeTask) run() (interface{}, error) {\n\tclient, err := s.newClient()\n\t// create session\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer session.Close()\n\n\t// run cmd\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tsession.Stdout = &stdout\n\tsession.Stderr = &stderr\n\n\tctx := createContext(s.Host)\n\tif err := session.Run(s.Cmd); err != nil {\n\t\t// if of type ExitError, then its a remote issue, add to code\n\t\twaitmsg, ok := err.(*ssh.ExitError)\n\t\tif ok {\n\t\t\tctx.Response.Code = waitmsg.ExitStatus()\n\t\t} else {\n\t\t\t// else return err\n\t\t\treturn ctx, err\n\t\t}\n\t}\n\n\tctx.Response.Stdout = stdout.String()\n\tctx.Response.Stderr = stderr.String()\n\n\treturn ctx, nil\n}", "func (sc *ScanClient) ScanSh(hubScheme string, host string, port int, username string, password string, path string, projectName string, versionName string, scanName string) error {\n\tif err := sc.ensureScanClientIsDownloaded(hubScheme, host, port, username, password); err != nil {\n\t\treturn errors.Annotate(err, \"cannot run scan.cli.sh\")\n\t}\n\tstartTotal := time.Now()\n\n\tcmd := exec.Command(sc.scanClientInfo.ScanCliShPath(),\n\t\t\"-Xms512m\",\n\t\t\"-Xmx4096m\",\n\t\t\"-Dblackduck.scan.cli.benice=true\",\n\t\t\"-Dblackduck.scan.skipUpdate=true\",\n\t\t\"-Done-jar.silent=true\",\n\t\t// \"-Done-jar.jar.path=\"+scanCliImplJarPath,\n\t\t// \"-jar\", scanCliJarPath,\n\t\t\"--host\", host,\n\t\t\"--port\", fmt.Sprintf(\"%d\", port),\n\t\t\"--scheme\", hubScheme,\n\t\t\"--project\", projectName,\n\t\t\"--release\", versionName,\n\t\t\"--username\", username,\n\t\t\"--name\", scanName,\n\t\tsc.getTLSVerification(),\n\t\t\"-v\",\n\t\tpath)\n\tcmd.Env = append(cmd.Env, fmt.Sprintf(\"BD_HUB_PASSWORD=%s\", password))\n\n\tlog.Infof(\"running command %+v for path %s\\n\", cmd, path)\n\tstartScanClient := time.Now()\n\tstdoutStderr, err := cmd.CombinedOutput()\n\n\trecordScanClientDuration(time.Now().Sub(startScanClient), err == nil)\n\trecordTotalScannerDuration(time.Now().Sub(startTotal), err == nil)\n\n\tif err != nil {\n\t\trecordScannerError(\"scan.cli.sh failed\")\n\t\tlog.Errorf(\"scan.cli.sh failed for path %s with error %s and output:\\n%s\\n\", path, err.Error(), string(stdoutStderr))\n\t\treturn errors.Trace(err)\n\t}\n\tlog.Infof(\"successfully completed scan.cli.sh for path %s\", path)\n\tlog.Debugf(\"output from path %s: %s\", path, stdoutStderr)\n\treturn nil\n}", "func (host *Host) SSHRead(job *Job, command string) (out string, err error) {\n\tproc, err := host.startSSH(job, command)\n\tclose(proc.Stdin())\n\tfor {\n\t\tselect {\n\t\tcase line, ok := <-proc.Stdout():\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tout = line\n\t\tcase line, ok := <-proc.Stderr():\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thost.logger.Println(line)\n\t\tcase err = <-proc.Done():\n\t\t\treturn\n\t\tcase <-time.After(job.Timeout):\n\t\t\treturn \"\", ErrorTimeout\n\t\tcase <-host.cancel:\n\t\t\tif proc.IsAlive() {\n\t\t\t\tproc.Signal(os.Interrupt)\n\t\t\t}\n\t\t\treturn \"\", ErrorCancel\n\t\t}\n\t}\n}", "func (ins *EC2RemoteClient) makeReady() error {\n\t// Check Instance is running - will error if instance doesn't exist\n\tresult, err := ins.ec2Client.DescribeInstanceStatus(&ec2.DescribeInstanceStatusInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting instance status : %s\", err)\n\t}\n\n\t// Start instance if needed\n\tif len(result.InstanceStatuses) == 0 || *result.InstanceStatuses[0].InstanceState.Name != \"running\" {\n\t\terr = ins.startInstance()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error starting instance : %s\", err)\n\t\t}\n\t}\n\n\t// Get Public IP address from ec2\n\terr = ins.getIPAddress()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting IP address : %s\", err)\n\t}\n\n\t// Set up SSH connection\n\tins.cmdClient, err = sshCmdClient.NewSSHCmdClient(ins.instanceIP, ins.sshCredentials)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Check we can at least run a trivial command\n\texitStatus, err := ins.RunCommand(\"true\")\n\tif err != nil || exitStatus != 0 {\n\t\treturn fmt.Errorf(\"Error running commands on instance : %s\", err)\n\t}\n\n\treturn err\n}", "func proxyCommand(w http.ResponseWriter, r *http.Request) {\n\tr.ParseForm()\n\tcommand := r.FormValue(\"command\")\n\targs := strings.Split(command, \" \")\n\n\tif len(args) == 0 {\n\t\tfmt.Fprintf(w, \"Bad command (%s)\\n\", command)\n\t\treturn\n\t}\n\t// If this is \"cd\", then change working directory.\n\tif args[0] == \"cd\" {\n\t\tif len(args) < 2 {\n\t\t\tfmt.Fprintln(w, \"'cd' must be followed with new directory!\")\n\t\t} else {\n\t\t\terr := os.Chdir(args[1])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(w, err.Error())\n\t\t\t} else {\n\t\t\t\tfmt.Fprintln(w, \"Switched directory to\", args[1])\n\t\t\t}\n\t\t\tshellDir = args[1]\n\t\t}\n\t\treturn\n\t}\n\t// Expand any arguments with wildcard.\n\tfullArgs := []string{}\n\tfor _, arg := range args {\n\t\tif strings.Contains(arg, \"*\") {\n\t\t\tmatches, err := filepath.Glob(arg)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Can't parse glob: %s [%s]\\n\", arg, err.Error())\n\t\t\t} else {\n\t\t\t\tfullArgs = append(fullArgs, matches...)\n\t\t\t}\n\t\t} else {\n\t\t\tfullArgs = append(fullArgs, arg)\n\t\t}\n\t}\n\n\t// Check for \"&\" at end to signify asynchronous command like server starts.\n\tlastArg := len(fullArgs) - 1\n\trunBackground := false\n\tif fullArgs[lastArg] == \"&\" {\n\t\trunBackground = true\n\t\tfullArgs = fullArgs[:lastArg]\n\t}\n\n\t// Do the command\n\tcmd := exec.Command(fullArgs[0], fullArgs[1:]...)\n\tvar out []byte\n\tvar err error\n\tif runBackground {\n\t\terr = cmd.Start()\n\t\tout = []byte(fmt.Sprintf(\"Ran background job: %s\\n\", command))\n\t} else {\n\t\tout, err = cmd.Output()\n\t}\n\tif err != nil {\n\t\tfmt.Println(\"Error: \", err.Error())\n\t\tfmt.Fprintln(w, err.Error())\n\t} else {\n\t\tfmt.Fprintln(w, string(out))\n\t}\n}", "func logCommand(t *testing.T, client ssh.Client, command string) {\n\tstdout := new(bytes.Buffer)\n\terr := client.Run(command+\" 2>&1\", stdout, os.Stderr)\n\tt.Logf(\"+ %s\\n%s\", command, stdout.String())\n\tif err != nil {\n\t\tt.Logf(\"`%s` failed with %v:\\n\", command, err)\n\t}\n}", "func (v *MachineVM) SSH(name string, opts machine.SSHOptions) error {\n\tif !v.isRunning() {\n\t\treturn errors.Errorf(\"vm %q is not running.\", v.Name)\n\t}\n\n\tsshDestination := v.RemoteUsername + \"@localhost\"\n\tport := strconv.Itoa(v.Port)\n\n\targs := []string{\"-i\", v.IdentityPath, \"-p\", port, sshDestination, \"-o\", \"UserKnownHostsFile /dev/null\", \"-o\", \"StrictHostKeyChecking no\"}\n\tif len(opts.Args) > 0 {\n\t\targs = append(args, opts.Args...)\n\t} else {\n\t\tfmt.Printf(\"Connecting to vm %s. To close connection, use `~.` or `exit`\\n\", v.Name)\n\t}\n\n\tcmd := exec.Command(\"ssh\", args...)\n\tlogrus.Debugf(\"Executing: ssh %v\\n\", args)\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdin = os.Stdin\n\n\treturn cmd.Run()\n}", "func NewSSHCommand(p *config.KfParams) *cobra.Command {\n\tvar (\n\t\tdisableTTY bool\n\t\tcommand []string\n\t\tcontainer string\n\t)\n\n\tcmd := &cobra.Command{\n\t\tUse: \"ssh APP_NAME\",\n\t\tShort: \"Open a shell on an App instance.\",\n\t\tExample: `\n\t\t# Open a shell to a specific App\n\t\tkf ssh myapp\n\n\t\t# Open a shell to a specific Pod\n\t\tkf ssh pod/myapp-revhex-podhex\n\n\t\t# Start a different command with args\n\t\tkf ssh myapp -c /my/command -c arg1 -c arg2\n\t\t`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tLong: `\n\t\tOpens a shell on an App instance using the Pod exec endpoint.\n\n\t\tThis command mimics CF's SSH command by opening a connection to the\n\t\tKubernetes control plane which spawns a process in a Pod.\n\n\t\tThe command connects to an arbitrary Pod that matches the App's runtime\n\t\tlabels. If you want a specific Pod, use the pod/<podname> notation.\n\n\t\tNOTE: Traffic is encrypted between the CLI and the control plane, and\n\t\tbetween the control plane and Pod. A malicious Kubernetes control plane\n\t\tcould observe the traffic.\n\t\t`,\n\t\tValidArgsFunction: completion.AppCompletionFn(p),\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx := cmd.Context()\n\t\t\tif err := p.ValidateSpaceTargeted(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstreamExec := execstreamer.Get(ctx)\n\n\t\t\tenableTTY := !disableTTY\n\t\t\tappName := args[0]\n\n\t\t\tpodSelector := metav1.ListOptions{}\n\t\t\tif strings.HasPrefix(appName, podPrefix) {\n\t\t\t\tpodName := strings.TrimPrefix(appName, podPrefix)\n\t\t\t\tpodSelector.FieldSelector = fields.OneTermEqualSelector(\"metadata.name\", podName).String()\n\t\t\t} else {\n\t\t\t\tappLabels := v1alpha1.AppComponentLabels(appName, \"app-server\")\n\t\t\t\tpodSelector.LabelSelector = labels.SelectorFromSet(appLabels).String()\n\t\t\t}\n\n\t\t\texecOpts := corev1.PodExecOptions{\n\t\t\t\tContainer: container,\n\t\t\t\tCommand: command,\n\t\t\t\tStdin: true,\n\t\t\t\tStdout: true,\n\t\t\t\tStderr: true,\n\t\t\t\tTTY: enableTTY,\n\t\t\t}\n\n\t\t\tt := term.TTY{\n\t\t\t\tOut: cmd.OutOrStdout(),\n\t\t\t\tIn: cmd.InOrStdin(),\n\t\t\t\tRaw: true,\n\t\t\t}\n\n\t\t\tsizeQueue := t.MonitorSize(t.GetSize())\n\n\t\t\tstreamOpts := remotecommand.StreamOptions{\n\t\t\t\tStdin: cmd.InOrStdin(),\n\t\t\t\tStdout: cmd.OutOrStdout(),\n\t\t\t\tStderr: cmd.ErrOrStderr(),\n\t\t\t\tTty: enableTTY,\n\t\t\t\tTerminalSizeQueue: sizeQueue,\n\t\t\t}\n\n\t\t\t// Set up a TTY locally if it's enabled.\n\t\t\tif fd, isTerm := dockerterm.GetFdInfo(streamOpts.Stdin); isTerm && enableTTY {\n\t\t\t\toriginalState, err := dockerterm.MakeRaw(fd)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tdefer dockerterm.RestoreTerminal(fd, originalState)\n\t\t\t}\n\n\t\t\treturn streamExec.Stream(ctx, podSelector, execOpts, streamOpts)\n\t\t},\n\t}\n\n\tcmd.Flags().StringArrayVarP(\n\t\t&command,\n\t\t\"command\",\n\t\t\"c\",\n\t\t[]string{\"/bin/bash\"},\n\t\t\"Command to run for the shell. Subsequent definitions will be used as args.\",\n\t)\n\n\tcmd.Flags().StringVar(\n\t\t&container,\n\t\t\"container\",\n\t\tv1alpha1.DefaultUserContainerName,\n\t\t\"Container to start the command in.\",\n\t)\n\n\tcmd.Flags().BoolVarP(\n\t\t&disableTTY,\n\t\t\"disable-pseudo-tty\",\n\t\t\"T\",\n\t\tfalse,\n\t\t\"Don't use a TTY when executing.\",\n\t)\n\n\treturn cmd\n}", "func (s *BaseAspidaListener) ExitConnectionSSH(ctx *ConnectionSSHContext) {}", "func (c *Client) copyImage(src, dst string) error {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.copyTimeoutSeconds)*time.Second)\n\tdefer cancel()\n\tcmdStr := c.skopeoCopyCmd(src, dst)\n\tlogf.Log.WithName(\"registry_client\").V(1).Info(\"Command\", cmdStr)\n\tcmdSl := strings.Split(cmdStr, \" \")\n\treturn exec.CommandContext(ctx, cmdSl[0], cmdSl[1:]...).Run()\n}", "func (cmd *EnvironmentCommand) executeCommand(client *ssh.Client, cmdLine string) error {\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tcmd.currentSession = session\n\tsession.Stdin = os.Stdin\n\tif cmd.SuppressOutput {\n\t\tsession.Stdout = &cmd.OutputBuffer\n\t\tsession.Stderr = &cmd.ErrorBuffer\n\t} else {\n\t\tsession.Stdout = io.MultiWriter(os.Stdout, &cmd.OutputBuffer)\n\t\tsession.Stderr = io.MultiWriter(os.Stderr, &cmd.ErrorBuffer)\n\t}\n\treturn session.Run(cmdLine)\n}", "func (sc *sshclient) runclient(ctx context.Context, address string) error {\n\tconn, err := ssh.Dial(\"tcp\", address, sc.config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot connect to %v: %v\", address, err)\n\t}\n\tdefer conn.Close()\n\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot open new session: %v\", err)\n\t}\n\tdefer session.Close()\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tconn.Close()\n\t}()\n\n\t/*\n\t\tfd := int(os.Stdin.Fd())\n\t\tstate, err := terminal.MakeRaw(fd)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"terminal make raw: %s\", err)\n\t\t}\n\t\tdefer terminal.Restore(fd, state)\n\t*/\n\tcurrent := console.Current()\n\tdefer current.Reset()\n\n\terr = current.SetRaw()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"terminal make raw: %s\", err)\n\t}\n\n\t// fd2 := int(os.Stdout.Fd())\n\t// w, h, err := terminal.GetSize(fd2)\n\t// if err != nil {\n\t// \treturn fmt.Errorf(\"terminal get size: %s\", err)\n\t// }\n\n\tws, err := current.Size()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"terminal get size: %s\", err)\n\t}\n\n\th := int(ws.Height)\n\tw := int(ws.Width)\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 1,\n\t\tssh.TTY_OP_ISPEED: 14400,\n\t\tssh.TTY_OP_OSPEED: 14400,\n\t}\n\n\tterm := os.Getenv(\"TERM\")\n\tif term == \"\" {\n\t\tterm = \"xterm-256color\"\n\t}\n\tif err := session.RequestPty(term, h, w, modes); err != nil {\n\t\treturn fmt.Errorf(\"session xterm: %s\", err)\n\t}\n\n\tsession.Stdout = os.Stdout\n\tsession.Stderr = os.Stderr\n\tsession.Stdin = os.Stdin\n\n\tif err := session.Shell(); err != nil {\n\t\treturn fmt.Errorf(\"session shell: %s\", err)\n\t}\n\n\tif err := session.Wait(); err != nil {\n\t\tif e, ok := err.(*ssh.ExitError); ok {\n\t\t\tswitch e.ExitStatus() {\n\t\t\tcase 130:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"ssh: %s\", err)\n\t}\n\treturn nil\n}", "func (c CrostiniGuestOS) Command(ctx context.Context, vshArgs ...string) *testexec.Cmd {\n\treturn c.VMInstance.Command(ctx, vshArgs...)\n}", "func BackgroundPlugin(transport plugin.Transport, onStop func(), plugin server.VersionedInterface,\n\tmore ...server.VersionedInterface) (server.Stoppable, <-chan struct{}) {\n\n\tdir := transport.Dir\n\tif dir == \"\" {\n\t\tdir = local.Dir()\n\t}\n\tEnsureDirExists(dir)\n\tname, _ := transport.Name.GetLookupAndType()\n\n\tsocketPath := path.Join(dir, name)\n\tpidPath := path.Join(dir, name+\".pid\")\n\treturn run(nil, socketPath, pidPath, onStop, plugin, more...)\n}", "func (c App) EstablishSSHConnection() revel.Result {\n\tsshIPHostname := strings.TrimSpace(c.Params.Get(\"ssh_ip\"))\n\tsshUser := strings.TrimSpace(c.Params.Get(\"ssh_user\"))\n\tsshPassword := c.Params.Get(\"ssh_password\")\n\tsshPort := strings.TrimSpace(c.Params.Get(\"ssh_port\"))\n\n\tvar err error\n\n\tif sshIPHostname == \"\" {\n\t\tresponse := CompileJSONResult(false, \"SSH IP is empty\")\n\t\treturn c.RenderJSON(response)\n\t} else if sshIPHostname == MockSSHHostString {\n\t\tif !MockSSHServer {\n\t\t\tgo createMockSSHServer()\n\t\t\ttime.Sleep(time.Second)\n\t\t\tMockSSHServer = true\n\t\t}\n\t\tsshIPHostname = \"127.0.0.1\"\n\t}\n\n\tif sshUser == \"\" {\n\t\tusername, err := user.Current()\n\t\tif err != nil {\n\t\t\tresponse := CompileJSONResult(false, \"You didn't specify SSH user and we were not able to determine it from your system\")\n\t\t\treturn c.RenderJSON(response)\n\t\t}\n\t\tsshUser = username.Username\n\t}\n\n\tif sshPort == \"\" {\n\t\tsshPort = \"22\"\n\t} else {\n\t\tif _, err := strconv.Atoi(sshPort); err != nil {\n\t\t\tresponse := CompileJSONResult(false, \"You specified wrong SSH port\")\n\t\t\treturn c.RenderJSON(response)\n\t\t}\n\t}\n\n\tSSHclient, SSHsession, err = createSSHSession(sshIPHostname, sshUser, sshPassword, sshPort)\n\n\tif err != nil {\n\t\tswitch err.Error() {\n\t\tcase \"cannot dial\":\n\t\t\tresponse := CompileJSONResult(false, \"We could not reach '\"+sshIPHostname+\":\"+sshPort+\"' OR login/password is incorrect\")\n\t\t\treturn c.RenderJSON(response)\n\t\tcase \"unable to create session\":\n\t\t\tresponse := CompileJSONResult(false, \"We reached '\"+sshIPHostname+\":\"+sshPort+\"' but could not create a test session\")\n\t\t\treturn c.RenderJSON(response)\n\t\tdefault:\n\t\t\tresponse := CompileJSONResult(false, err.Error())\n\t\t\treturn c.RenderJSON(response)\n\t\t}\n\t}\n\treturn nil\n}", "func (svc *SSHService) run(ssh *system.SSHConfig, cmd string) (int, string, string, error) {\n\t// Create the command\n\tsshCmd, err := ssh.Command(cmd)\n\tif err != nil {\n\t\treturn 0, \"\", \"\", err\n\t}\n\treturn sshCmd.Run()\n}", "func makeClients(cmd string, c *cli.Context) []*SSHClient.SSHClient {\n\tif c.String(\"user\") == \"\" {\n\t\tfmt.Fprintln(os.Stderr, \"Error: No --user/-u provided\")\n os.Exit(1)\n\t}\n\n\tif c.String(\"pkey\") == \"\" {\n\t\tfmt.Fprintln(os.Stderr, \"Error: No --pkey/-k provided\")\n os.Exit(1)\n\t}\n\n\tsshConfig := &ssh.ClientConfig{\n\t\tUser: c.String(\"user\"),\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tSSHClient.PublicKeyFile(c.String(\"pkey\")),\n\t\t},\n\t}\n\n\thosts := deleteEmpty(c.StringSlice(\"host\"))\n\tif len(hosts) == 0 {\n\t\tfmt.Fprintln(os.Stderr, \"Error: No --hosts/-x provided\")\n os.Exit(1)\n\t}\n\n\tclients := make([]*SSHClient.SSHClient, len(hosts))\n\tfor i, host := range hosts {\n\t\t_cmd := &SSHClient.SSHCommand{\n\t\t\tCmd: cmd,\n\t\t}\n\t\tclient := &SSHClient.SSHClient{\n\t\t\tConfig: sshConfig,\n\t\t\tHost: host,\n\t\t\tPort: 22,\n\t\t\tCmd: _cmd,\n\t\t}\n\t\tclients[i] = client\n\t}\n\n\treturn clients\n}", "func (ins *EC2RemoteClient) startInstance() error {\n\tlog.Printf(\"Starting EC2 Instance %s\", ins.InstanceID)\n\t_, err := ins.ec2Client.StartInstances(&ec2.StartInstancesInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error starting instance : %s\", err)\n\t}\n\tlog.Printf(\"Waiting for Instance %s to become ready (may take a few minutes)\", ins.InstanceID)\n\terr = ins.ec2Client.WaitUntilInstanceStatusOk(&ec2.DescribeInstanceStatusInput{InstanceIds: aws.StringSlice([]string{ins.InstanceID})})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error waiting for instance to become available : %s\", err)\n\t}\n\treturn err\n}", "func BackgroundRun(cmd *exec.Cmd, name string, debug bool) (err error) {\n\terr = runCmd(cmd, name, debug)\n\tif err != nil {\n\t\treturn\n\t}\n\tgo func() {\n\t\terr = cmd.Wait()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tlog.Info().Msgf(\"%s finished\", name)\n\t}()\n\treturn\n}", "func NewClient(config *Config) (*Client, error) {\n c := &Client{}\n\n client, err := ssh.Dial(\"tcp\", config.Host + \":\" + strconv.Itoa(config.Port), config.ClientConfig)\n if err != nil {\n return nil, err\n }\n\n c.client = client\n return c, nil\n}", "func getSSH(t *testing.T, vm *gcp.VM) (ssh.Client, error) {\n\tips, err := vm.GetIPs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &ssh.SSHClient{\n\t\tCreds: &vm.SSHCreds,\n\t\tPort: 22,\n\t}\n\n\tif onKokoro, err := isStartedByKokoro(); err != nil {\n\t\treturn nil, err\n\t} else if onKokoro {\n\t\tclient.IP = ips[gcp.PrivateIP]\n\t\tt.Logf(\"Detected that VM is started by Kokoro, so using private IP: %v\", client.IP)\n\t} else {\n\t\tclient.IP = ips[gcp.PublicIP]\n\t\tt.Logf(\"Using public VM IP: %v\", client.IP)\n\t}\n\n\tif err := client.WaitForSSH(5 * time.Minute); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}", "func (client *Client) Run() {\n\tret, val, msg := client.executeCommand()\n\tlog.Printf(\"Execute command result: %v\", ret)\n\tlog.Printf(\"Execute command value: %v\", val)\n\tlog.Printf(\"Execute command message: %v\", msg)\n}", "func (c *Config) StartAndWait(cmd *Command) error {\n\terr := c.setClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Testing:\n\tsession, err := c.client.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\t//We send the keepalive every minute in case the server has\n\t// a session timeout set.\n\tgo keepAlive(session)\n\n\tsession.Stdout = &cmd.Stdout\n\tsession.Stderr = &cmd.Stderr\n\n\tif err = session.Start(cmd.Command + \"\\n\"); err != nil {\n\t\treturn err\n\t}\n\n\terr = session.Wait()\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tcase *ssh.ExitError:\n\t\t\tcmd.ExitStatus = err.(*ssh.ExitError).ExitStatus()\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewClient(sshc *ssh.Client) (cl *Client, err error) {\n\tlogp := \"New\"\n\tcl = &Client{}\n\n\tcl.sess, err = sshc.NewSession()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: NewSession: %w\", logp, err)\n\t}\n\n\tcl.pipeIn, err = cl.sess.StdinPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: StdinPipe: %w\", logp, err)\n\t}\n\tcl.pipeOut, err = cl.sess.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: StdoutPipe: %w\", logp, err)\n\t}\n\tcl.pipeErr, err = cl.sess.StderrPipe()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: StderrPipe: %w\", logp, err)\n\t}\n\n\terr = cl.sess.RequestSubsystem(subsystemNameSftp)\n\tif err != nil {\n\t\tif err.Error() == \"ssh: subsystem request failed\" {\n\t\t\treturn nil, ErrSubsystem\n\t\t}\n\t\treturn nil, fmt.Errorf(\"%s: RequestSubsystem: %w\", logp, err)\n\t}\n\n\tcl.requestId = uint32(time.Now().Unix())\n\n\terr = cl.init()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: %w\", logp, err)\n\t}\n\n\treturn cl, nil\n}", "func (e *Engine) SSHVM(namespace, id, user, key string, term *termutil.Terminal) error {\n\tcontainer, err := e.docker.Inspect(id)\n\tif err != nil {\n\t\tfullName := internal.GenerateContainerName(namespace, id)\n\n\t\tcontainer, err = e.docker.Inspect(fullName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tip := container.NetworkSettings.IPAddress\n\tkeyPath := homedir.ExpandPath(key)\n\n\tprivateKey, err := ioutil.ReadFile(keyPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsigner, err := ssh.ParsePrivateKey(privateKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig := ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(), // nolint: gosec\n\t}\n\tconfig.SetDefaults()\n\n\tconn, err := ssh.Dial(\"tcp\", ip+\":22\", &config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer conn.Close()\n\n\tsess, err := conn.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer sess.Close()\n\n\tsess.Stdin = term.In()\n\tsess.Stdout = term.Out()\n\tsess.Stderr = term.Err()\n\n\tsz, err := term.GetWinsize()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = term.MakeRaw()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer handleError(term.Restore())\n\n\terr = sess.RequestPty(os.Getenv(\"TERM\"), int(sz.Height), int(sz.Width), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = sess.Shell()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// If our terminal window changes, signal the ssh connection\n\tstopch := make(chan struct{})\n\tdefer close(stopch)\n\n\tgo func() {\n\t\tsigch := make(chan os.Signal, 1)\n\t\tsignal.Notify(sigch, syscall.SIGWINCH)\n\n\t\tdefer signal.Stop(sigch)\n\t\tdefer close(sigch)\n\touter:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-sigch:\n\t\t\t\tsz, err := term.GetWinsize()\n\t\t\t\tif err == nil {\n\t\t\t\t\thandleError(sess.WindowChange(int(sz.Height), int(sz.Width)))\n\t\t\t\t}\n\t\t\tcase <-stopch:\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn sess.Wait()\n}", "func (k *SshCMD)RemoteRun(user string, addr string, cmd string) (string, error) {\n\t// privateKey could be read from a file, or retrieved from another storage\n\t// source, such as the Secret Service / GNOME Keyring\n\t// Authentication\n\tconfig := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(k.rsa),\n\t\t\t//ssh.Password(\"jack2017\"),\n\t\t},\n\t\tHostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {\n\t\t\treturn nil\n\t\t},\n\t\t//alternatively, you could use a password\n\t\t/*\n\t\t\tAuth: []ssh.AuthMethod{\n\t\t\t\tssh.Password(\"PASSWORD\"),\n\t\t\t},\n\t\t*/\n\t}\n\t// Connect\n\tclient, err := ssh.Dial(\"tcp\", addr+\":22222\", config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// Create a session. It is one session per command.\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer session.Close()\n\tvar b bytes.Buffer // import \"bytes\"\n\tsession.Stdout = &b // get output\n\t// you can also pass what gets input to the stdin, allowing you to pipe\n\t// content from client to server\n\t// session.Stdin = bytes.NewBufferString(\"My input\")\n\tsession.Stderr = os.Stderr\n\t// Finally, run the command\n\terr = session.Run(cmd)\n\treturn b.String(), err\n}", "func withFixedUpSSHCLI(t *testing.T) func() {\n\tt.Helper()\n\n\tsshAbsPath, err := exec.LookPath(\"ssh\")\n\tth.AssertNil(t, err)\n\n\tsshScript := `#!/bin/sh\nSSH_BIN -o PasswordAuthentication=no -o ConnectTimeout=3 -o UserKnownHostsFile=\"$HOME/.ssh/known_hosts\" $@\n`\n\tif runtime.GOOS == \"windows\" {\n\t\tsshScript = `@echo off\nSSH_BIN -o PasswordAuthentication=no -o ConnectTimeout=3 -o UserKnownHostsFile=%USERPROFILE%\\.ssh\\known_hosts %*\n`\n\t}\n\tsshScript = strings.ReplaceAll(sshScript, \"SSH_BIN\", sshAbsPath)\n\n\thome, err := os.UserHomeDir()\n\tth.AssertNil(t, err)\n\n\thomeBin := filepath.Join(home, \"bin\")\n\terr = os.MkdirAll(homeBin, 0700)\n\tth.AssertNil(t, err)\n\n\tsshScriptName := \"ssh\"\n\tif runtime.GOOS == \"windows\" {\n\t\tsshScriptName = \"ssh.bat\"\n\t}\n\n\tsshScriptFullPath := filepath.Join(homeBin, sshScriptName)\n\terr = os.WriteFile(sshScriptFullPath, []byte(sshScript), 0700)\n\tth.AssertNil(t, err)\n\n\toldPath := os.Getenv(\"PATH\")\n\tos.Setenv(\"PATH\", homeBin+string(os.PathListSeparator)+oldPath)\n\treturn func() {\n\t\tos.Setenv(\"PATH\", oldPath)\n\t\tos.RemoveAll(homeBin)\n\t}\n}", "func rerunBackground() error {\n\targs := make([]string, 0, len(os.Args))\n\tfoundBackground := false\n\tfor _, arg := range os.Args {\n\t\tif arg == \"--background\" || strings.HasPrefix(arg, \"--background=\") {\n\t\t\tfoundBackground = true\n\t\t\tcontinue\n\t\t}\n\t\targs = append(args, arg)\n\t}\n\tif !foundBackground {\n\t\targs = append(args, \"--background=false\")\n\t}\n\tcmd := exec.Command(args[0], args[1:]...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn sdnotify.Exec(cmd)\n}", "func (r *RedisStorage) do(ctx context.Context, command string, args ...interface{}) (interface{}, error) {\n\tresultCh := make(chan interface{}, 1)\n\terrorCh := hystrix.Go(CbRedisStorage, func() error {\n\t\tcon := r.Pool.Get()\n\n\t\treply, err := con.Do(command, args...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tresultCh <- reply\n\n\t\treturn nil\n\t}, nil)\n\n\tselect {\n\tcase result := <-resultCh:\n\t\t// success\n\t\treturn result, nil\n\n\tcase <-ctx.Done():\n\t\t// timeout/context cancelled\n\t\treturn nil, ctx.Err()\n\n\tcase err := <-errorCh:\n\t\t// failure\n\t\treturn nil, err\n\t}\n}", "func (eCmd *Exec) Run() int {\n\tif eCmd.allocatePTY && !isTerminal() {\n\t\tlog.Error(\"Cannot allocate pseudo-terminal without a terminal\")\n\t\treturn 1\n\t}\n\n\tlocalClient, err := eCmd.clientGetter.Client(eCmd.common.host)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn 1\n\t}\n\tdefer localClient.Close()\n\n\tcontainerClient, err := eCmd.clientGetter.ContainerClient(\n\t\tlocalClient, eCmd.targetContainer)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error getting container client\")\n\t\treturn 1\n\t}\n\n\tcontainer, err := util.GetContainer(containerClient, eCmd.targetContainer)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error getting container information\")\n\t\treturn 1\n\t}\n\n\terr = eCmd.SSHClient.Connect(containerClient.Host(), eCmd.privateKey)\n\tif err != nil {\n\t\tlog.WithError(err).Info(\"Error opening SSH connection\")\n\t\treturn 1\n\t}\n\tdefer eCmd.SSHClient.Disconnect()\n\n\tif eCmd.allocatePTY {\n\t\tif err = eCmd.SSHClient.RequestPTY(); err != nil {\n\t\t\tlog.WithError(err).Info(\"Error requesting pseudo-terminal\")\n\t\t\treturn 1\n\t\t}\n\t}\n\n\tvar flags string\n\tif eCmd.allocatePTY {\n\t\tflags = \"-it\"\n\t}\n\tcommand := strings.Join(\n\t\t[]string{\"docker exec\", flags, container.DockerID, eCmd.command}, \" \")\n\tif err = eCmd.SSHClient.Run(command); err != nil {\n\t\tlog.WithError(err).Info(\"Error running command over SSH\")\n\t\treturn 1\n\t}\n\n\treturn 0\n}", "func (c *SSHConnection) RunCommand(cmd string) ([]byte, error) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.lastUsed = time.Now()\n\n\tif c.client == nil {\n\t\treturn nil, errors.New(\"not connected\")\n\t}\n\n\tsession, err := c.client.NewSession()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not open session\")\n\t}\n\tdefer session.Close()\n\n\tvar b = &bytes.Buffer{}\n\tsession.Stdout = b\n\n\terr = session.Run(cmd)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not run command\")\n\t}\n\n\treturn b.Bytes(), nil\n}", "func (ssh *SSHConfig) Command(cmdString string) (*SSHCommand, error) {\n\treturn ssh.command(cmdString, false)\n}", "func Run(connectAs string, connectTo string, key string) {\n\ttarget := connectAs + \"@\" + connectTo\n\tlog.Info(\"Connecting as \" + target)\n\n\texecutable := \"sshpass\"\n\tparams := []string{\n\t\t\"-p\", key, \"ssh\", \"-o\", \"StrictHostKeyChecking=no\", \"-t\", \"-t\", target,\n\t}\n\tlog.Infof(\"Launching: %s %s\", executable, strings.Join(params, \" \"))\n\n\tif log.GetLevel() == log.DebugLevel {\n\t\tfor i, param := range params {\n\t\t\tif param == \"ssh\" {\n\t\t\t\ti = i + 1\n\t\t\t\t// Yes: this is crazy, but this inserts an element into a slice\n\t\t\t\tparams = append(params[:i], append([]string{\"-v\"}, params[i:]...)...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tcmd := exec.Command(executable, params...)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tcmd.Stdin = os.Stdin\n\terr := cmd.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcmd.Wait()\n\tlog.Infof(\"Just ran subprocess %d, exiting\\n\", cmd.Process.Pid)\n}", "func (client *activeClient) runCommand(c *ishell.Context) {\n\tcommand := strings.Join(c.Args, \" \")\n\tvar r string\n\targs := shared.Cmd{\n\t\tCmd: command,\n\t\tPowershell: false,\n\t}\n\n\terr := client.RPC.Call(\"API.RunCmd\", args, &r)\n\tif err != nil {\n\t\tc.Println(yellow(\"[\"+client.Client.Name+\"] \") + red(\"[!] Bad or unkown command!\"))\n\t\tc.Println(yellow(\"[\"+client.Client.Name+\"] \") + red(\"[!] \", err))\n\t}\n\n\tc.Println(r)\n}" ]
[ "0.5552612", "0.5394377", "0.5374934", "0.5220337", "0.51360375", "0.5109867", "0.5089216", "0.5080416", "0.50411", "0.5035837", "0.5011521", "0.50001675", "0.4995725", "0.49885878", "0.4986906", "0.4981291", "0.4974931", "0.49558264", "0.4928265", "0.49180338", "0.4910491", "0.49097672", "0.48974165", "0.4893289", "0.48847154", "0.48497584", "0.48459265", "0.48363638", "0.48250166", "0.48214614", "0.4813431", "0.47896576", "0.4783508", "0.47824255", "0.47706908", "0.47686106", "0.47656938", "0.47645798", "0.4763831", "0.475201", "0.4750313", "0.4739304", "0.47234446", "0.4709372", "0.47060835", "0.47006044", "0.46906713", "0.46846154", "0.467972", "0.4676833", "0.46753418", "0.4655752", "0.46513087", "0.46281448", "0.46088216", "0.4601526", "0.45968744", "0.45951438", "0.45926467", "0.45923978", "0.45894435", "0.4586429", "0.45789045", "0.45781404", "0.45739767", "0.45715934", "0.45710313", "0.45698535", "0.4568131", "0.45635873", "0.45594442", "0.45572057", "0.45566514", "0.45528755", "0.45313296", "0.45207796", "0.45118418", "0.45102108", "0.4502094", "0.450097", "0.44976306", "0.44865096", "0.4483519", "0.44791135", "0.4465564", "0.44578576", "0.44552663", "0.44499356", "0.44431764", "0.44400284", "0.44371438", "0.44370157", "0.4434294", "0.44297227", "0.44273666", "0.44032776", "0.44009888", "0.43893698", "0.4380941", "0.437529" ]
0.7470312
0
CopyFile copies a file from the local filesystem to that on the EC2 instance
func (ins *EC2RemoteClient) CopyFile(source string, destination string) error { err := ins.cmdClient.CopyFile(source, destination) return err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func copyFile(srcFile string, destFile string) error {\n\tsrcReader, err := assets.FS.Open(srcFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error opening %s file: %w\", srcFile, err)\n\t}\n\tdefer srcReader.Close()\n\n\tdestReader, err := os.Create(destFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating runtime %s file: %w\", destFile, err)\n\t}\n\tdefer destReader.Close()\n\n\t_, err = io.Copy(destReader, srcReader)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error copying source file to destination file: %w\", err)\n\t}\n\n\treturn nil\n}", "func copyFile(src, dst string) error {\n\t// copycmd := exec.Command(\"cp\", src, dst)\n\treturn nil\n}", "func (h *Host) CopyFile(file os.File, remotePath string, permissions string) error {\n\tsession, err := h.sshClient.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tscpClient := scp.Client{\n\t\tSession: session,\n\t\tTimeout: time.Second * 60,\n\t\tRemoteBinary: \"scp\",\n\t}\n\n\treturn scpClient.CopyFromFile(file, remotePath, permissions)\n}", "func copyFile(sourcePath, destPath string) error {\n\tr, err := os.Open(sourcePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\tw, err := os.Create(destPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(w, r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn w.Close()\n}", "func (n *mockAgent) copyFile(src, dst string) error {\n\treturn nil\n}", "func (c *CollectHostCopy) copyFile(src, dst string, result CollectorResult) error {\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer in.Close()\n\n\trelDest := c.relBundlePath(dst)\n\terr = result.SaveResult(c.BundlePath, relDest, in)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func CopyFile(source, destination string) error {\n\tin, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tout, err := os.Create(destination)\n\tif err != nil {\n\t\t_ = in.Close()\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(out, in)\n\tif err != nil {\n\t\t_ = in.Close()\n\t\t_ = out.Close()\n\t\treturn err\n\t}\n\n\t_ = in.Close()\n\treturn out.Close()\n}", "func FileCopy(src string, dst string) error {\n\tsrcFile, err := os.Open(src)\n\tif Error(err) {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tError(srcFile.Close())\n\t}()\n\n\tdestFile, err := os.Create(dst)\n\tif Error(err) {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tError(destFile.Close())\n\t}()\n\n\t_, err = io.Copy(destFile, srcFile)\n\tif Error(err) {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CopyFile(source string, target string) error {\n\ts, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer s.Close()\n\td, err := os.Create(target)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := io.Copy(d, s); err != nil {\n\t\td.Close()\n\t\treturn err\n\t}\n\treturn d.Close()\n}", "func copyFile(src string, dst string) {\n\tdefer wg.Done()\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\tprintErr(err)\n\t\treturn\n\t}\n\tdefer in.Close()\n\n\tout, err := os.Create(dst)\n\tif err != nil {\n\t\tprintErr(err)\n\t\treturn\n\t}\n\tdefer out.Close()\n\n\t_, err = io.Copy(out, in)\n\tif err != nil {\n\t\tprintErr(err)\n\t\treturn\n\t}\n}", "func (a *DefaultClient) Copy(srcFile, tgtFile vfs.File) error {\n\t// Can't use url.PathEscape here since that will escape everything (even the directory separators)\n\tsrcURL, err := url.Parse(strings.Replace(srcFile.URI(), \"%\", \"%25\", -1))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttgtURL, err := url.Parse(tgtFile.Location().(*Location).ContainerURL())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontainerURL := azblob.NewContainerURL(*tgtURL, a.pipeline)\n\tblobURL := containerURL.NewBlockBlobURL(utils.RemoveLeadingSlash(tgtFile.Path()))\n\tctx := context.Background()\n\tresp, err := blobURL.StartCopyFromURL(ctx, *srcURL, azblob.Metadata{}, azblob.ModifiedAccessConditions{},\n\t\tazblob.BlobAccessConditions{}, azblob.DefaultAccessTier, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor resp.CopyStatus() == azblob.CopyStatusPending {\n\t\ttime.Sleep(2 * time.Second)\n\t}\n\n\tif resp.CopyStatus() == azblob.CopyStatusSuccess {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"copy failed ERROR[%s]\", resp.ErrorCode())\n}", "func copyFile(t *testing.T, source string, destination string) {\n\tcontents, err := ioutil.ReadFile(source)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to read file %s due to error: %v\", source, err)\n\t}\n\n\twriteFileWithSamePermissions(t, source, destination, contents)\n}", "func CopyFile(source string, dest string) (err error) {\n\tsf, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer sf.Close()\n\tdf, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer df.Close()\n\t_, err = io.Copy(df, sf)\n\tif err == nil {\n\t\tsi, err := os.Stat(source)\n\t\tif err != nil {\n\t\t\terr = os.Chmod(dest, si.Mode())\n\t\t}\n\n\t}\n\n\treturn\n}", "func CopyFile(srcFile string, destFile string) { //TODO move this to our imported copy repo\n\tfileContents, err := os.Open(srcFile)\n\tdefer fileContents.Close()\n\tif err != nil {\n\t\tLogger.WithFields(logrus.Fields{\"File\": srcFile, \"Error\": err}).Error(\"Cannot open source file\")\n\t}\n\toutfileContents, err := os.Create(destFile)\n\tdefer outfileContents.Close()\n\tif err != nil {\n\t\tLogger.WithFields(logrus.Fields{\"File\": destFile, \"Error\": err}).Error(\"Cannot open destination file\")\n\t}\n\t_, err = io.Copy(outfileContents, fileContents)\n\tif err != nil {\n\t\tLogger.WithFields(logrus.Fields{\"Source File\": srcFile, \"Destination File\": destFile, \"Error\": err}).Error(\"Cannot write contents to destination file\")\n\t}\n\n}", "func CopyFile(src string, dest string) error {\n\tsrcFile, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer srcFile.Close()\n\n\tdestFile, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer destFile.Close()\n\n\t_, err = io.Copy(destFile, srcFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = destFile.Sync()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CopyFile(origin, destination string) {\n\tin, err := os.Open(origin)\n\thandleError(err)\n\tdefer closeFile(in)\n\tout, err := os.Create(destination)\n\thandleError(err)\n\tdefer closeFile(out)\n\n\t_, err = io.Copy(in, out)\n\thandleError(err)\n\t// flush io buffer to output file\n\terr = out.Sync()\n\thandleError(err)\n}", "func CopyFile(src string, dst string) {\n\n\tlog.Debug(\"Copying from \" + src + \" -> \" + dst)\n\n\tbytesRead, errSrc := os.ReadFile(src)\n\n\tif errSrc != nil {\n\t\tlog.Fatal(\"Error: \" + errSrc.Error() + \".\")\n\t}\n\terrDst := os.WriteFile(dst, bytesRead, 0644)\n\tif errDst != nil {\n\t\tlog.Fatal(\"Error: \" + errDst.Error() + \".\")\n\t}\n\n}", "func CopyFile(sourceFile string, destinationFile string) error {\n\tcontent, err := ioutil.ReadFile(sourceFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read source file %s: %v\", sourceFile, err)\n\t}\n\terr = ioutil.WriteFile(destinationFile, content, 0666)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write destination file %s: %v\", destinationFile, err)\n\t}\n\treturn nil\n}", "func copyFile(src, dst string) error {\n\tvar err error\n\tvar srcfd *os.File\n\tvar dstfd *os.File\n\tvar srcinfo os.FileInfo\n\n\tif srcfd, err = os.Open(src); err != nil {\n\t\treturn err\n\t}\n\tdefer srcfd.Close()\n\n\tif dstfd, err = os.Create(dst); err != nil {\n\t\treturn err\n\t}\n\tdefer dstfd.Close()\n\n\tif _, err = io.Copy(dstfd, srcfd); err != nil {\n\t\treturn err\n\t}\n\tif srcinfo, err = os.Stat(src); err != nil {\n\t\treturn err\n\t}\n\treturn os.Chmod(dst, srcinfo.Mode())\n}", "func copyFile(source string, dest string) error {\n\tln, err := os.Readlink(source)\n\tif err == nil {\n\t\treturn os.Symlink(ln, dest)\n\t}\n\ts, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer s.Close()\n\n\td, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer d.Close()\n\n\t_, err = io.Copy(d, s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsi, err := os.Stat(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chmod(dest, si.Mode())\n\n\treturn err\n}", "func CopyFile(t testing.TB, sourceFile string, destinationFile string) {\n\tt.Helper()\n\n\tsrc, err := os.Open(sourceFile)\n\trequire.NoError(t, err, \"Failed to open source file: %s\")\n\t//nolint:errcheck\n\tdefer src.Close()\n\n\tdst, err := os.OpenFile(destinationFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o755)\n\trequire.NoError(t, err, \"Failed to open destination file: %s\", destinationFile)\n\t//nolint:errcheck\n\tdefer dst.Close()\n\n\t_, err = io.Copy(dst, src)\n\trequire.NoError(t, err, \"Failed to copy file: %s\", sourceFile)\n}", "func CopyFile(source, dest string) error {\n\tinput, err := ioutil.ReadFile(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(dest, input, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CopyFile(dest, src string) error {\n\ts, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer s.Close()\n\n\td, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := io.Copy(d, s); err != nil {\n\t\td.Close()\n\t\treturn err\n\t}\n\n\treturn d.Close()\n}", "func (e *BackupEnv) CopyFile(source string, dest string) (err error, backedByte int64) {\n sourcefile, err := os.Open(source)\n if err != nil {\n return err, 0\n }\n\n defer sourcefile.Close()\n\n var destfile io.Writer\n if (e.Options.Compress) {\n dest += \".lz4\"\n dfile, err := os.Create(dest)\n if err != nil {\n return err, 0\n }\n defer dfile.Close()\n destfile = lz4.NewWriter(dfile)\n } else {\n dfile, err := os.Create(dest)\n destfile = dfile\n if err != nil {\n return err, 0\n }\n defer dfile.Close()\n }\n\n _, err = io.Copy(destfile, sourcefile)\n if err != nil {\n return err, 0\n }\n\n sourceinfo, err := os.Stat(source);\n if err != nil {\n return err, 0\n }\n\n return nil, sourceinfo.Size();\n}", "func CopyFile(srcFile, destFile string) error {\n\tif output, err := exec.Command(\"cp\", \"-f\", srcFile, destFile).CombinedOutput(); err != nil {\n\t\tstderr := strings.TrimSpace(string(output))\n\t\treturn fmt.Errorf(\"unable to copy file from %s -> %s (%s): %v\", srcFile, destFile, stderr, err)\n\t}\n\treturn nil\n}", "func CopyFile(from string, to string) error {\n\tff, err := os.Open(from)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttf, err := os.OpenFile(to, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err == nil {\n\t\tff.Close()\n\t\treturn err\n\t}\n\t_, err = io.CopyBuffer(tf, ff, make([]byte, 4096))\n\tif err1 := ff.Close(); err == nil {\n\t\terr = err1\n\t}\n\tif err1 := tf.Close(); err == nil {\n\t\terr = err1\n\t}\n\treturn err\n}", "func CopyFile(dst, src string) {\n\tfo, err := os.Create(dst)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer fo.Close()\n\n\tfi, err := os.Open(src)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer fi.Close()\n\n\tif _, err = io.Copy(fo, fi); err != nil {\n\t\tpanic(err)\n\t}\n}", "func CopyFile(src string, dst string) {\n\tinput, err := ioutil.ReadFile(src)\n\tCheck(err)\n\n\terr = ioutil.WriteFile(dst, input, 0644)\n\tCheck(err)\n}", "func CopyFile(src, to string) {\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to read %s: %v\\n\", src, err)\n\t\tos.Exit(1)\n\t}\n\tdefer in.Close()\n\tfile, err := os.Create(to)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to create %s: %v\\n\", to, err)\n\t\tos.Exit(1)\n\t}\n\tdefer file.Close()\n\n\t_, err = io.Copy(file, in)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to copy %s to %s: %v\\n\", src, to, err)\n\t\tos.Exit(1)\n\t}\n}", "func copyFile(dst, src string) (err error) {\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer in.Close()\n\n\tout, err := os.Create(dst)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\tif e := out.Close(); e != nil {\n\t\t\terr = e\n\t\t}\n\t}()\n\n\t_, err = io.Copy(out, in)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = out.Sync()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsi, err := os.Stat(src)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = os.Chmod(dst, si.Mode())\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c APIClient) CopyFile(srcRepo, srcCommit, srcPath, dstRepo, dstCommit, dstPath string, overwrite bool) error {\n\tif _, err := c.PfsAPIClient.CopyFile(c.Ctx(),\n\t\t&pfs.CopyFileRequest{\n\t\t\tSrc: NewFile(srcRepo, srcCommit, srcPath),\n\t\t\tDst: NewFile(dstRepo, dstCommit, dstPath),\n\t\t\tOverwrite: overwrite,\n\t\t}); err != nil {\n\t\treturn grpcutil.ScrubGRPC(err)\n\t}\n\treturn nil\n}", "func CopyFile(src, dst string) (err error) {\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer in.Close()\n\tout, err := os.Create(dst)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\tcerr := out.Close()\n\t\tif err == nil {\n\t\t\terr = cerr\n\t\t}\n\t}()\n\tif _, err = io.Copy(out, in); err != nil {\n\t\treturn\n\t}\n\terr = out.Sync()\n\treturn\n}", "func FileCopy(src, dst string) error {\n\tfsrc, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fsrc.Close()\n\n\tfi, err := fsrc.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfdst, err := os.OpenFile(dst, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, fi.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(fdst, fsrc)\n\treturn nonil(err, fdst.Sync(), fdst.Close())\n}", "func fileCopy(a, b string) error {\n\tsFile, err := os.Open(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer sFile.Close()\n\n\teFile, err := os.Create(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer eFile.Close()\n\n\t_, err = io.Copy(eFile, sFile) // first var shows number of bytes\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func CopyFile(src, dst string) error {\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer in.Close()\n\n\tout, err := os.Create(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t_, err = io.Copy(out, in)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn out.Close()\n}", "func CopyFile(fileName string, destPath string) error {\n\toriFile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdestFile, err := os.Create(destPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbytesWritten, err := io.Copy(destFile, oriFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Bytes copied: \", bytesWritten)\n\n\toriFile.Close()\n\tdestFile.Close()\n\n\treturn nil\n}", "func (s *SSHRunner) Copy(f assets.CopyableFile) error {\n\tdst := path.Join(path.Join(f.GetTargetDir(), f.GetTargetName()))\n\n\t// For small files, don't bother risking being wrong for no performance benefit\n\tif f.GetLength() > 2048 {\n\t\texists, err := fileExists(s, f, dst)\n\t\tif err != nil {\n\t\t\tklog.Infof(\"existence check for %s: %v\", dst, err)\n\t\t}\n\n\t\tif exists {\n\t\t\tklog.Infof(\"copy: skipping %s (exists)\", dst)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tsrc := f.GetSourcePath()\n\tklog.Infof(\"scp %s --> %s (%d bytes)\", src, dst, f.GetLength())\n\tif f.GetLength() == 0 {\n\t\tklog.Warningf(\"0 byte asset: %+v\", f)\n\t}\n\n\tsess, err := s.session()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"NewSession\")\n\t}\n\tdefer func() {\n\t\tif err := sess.Close(); err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tklog.Errorf(\"session close: %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tw, err := sess.StdinPipe()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"StdinPipe\")\n\t}\n\t// The scpcmd below *should not* return until all data is copied and the\n\t// StdinPipe is closed. But let's use errgroup to make it explicit.\n\tvar g errgroup.Group\n\tvar copied int64\n\n\tg.Go(func() error {\n\t\tdefer w.Close()\n\t\theader := fmt.Sprintf(\"C%s %d %s\\n\", f.GetPermissions(), f.GetLength(), f.GetTargetName())\n\t\tfmt.Fprint(w, header)\n\t\tif f.GetLength() == 0 {\n\t\t\tklog.Warningf(\"asked to copy a 0 byte asset: %+v\", f)\n\t\t\tfmt.Fprint(w, \"\\x00\")\n\t\t\treturn nil\n\t\t}\n\n\t\tcopied, err = io.Copy(w, f)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"io.Copy\")\n\t\t}\n\t\tif copied != int64(f.GetLength()) {\n\t\t\treturn fmt.Errorf(\"%s: expected to copy %d bytes, but copied %d instead\", f.GetTargetName(), f.GetLength(), copied)\n\t\t}\n\t\tfmt.Fprint(w, \"\\x00\")\n\t\treturn nil\n\t})\n\n\tscp := fmt.Sprintf(\"sudo test -d %s && sudo scp -t %s\", f.GetTargetDir(), f.GetTargetDir())\n\tmtime, err := f.GetModTime()\n\tif err != nil {\n\t\tklog.Infof(\"error getting modtime for %s: %v\", dst, err)\n\t} else if mtime != (time.Time{}) {\n\t\tscp += fmt.Sprintf(\" && sudo touch -d \\\"%s\\\" %s\", mtime.Format(layout), dst)\n\t}\n\tout, err := sess.CombinedOutput(scp)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %s\\noutput: %s\", scp, err, out)\n\t}\n\treturn g.Wait()\n}", "func (app *Application) copyFile (file os.FileInfo, source, destination string) error {\n\n fileData, _ := ioutil.ReadFile (source)\n\n // detecting template and processing it\n if strings.HasSuffix (source, \".go.template\") {\n var buffer bytes.Buffer\n tmpl := template.Must (template.New (\"app\").Parse (string(fileData)))\n tmpl.Execute (&buffer, app)\n\n // overwriting file contents with data from processed template\n fileData = buffer.Bytes ()\n\n // removing tmp suffixes from file names\n destination = strings.Replace(destination, \".template\", \"\", -1)\n }\n\n if err := ioutil.WriteFile (destination, fileData, file.Mode ()); err == nil {\n fmt.Println(green, \" create:\", reset, destination)\n } else {\n return err\n }\n return nil\n}", "func CopyFile(src, dst string) (err error) {\n\tsrcFile, err := os.Open(src)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer srcFile.Close()\n\n\tdstFile, err := os.Create(dst)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\tcloseError := dstFile.Close()\n\t\tif err == nil {\n\t\t\terr = closeError\n\t\t}\n\t}()\n\n\t_, err = io.Copy(dstFile, srcFile)\n\tif err != nil {\n\t\t// TODO: Not sure how to add test coverage for this line\n\t\treturn\n\t}\n\terr = dstFile.Sync()\n\treturn\n}", "func CopyFile(src, dst string) error {\n\tvar in, out *os.File\n\tvar err error\n\tin, err = os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err = in.Close(); err != nil {\n\t\t\tglog.Errorf(\"Error: close file from %s, %s\", src, err)\n\t\t}\n\t}()\n\tout, err = os.Create(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err = out.Close(); err != nil {\n\t\t\tglog.Errorf(\"Error: close file from %s, %s\", dst, err)\n\t\t}\n\t}()\n\tif _, err = io.Copy(out, in); err != nil {\n\t\treturn err\n\t}\n\terr = out.Sync()\n\treturn err\n}", "func (f *Fs) CopyFile(src string, dst string) error {\n\tsrcFile, err := f.AferoFs.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer srcFile.Close()\n\n\tsrcInfo, err := srcFile.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdstFile, err := f.AferoFs.OpenFile(dst, os.O_RDWR|os.O_CREATE, srcInfo.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dstFile.Close()\n\n\tif _, err = io.Copy(dstFile, srcFile); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CopyFile(source string, dest string) error {\n\tln, err := os.Readlink(source)\n\tif err == nil {\n\t\treturn os.Symlink(ln, dest)\n\t}\n\ts, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer s.Close()\n\n\td, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer d.Close()\n\n\t_, err = io.Copy(d, s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsi, err := os.Stat(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chmod(dest, si.Mode())\n\n\treturn err\n}", "func CopyFile(srcPath, dstPath string) error {\n\tsrcFile, err := os.OpenFile(srcPath, FsRFlags, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer srcFile.Close()\n\n\t// create and open file\n\tdstFile, err := QuickOpenFile(dstPath, FsCWTFlags)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dstFile.Close()\n\n\t_, err = io.Copy(dstFile, srcFile)\n\treturn err\n}", "func copyFile(filename string, newfilename string) {\n of, err := os.Open(filename)\n u.ErrNil(err, \"Can't Open old file\")\n defer of.Close()\n \n nf, err2 := os.Create(newfilename)\n u.ErrNil(err2, \"Can't create new file\")\n defer nf.Close()\n \n bw, err3 := io.Copy(nf, of)\n u.ErrNil(err3, \"Can't copy from old to new\")\n log.Printf(\"Bytes written: %d\\n\", bw)\n \n if err4 := nf.Sync(); err4 != nil {\n log.Fatalln(err4)\n }\n log.Printf(\"Done copying from %s to %s\\n\", filename, newfilename)\n\n}", "func CopyFile(src, dst string) error {\n\tvar err error\n\tvar srcfd *os.File\n\tvar dstfd *os.File\n\tvar srcinfo os.FileInfo\n\n\tif srcfd, err = os.Open(src); err != nil {\n\t\treturn err\n\t}\n\tdefer srcfd.Close()\n\n\tif dstfd, err = os.Create(dst); err != nil {\n\t\treturn err\n\t}\n\tdefer dstfd.Close()\n\n\tif _, err = io.Copy(dstfd, srcfd); err != nil {\n\t\treturn err\n\t}\n\tif srcinfo, err = os.Stat(src); err != nil {\n\t\treturn err\n\t}\n\treturn os.Chmod(dst, srcinfo.Mode())\n}", "func CopyFile(src, dst string) error {\n\tvar err error\n\tvar srcfd *os.File\n\tvar dstfd *os.File\n\tvar srcinfo os.FileInfo\n\n\tif srcfd, err = os.Open(src); err != nil {\n\t\treturn err\n\t}\n\tdefer srcfd.Close()\n\n\tif dstfd, err = os.Create(dst); err != nil {\n\t\treturn err\n\t}\n\tdefer dstfd.Close()\n\n\tif _, err = io.Copy(dstfd, srcfd); err != nil {\n\t\treturn err\n\t}\n\tif srcinfo, err = os.Stat(src); err != nil {\n\t\treturn err\n\t}\n\treturn os.Chmod(dst, srcinfo.Mode())\n}", "func copyFileExternal(t *testing.T, sourceFile, destinationFile string) {\n\tt.Helper()\n\tvar cpCmd string\n\tvar cpArgs []string\n\tif os.PathSeparator == '\\\\' {\n\t\t// Hacky way to check that this is Windows\n\t\tcpCmd = \"cmd\"\n\t\tcpArgs = []string{\n\t\t\t\"/C\",\n\t\t\t\"start\",\n\t\t\t\"/B\",\n\t\t\t\"cmd\",\n\t\t\t\"/C\",\n\t\t\t\"copy\",\n\t\t\tfilepath.FromSlash(sourceFile),\n\t\t\tfilepath.FromSlash(destinationFile)}\n\t} else {\n\t\t// This is linux (or mac)\n\t\tcpCmd = \"cp\"\n\t\tcpArgs = []string{\n\t\t\tsourceFile,\n\t\t\tdestinationFile}\n\t}\n\tcmd := exec.Command(cpCmd, cpArgs...)\n\terr := cmd.Run()\n\tassertExpectNoErr(t, \"\", err)\n}", "func CopyFile(dstName, srcName string) error {\n\tsrc, err := os.Open(srcName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer src.Close()\n\n\tdst, err := os.Create(dstName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dst.Close()\n\n\t_, err = io.Copy(dst, src)\n\treturn err\n}", "func CopyFile(srcFilePath, dstFilePath string) (err error) {\n var src *os.File\n if src, err = os.Open(srcFilePath); src != nil {\n if err == nil {\n err = SaveTo(src, dstFilePath)\n }\n _ = src.Close()\n }\n return\n}", "func CopyFile(pathA, pathB string) {\n\tfile, err := ioutil.ReadFile(pathA)\n\tMust(err)\n\n\terr = os.Remove(pathB)\n\tif err != nil && !os.IsNotExist(err) {\n\t\tMust(err)\n\t}\n\n\tNewFile(pathB, string(file))\n}", "func CopyFile(src, dst string) error {\n\tfilePath := filepath.Clean(src)\n\tin, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error opening file: %v : %w\", src, err)\n\t}\n\tdefer func() {\n\t\terr := in.Close()\n\t\tif err != nil {\n\t\t\tlog.Error().Err(err).Str(\"filename\", filePath).Msg(\"error closing the file\")\n\t\t}\n\t}()\n\n\t// DST FILE\n\tfilePath = filepath.Clean(dst)\n\tout, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating file: %v : %w\", src, err)\n\t}\n\tdefer func() {\n\t\terr := out.Close()\n\t\tif err != nil {\n\t\t\tlog.Error().Err(err).Str(\"filename\", filePath).Msg(\"error closing the file\")\n\t\t}\n\t}()\n\n\tif _, err = io.Copy(out, in); err != nil {\n\t\treturn fmt.Errorf(\"error copying %v to %v : %w\", src, dst, err)\n\t}\n\n\treturn nil\n}", "func (m *Minio) CopyFile(ctx context.Context, srcBucket, srcPath, destBucket, destPath string) error {\n\tsrc := minio.CopySrcOptions{\n\t\tBucket: srcBucket,\n\t\tObject: srcPath,\n\t}\n\t// Destination object\n\tdst := minio.CopyDestOptions{\n\t\tBucket: destBucket,\n\t\tObject: destPath,\n\t}\n\t// Copy object call\n\tif _, err := m.client.CopyObject(ctx, dst, src); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (client *Client) Copy(ctx context.Context, file File, bucket *storage.BucketHandle, remote string, trim bool) error {\n\tif bucket == nil {\n\t\treturn ErrorNilBucket\n\t}\n\n\tlocalFile, err := os.Open(file.FullPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open file %s, err: %q\", file.FullPath, err)\n\t}\n\tdefer func() {\n\t\tif err := localFile.Close(); err != nil {\n\t\t\tlog.Println(\"failed to close localfile\", \"err\", err)\n\t\t}\n\t}()\n\n\textension := strings.ToLower(path.Ext(file.FullPath))\n\tcontentType := mime.TypeByExtension(extension)\n\n\tfilePath := file.FullPath\n\tif trim {\n\t\tfilePath = file.PathTrimmed\n\t}\n\n\tobjectPath := path.Join(remote, filePath)\n\n\twc := bucket.Object(objectPath).NewWriter(ctx)\n\twc.ContentType = contentType\n\tdefer func() {\n\t\tif err := wc.Close(); err != nil {\n\t\t\tlog.Println(\"failed to close writer\", \"err\", err)\n\t\t}\n\t}()\n\n\tif _, err = io.Copy(wc, localFile); err != nil {\n\t\treturn fmt.Errorf(\"failed to copy to Cloud Storage: %w\", err)\n\t}\n\n\treturn nil\n}", "func copyFileTo(fromFn, toFn string) error {\n\tsfs, err := fs.New()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfrom, err := sfs.Open(fromFn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer from.Close()\n\n\tto, err := os.OpenFile(toFn, os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer to.Close()\n\n\t_, err = io.Copy(to, from)\n\treturn err\n}", "func copyFile(src string, srcMode os.FileMode, dst string) error {\n\tif fi, err := os.Stat(dst); err == nil && fi.IsDir() {\n\t\t// The destination is an existing folder, write the file into it.\n\t\t_, srcFileName := filepath.Split(src)\n\t\tdst = filepath.Join(dst, srcFileName)\n\t}\n\n\t// Open the source file.\n\tsrcFile, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer srcFile.Close()\n\n\t// Open the destination file.\n\tdstFile, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, srcMode)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dstFile.Close()\n\n\t// Write the file content.\n\tif _, err := io.Copy(dstFile, srcFile); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CopyFile(src string, dst string) error {\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer CheckClose(in)\n\tout, err := os.Create(dst)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create file %v, err: %v\", src, err)\n\t}\n\tdefer CheckClose(out)\n\t_, err = io.Copy(out, in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to copy file from %v to %v err: %v\", src, dst, err)\n\t}\n\n\terr = out.Sync()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsi, err := os.Stat(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chmod(dst, si.Mode())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to chmod file %v to mode %v\", dst, si.Mode())\n\t}\n\n\treturn nil\n}", "func S3CopyFile(input *s3.CopyObjectInput) error {\n\tsvc := s3.New(session.New())\n\tresult, err := svc.CopyObject(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase s3.ErrCodeObjectNotInActiveTierError:\n\t\t\t\tlog.Println(s3.ErrCodeObjectNotInActiveTierError, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tlog.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tlog.Println(err.Error())\n\t\t}\n\t\treturn nil\n\t}\n\tlog.Println(result)\n\treturn nil\n}", "func (sshConfig *SSHConfig) CopyFile(fileReader io.Reader, remotePath string, permissions string) error {\n\tcontentBytes, _ := ioutil.ReadAll(fileReader)\n\treturn sshConfig.CopyBytesToFile(contentBytes, remotePath, permissions)\n}", "func CopyFile(src, dst string) error {\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer in.Close()\n\n\tout, err := os.Create(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t_, err = io.Copy(out, in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Copy modes.\n\tf, err := os.Stat(src)\n\tif err == nil {\n\t\terr = os.Chmod(dst, f.Mode())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn out.Close()\n}", "func CopyFile(src string, dst string) (err error) {\n\n\tsourcefile, err := os.Open(src)\n\tfmt.Println(src + \" --->>> \" + dst)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tdefer sourcefile.Close()\n\n\tdestfile, err := os.Create(dst)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\t//копируем содержимое и проверяем коды ошибок\n\t_, err = io.Copy(destfile, sourcefile)\n\tif closeErr := destfile.Close(); err == nil {\n\t\t//если ошибки в io.Copy нет, то берем ошибку от destfile.Close(), если она была\n\t\terr = closeErr\n\t}\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tsourceinfo, err := os.Stat(src)\n\tif err == nil {\n\t\terr = os.Chmod(dst, sourceinfo.Mode())\n\t}\n\treturn err\n}", "func (t *testRunner) copyFile(src string) string {\n\tt.Helper()\n\treturn t.copyFileTo(src, filepath.Base(src))\n}", "func copyFile(src, dst string) error {\n\tvar err error\n\tvar sourceFD *os.File\n\tvar destFD *os.File\n\tvar srcInfo os.FileInfo\n\tvar srcDirInfo os.FileInfo\n\n\twskprint.PrintlnOpenWhiskVerbose(Flags.Verbose, \"Source File [\"+src+\"] is being copied to [\"+dst+\"]\")\n\n\t// open source file to read it from disk and defer to close the file\n\t// once this function is done executing\n\tif sourceFD, err = os.Open(src); err != nil {\n\t\treturn err\n\t}\n\tdefer sourceFD.Close()\n\n\t// running stat on Dir(src), Dir returns all but the last element of the src\n\t// this info is needed in case when a destination path has a directory structure which does not exist\n\tif srcDirInfo, err = os.Stat(filepath.Dir(src)); err != nil {\n\t\treturn err\n\t}\n\n\t// check if the parent directory exist before creating a destination file\n\t// create specified path along with creating any parent directory\n\t// e.g. when destination is greeting/common/utils.js and parent dir common\n\t// doesn't exist, its getting created here at greeting/common\n\tif _, err = os.Stat(filepath.Dir(dst)); os.IsNotExist(err) {\n\t\twskprint.PrintlnOpenWhiskVerbose(Flags.Verbose, \"Creating directory pattern [\"+filepath.Dir(dst)+\"] before creating destination file\")\n\t\tif err = os.MkdirAll(filepath.Dir(dst), srcDirInfo.Mode()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// create destination file before copying source content\n\t// defer closing the destination file until the function is done executing\n\tif destFD, err = os.Create(dst); err != nil {\n\t\treturn err\n\t}\n\tdefer destFD.Close()\n\n\t// now, actually copy the source file content into destination file\n\tif _, err = io.Copy(destFD, sourceFD); err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve the file mode bits of the source file\n\t// so that the bits can be set to the destination file\n\tif srcInfo, err = os.Stat(src); err != nil {\n\t\treturn err\n\t}\n\treturn os.Chmod(dst, srcInfo.Mode())\n}", "func CopyFile(src, dst string) (err error) {\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer in.Close()\n\n\tout, err := os.Create(dst)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif e := out.Close(); e != nil {\n\t\t\terr = e\n\t\t}\n\t}()\n\n\t_, err = io.Copy(out, in)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = out.Sync()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsi, err := os.Stat(src)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = os.Chmod(dst, si.Mode())\n\tif err != nil {\n\t\treturn\n\t}\n\t\n\tfmt.Print(\".\")\n\n\treturn\n}", "func (s *Slave) CopyFile(file string, destination string) chan error {\n\tch := make(chan error)\n\n\tgo func() {\n\t\trc, err := NewRemoteConnection(s)\n\t\tif err != nil {\n\t\t\tch <- err\n\t\t\treturn\n\t\t}\n\n\t\tresult := rc.CopyFile(file, destination)\n\t\tch <- result\n\t}()\n\n\treturn ch\n}", "func _file_copy(call otto.FunctionCall) otto.Value {\n\tsourcePath, _ := call.Argument(0).ToString()\n\tdestinationPath, _ := call.Argument(1).ToString()\n\n\t//check if destination exists and delete if so\n\tif fileExists(destinationPath) {\n\t\tif err := os.Remove(destinationPath); err != nil {\n\t\t\tjsThrow(call, err)\n\t\t}\n\t}\n\n\t//read source file\n\tin, err := os.Open(sourcePath)\n\tif err != nil {\n\t\tjsThrow(call, err)\n\t}\n\tdefer in.Close()\n\n\t//create destination file\n\tout, err := os.Create(destinationPath)\n\tif err != nil {\n\t\tjsThrow(call, err)\n\t}\n\tdefer out.Close()\n\n\t//copy contents of source to destination\n\t_, err = io.Copy(out, in)\n\t_ = out.Close()\n\tif err != nil {\n\t\tjsThrow(call, err)\n\t}\n\treturn otto.Value{}\n}", "func (h *fs) Copy(sourcePath string, targetPath string) error {\n\tif _, err := os.Stat(sourcePath); err != nil {\n\t\treturn err\n\t}\n\n\tinfo, err := os.Stat(targetPath)\n\n\tif err != nil || (info != nil && !info.IsDir()) {\n\t\terr = os.Mkdir(targetPath, 0700)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttargetPath = filepath.Join(targetPath, filepath.Base(sourcePath))\n\t}\n\t// TODO: Use the appropriate command for Windows\n\tglog.V(5).Infof(\"cp -a %s %s\", sourcePath, targetPath)\n\treturn h.runner.Run(\"cp\", \"-a\", sourcePath, targetPath)\n}", "func CopyFile(dstName, srcName string) (written int64, err error) {\n src, err := os.Open(srcName)\n if err != nil {\n return\n }\n defer src.Close()\n\n dst, err := os.Create(dstName)\n if err != nil {\n return\n }\n defer dst.Close()\n\n return io.Copy(dst, src)\n}", "func CopyFile(src, dst string) error {\r\n\tsrcFile, err := os.Open(src)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\tdefer srcFile.Close()\r\n\tdstFile, err := os.Create(dst)\r\n\tif err != nil {\r\n\t\treturn nil\r\n\t}\r\n\tdefer dstFile.Close()\r\n\t_, err = io.Copy(dstFile, srcFile) // why is this (dst, src) instead of (src, dst)???\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\treturn nil\r\n}", "func Copyfile(dst, src string) error {\n\ts, err := os.Open(src)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// No need to check errors on read only file, we already got everything\n\t// we need from the filesystem, so nothing can go wrong now.\n\tdefer s.Close()\n\n\td, err := os.Create(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := io.Copy(d, s); err != nil {\n\t\td.Close()\n\t\treturn err\n\t}\n\treturn d.Close()\n}", "func copyFileContents(src, dst string) (err error) {\n\tcmd := exec.Command(\"cp\", src, dst)\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\treturn cmd.Wait()\n}", "func ScpFileFrom(t testing.TestingT, host Host, remotePath string, localDestination *os.File, useSudo bool) {\n\terr := ScpFileFromE(t, host, remotePath, localDestination, useSudo)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func CopyFile(source string, dest string, uid, gid int) error {\n\t// Open the source file.\n\tsrc, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer src.Close()\n\n\t// Makes the directory needed to create the dst\n\t// file.\n\terr = os.MkdirAll(filepath.Dir(dest), cnst.PERM_DEFAULT)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Create the destination file.\n\tdst, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dst.Close()\n\n\t// Copy the contents of the file.\n\t_, err = io.Copy(dst, src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Copy the mode if the user can't\n\t// open the file.\n\tinfo, err := os.Stat(source)\n\tif err != nil {\n\t\terr = os.Chmod(dest, info.Mode())\n\t\tModPermission(uid, gid, dest)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (t *testRunner) copyFileTo(src, name string) string {\n\tt.Helper()\n\n\tnewf, err := os.CreateTemp(t.dir, \"\")\n\trequire.NoError(t, err)\n\n\tf, err := os.Open(src)\n\trequire.NoError(t, err)\n\n\t_, err = io.Copy(newf, f)\n\trequire.NoError(t, err)\n\trequire.NoError(t, f.Close())\n\trequire.NoError(t, newf.Close())\n\n\tdst := filepath.Join(t.dir, name)\n\terr = os.Rename(newf.Name(), dst)\n\trequire.NoError(t, err)\n\n\treturn dst\n}", "func (sshConfig *SSHConfig) CopyFromFile(file os.File, remotePath string, permissions string) error {\n\tstat, err := file.Stat()\n\tif err == nil {\n\t\terr = sshConfig.Copy(&file, remotePath, permissions, stat.Size())\n\t}\n\treturn err\n}", "func (r Runner) ScpFile(deploymentName, source, target string) error {\n\toutput, err := r.boshExec(\"-d\", deploymentName, \"scp\", source, target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to SCP file from %s to %s (%s): %w\", source, target, output, err)\n\t}\n\treturn nil\n}", "func copyFileFromRemote(t testing.TestingT, sshSession *SshSession, file *os.File, remotePath string, useSudo bool) error {\n\tlogger.Logf(t, \"Running command %s on %s@%s\", sshSession.Options.Command, sshSession.Options.Username, sshSession.Options.Address)\n\tif err := setUpSSHClient(sshSession); err != nil {\n\t\treturn err\n\t}\n\n\tif err := setUpSSHSession(sshSession); err != nil {\n\t\treturn err\n\t}\n\n\tcommand := fmt.Sprintf(\"dd if=%s\", remotePath)\n\tif useSudo {\n\t\tcommand = fmt.Sprintf(\"sudo %s\", command)\n\t}\n\n\tr, err := sshSession.Session.Output(command)\n\tif err != nil {\n\t\tfmt.Printf(\"error reading from remote stdout: %s\", err)\n\t}\n\tdefer sshSession.Session.Close()\n\t//write to local file\n\t_, err = file.Write(r)\n\n\treturn err\n}", "func CopyFile(originalFile io.Reader, fileName string) error {\n\treturn instance.copyFile(originalFile, fileName)\n}", "func copyFile(src, dst string) error {\n\ts, err := os.Stat(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !s.Mode().IsRegular() {\n\t\treturn fmt.Errorf(\"%s is not a regular file\", src)\n\t}\n\td, err := os.Stat(dst)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif s.Size() == d.Size() {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn os.Link(src, dst)\n\n}", "func CopyFile(src, dst string, overwrite bool) error {\n\tsrcFile, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer srcFile.Close()\n\n\tif !overwrite {\n\t\t// check if the file exists, if it does then return an error\n\t\t_, err := os.Stat(dst)\n\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\treturn errors.New(\"won't overwrite destination file\")\n\t\t}\n\t}\n\n\tdstFile, err := os.Create(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dstFile.Close()\n\n\t_, err = io.Copy(dstFile, srcFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// flush the buffer\n\terr = dstFile.Sync()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// copy file permissions\n\tsrcInfo, err := os.Stat(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.Chmod(dst, srcInfo.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func CopyFile(dst, src string, info os.FileInfo) error {\n\tif err := os.MkdirAll(filepath.Dir(dst), info.Mode()); err != nil {\n\t\t\treturn err\n\t}\n\n\tfdst, err := os.Create(dst)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer fdst.Close()\n\n\tif err = os.Chmod(fdst.Name(), info.Mode()); err != nil {\n\t\treturn err\n\t}\n\n\tfsrc, err := os.Open(src)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer fsrc.Close()\n\n\t_, err = io.Copy(fdst, fsrc)\n\n\treturn err\n}", "func copyFile(src, dst string) (err error) {\n\tsfi, err := os.Stat(src)\n\tif err != nil {\n\t\treturn\n\t}\n\tif !sfi.Mode().IsRegular() {\n\t\t// cannot copy non-regular files (e.g., directories,\n\t\t// symlinks, devices, etc.)\n\t\treturn fmt.Errorf(\"CopyFile: non-regular source file %s (%q)\", sfi.Name(), sfi.Mode().String())\n\t}\n\tdfi, err := os.Stat(dst)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tif !(dfi.Mode().IsRegular()) {\n\t\t\treturn fmt.Errorf(\"CopyFile: non-regular destination file %s (%q)\", dfi.Name(), dfi.Mode().String())\n\t\t}\n\t\tif os.SameFile(sfi, dfi) {\n\t\t\treturn\n\t\t}\n\t}\n\tif err = os.Link(src, dst); err == nil {\n\t\treturn\n\t}\n\terr = copyFileContents(src, dst)\n\treturn\n}", "func copyFile(src, dst string) (err error) {\n\tsfi, err := os.Stat(src)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif !sfi.Mode().IsRegular() {\n\t\t// cannot copy non-regular files (e.g., directories,\n\t\t// symlinks, devices, etc.)\n\t\treturn fmt.Errorf(\"CopyFile: non-regular source file %s (%q)\", sfi.Name(), sfi.Mode().String())\n\t}\n\n\tdfi, err := os.Stat(dst)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tif !(dfi.Mode().IsRegular()) {\n\t\t\treturn fmt.Errorf(\"CopyFile: non-regular destination file %s (%q)\", dfi.Name(), dfi.Mode().String())\n\t\t}\n\t\tif os.SameFile(sfi, dfi) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif err = os.Link(src, dst); err == nil {\n\t\treturn\n\t}\n\n\terr = copyFileContents(src, dst)\n\treturn\n}", "func (gl *GuluFile) CopyFile(source, dest string) (err error) {\n\treturn gl.copyFile(source, dest, true)\n}", "func copyBlobFile(src io.Reader, dstPath string) error {\n\tlogrus.Debugf(\"copying blob to %s\", dstPath)\n\tif err := os.MkdirAll(filepath.Dir(dstPath), os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\tdst, err := os.OpenFile(dstPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0666)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating blob file: %v\", err)\n\t}\n\tdefer dst.Close()\n\tif _, err := io.Copy(dst, src); err != nil {\n\t\treturn fmt.Errorf(\"error copying blob %q: %v\", filepath.Base(dstPath), err)\n\t}\n\treturn nil\n}", "func CopyFile(dst, src string, mode os.FileMode) error {\n\tfrom, err := os.Open(src)\n\tif err != nil {\n\t\treturn NewCopyError(src, dst, \"cannot open source file\", err)\n\t}\n\n\tdefer from.Close()\n\n\tto, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)\n\tif err != nil {\n\t\treturn NewCopyError(src, dst, \"cannot open destination file\", err)\n\t}\n\n\tdefer to.Close()\n\n\tif _, err = io.Copy(to, from); err != nil {\n\t\treturn NewCopyError(src, dst, \"cannot copy data\", err)\n\t}\n\n\treturn nil\n}", "func (r *Reader) CopyFile(src, dest string, dereference bool) error {\n\tif !dereference {\n\t\tfileInfo, err := r.rootFS.stat(src)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot stat source file: %v\", err)\n\t\t}\n\t\tif fileInfo.Mode() == os.ModeSymlink {\n\t\t\ttarget, err := r.rootFS.readLink(src)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"cannot read link target from source file: %v\", err)\n\t\t\t}\n\t\t\tos.Remove(dest)\n\t\t\terr = os.Symlink(target, dest)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"cannot create symbolic link: %v\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\tsrcReader, err := r.rootFS.fileReader(src)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot read source file: %v\", err)\n\t}\n\tdestFile, err := os.Create(dest)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot create destination file: %v\", err)\n\t}\n\t_, err = io.Copy(destFile, srcReader)\n\tdestFile.Close()\n\treturn err\n}", "func CopyFile(dst, src string) error {\n\tsrcfile, err := os.Open(src)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to open the source file at path %q Error: %q\", src, err)\n\t}\n\tdefer srcfile.Close()\n\n\tsrcfileinfo, err := srcfile.Stat()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to get size of the source file at path %q Error: %q\", src, err)\n\t}\n\tsrcfilesize := srcfileinfo.Size()\n\n\tdstfile, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, DefaultFilePermission)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create the destination file at path %q Error: %q\", dst, err)\n\t}\n\tdefer dstfile.Close()\n\n\twritten, err := io.Copy(dstfile, srcfile)\n\tif written != srcfilesize {\n\t\treturn fmt.Errorf(\"Failed to copy all the bytes from source %q to destination %q. %d out of %d bytes written. Error: %v\", src, dst, written, srcfilesize, err)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to copy from source %q to destination %q. Error: %q\", src, dst, err)\n\t}\n\n\treturn dstfile.Close()\n}", "func (suite *fileTestSuite) TestFileCopy() {\n\tdirName := suite.testPath + \"/test123\"\n\tfileName := suite.testPath + \"/test\"\n\tdstFileName := dirName + \"/test_copy.txt\"\n\n\terr := os.Mkdir(dirName, 0777)\n\tsuite.Equal(nil, err)\n\n\tsrcFile, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0777)\n\tsuite.Equal(nil, err)\n\tdefer srcFile.Close()\n\n\tdstFile, err := os.Create(dstFileName)\n\tsuite.Equal(nil, err)\n\tdefer dstFile.Close()\n\n\t_, err = io.Copy(srcFile, dstFile)\n\tsuite.Equal(nil, err)\n\tdstFile.Close()\n\n\tsuite.fileTestCleanup([]string{dirName})\n}", "func copySampleFile(src, dest string) error {\n\tsourceFileStat, err := os.Stat(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !sourceFileStat.Mode().IsRegular() {\n\t\treturn fmt.Errorf(\"%s is not a regular file\", src)\n\t}\n\n\tsource, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer source.Close()\n\n\t// Create all parent directories if needed\n\tif err := os.MkdirAll(filepath.Dir(dest), 0700); err != nil {\n\t\treturn err\n\t}\n\n\tdestFile, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer destFile.Close()\n\n\t_, err = io.Copy(destFile, source)\n\n\treturn err\n}", "func CopyFile(oldFile, newFile string) error {\n\toldf, err := os.Open(oldFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer oldf.Close()\n\tstat, err := oldf.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\ttmpFile := newFile + \".tmp\"\n\tnewf, err := os.OpenFile(tmpFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, stat.Mode()&os.ModePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer newf.Close()\n\t_, err = io.Copy(newf, oldf)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := newf.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Chtimes(tmpFile, stat.ModTime(), stat.ModTime()); err != nil {\n\t\treturn err\n\t}\n\treturn os.Rename(tmpFile, newFile)\n}", "func CopyFile(dstName, srcName string) (written int64, err error) {\r\n\tsrc, err := os.Open(srcName)\r\n\tif err != nil {\r\n\t\treturn\r\n\t}\r\n\tdefer src.Close()\r\n\r\n\tdst, err := os.Create(dstName)\r\n\tif err != nil {\r\n\t\treturn\r\n\t}\r\n\tdefer dst.Close()\r\n\r\n\treturn io.Copy(dst, src)\r\n}", "func copyFileOnS3(s3Endpoint string, awsAccessKeyID string, awsSecretAccessKey string, useSsl bool, awsRegion string, s3Location string, s3BucketName string, s3NewLocation string) error {\n\t// Create an instance of the Minio Client\n minioClient, err := minio.New(s3Endpoint, awsAccessKeyID, awsSecretAccessKey, useSsl)\n if err != nil {\n return err\n }\n\n\t// Prepare the copy object\n src := minio.NewSourceInfo(s3BucketName, s3BucketName, nil)\n dst, err := minio.NewDestinationInfo(s3BucketName, s3NewLocation, nil, nil)\n\n\t// Copy the object\n\terr = minioClient.CopyObject(dst, src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (f File) CopyFile(src string) (string, error) {\n\t// Filepath, file's location\n\tfp := path.Join(FileLoc, f.Title)\n\n\t// WriteFile writes teh file, and handle errors (To dry up the code)\n\treturn WriteFile(fp, src)\n}", "func (sshConfig *SSHConfig) CopyLocalFileToRemoteFile(localFilename, remoteFilename, permissions string) error {\n\tif expandedLocalFilename, err := Expand(localFilename); err == nil {\n\t\tlocalFilename = expandedLocalFilename\n\t} else {\n\t\treturn err\n\t}\n\tfile, err := os.Open(localFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\terr = sshConfig.CopyFromFile(*file, remoteFilename, permissions)\n\treturn err\n}", "func CopyFile(dstfile, srcfile string, key, iv []byte) error {\n\tr, err := os.Open(srcfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar w io.WriteCloser\n\tw, err = os.Create(dstfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw = gzip.NewWriter(w)\n\n\tdefer w.Close()\n\tc, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(cipher.StreamWriter{S: cipher.NewOFB(c, iv), W: w}, r)\n\treturn err\n}", "func CopyFile(src, dst string) (err error) {\n sfi, err := os.Stat(src)\n if err != nil {\n return\n }\n if !sfi.Mode().IsRegular() {\n // cannot copy non-regular files (e.g., directories,\n // symlinks, devices, etc.)\n return fmt.Errorf(\"CopyFile: non-regular source file %s (%q)\", sfi.Name(), sfi.Mode().String())\n }\n dfi, err := os.Stat(dst)\n if err != nil {\n if !os.IsNotExist(err) {\n return\n }\n } else {\n if !(dfi.Mode().IsRegular()) {\n return fmt.Errorf(\"CopyFile: non-regular destination file %s (%q)\", dfi.Name(), dfi.Mode().String())\n }\n if os.SameFile(sfi, dfi) {\n return\n }\n }\n if err = os.Link(src, dst); err == nil {\n return\n }\n err = copyFileContents(src, dst)\n return\n}", "func CopyFile(src, dst string) (w int64, err error) {\n\tsrcFile, err := os.Open(src)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn\n\t}\n\tdefer srcFile.Close()\n\n\tdstFile, err := os.Create(dst)\n\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn\n\t}\n\n\tdefer dstFile.Close()\n\n\treturn io.Copy(dstFile, srcFile)\n}", "func Copy_file(src, dst string) (err error) {\n\n\tsfi, err := os.Stat(src)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif !sfi.Mode().IsRegular() {\n\t\t// cannot copy non-regular files (e.g., directories,\n\t\t// symlinks, devices, etc.)\n\t\treturn fmt.Errorf(\"copy_file: non-regular source file %s (%q)\", sfi.Name(), sfi.Mode().String())\n\t}\n\n\tdfi, err := os.Stat(dst)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tif !(dfi.Mode().IsRegular()) {\n\t\t\treturn fmt.Errorf(\"copy_file: non-regular destination file %s (%q)\", dfi.Name(), dfi.Mode().String())\n\t\t}\n\t\tif os.SameFile(sfi, dfi) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif err = os.Link(src, dst); err == nil {\n\t\treturn\n\t}\n\n\terr = copy_file_contents(src, dst)\n\treturn\n}", "func Copy(src, dst string) error {\n\tFileioLogger.Debugf(\"Copy file from %s to %s\", src, dst)\n\tin, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer in.Close()\n\n\tout, err := os.Create(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\n\t_, err = io.Copy(out, in)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn out.Close()\n}", "func CopyFile(src string, dest string) (int64, error) {\n\tsrcStat, err := os.Stat(src)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif !srcStat.Mode().IsRegular() {\n\t\treturn 0, fmt.Errorf(\"%s is not a regular file\", src)\n\t}\n\tsrcFile, err := os.Open(src)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tsrcFile.Seek(0, 0)\n\tdefer srcFile.Close()\n\n\tdstStat, err := os.Stat(dest)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn 0, err\n\t\t}\n\t} else {\n\t\tif os.SameFile(srcStat, dstStat) {\n\t\t\treturn 0, nil\n\t\t}\n\t}\n\tdestFile, err := os.Create(dest)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer destFile.Close()\n\n\treturn io.Copy(destFile, srcFile)\n}" ]
[ "0.7557772", "0.7409318", "0.7393557", "0.73781157", "0.73433125", "0.72831494", "0.7226255", "0.7216362", "0.7208918", "0.7180465", "0.7172702", "0.7170716", "0.7159853", "0.71534693", "0.71534246", "0.7148969", "0.7106985", "0.7104262", "0.70982164", "0.7090298", "0.7056388", "0.7053208", "0.7045564", "0.7043269", "0.70358044", "0.70356065", "0.7034763", "0.70312375", "0.7019801", "0.7015824", "0.7014775", "0.6988934", "0.69783825", "0.6966352", "0.6954734", "0.6947732", "0.6938313", "0.6936345", "0.6933924", "0.69085836", "0.69013953", "0.6885155", "0.6853194", "0.6851657", "0.6840757", "0.6840757", "0.6839758", "0.6837192", "0.6828893", "0.6811629", "0.6806446", "0.6798916", "0.6792228", "0.678655", "0.6783095", "0.6782211", "0.67776245", "0.67755115", "0.6756653", "0.6755166", "0.6752447", "0.6751093", "0.6750725", "0.67228746", "0.67207843", "0.6679138", "0.6666728", "0.66630614", "0.66381186", "0.6637697", "0.66356623", "0.66202056", "0.6592113", "0.6591769", "0.65843487", "0.6578236", "0.6570378", "0.6569043", "0.6554347", "0.6547979", "0.6540979", "0.65385", "0.6517006", "0.648562", "0.6463142", "0.6445651", "0.64347833", "0.6433582", "0.643148", "0.64200896", "0.64159757", "0.64126045", "0.64009434", "0.63951325", "0.63916117", "0.6377536", "0.63772", "0.637717", "0.63636875", "0.6362643" ]
0.7871186
0